def _change_status(self, ref, status_slug, bitbucket_user):
        if Issue.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Issue
            statusClass = IssueStatus
        elif Task.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Task
            statusClass = TaskStatus
        elif UserStory.objects.filter(project=self.project, ref=ref).exists():
            modelClass = UserStory
            statusClass = UserStoryStatus
        else:
            raise ActionSyntaxException(
                _("The referenced element doesn't exist"))

        element = modelClass.objects.get(project=self.project, ref=ref)

        try:
            status = statusClass.objects.get(project=self.project,
                                             slug=status_slug)
        except statusClass.DoesNotExist:
            raise ActionSyntaxException(_("The status doesn't exist"))

        element.status = status
        element.save()

        snapshot = take_snapshot(
            element,
            comment=_("Status changed from BitBucket commit"),
            user=get_bitbucket_user(bitbucket_user))
        send_notifications(element, history=snapshot)
    def process_event(self):
        number = self.payload.get('issue', {}).get('id', None)
        subject = self.payload.get('issue', {}).get('title', None)

        bitbucket_url = self.payload.get('issue',
                                         {}).get('links',
                                                 {}).get('html',
                                                         {}).get('href', None)
        bitbucket_user_id = self.payload.get('actor',
                                             {}).get('user',
                                                     {}).get('uuid', None)
        bitbucket_user_name = self.payload.get('actor',
                                               {}).get('user', {}).get(
                                                   'username', None)
        bitbucket_user_url = self.payload.get('actor', {}).get('user', {}).get(
            'links', {}).get('html', {}).get('href')

        project_url = self.payload.get('repository',
                                       {}).get('links',
                                               {}).get('html',
                                                       {}).get('href', None)

        comment_message = self.payload.get('comment',
                                           {}).get('content',
                                                   {}).get('raw', '')
        comment_message = replace_bitbucket_references(project_url,
                                                       comment_message)

        user = get_bitbucket_user(bitbucket_user_id)

        if not all([comment_message, bitbucket_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(
            external_reference=["bitbucket", bitbucket_url])
        tasks = Task.objects.filter(
            external_reference=["bitbucket", bitbucket_url])
        uss = UserStory.objects.filter(
            external_reference=["bitbucket", bitbucket_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and bitbucket_user_name and bitbucket_user_url:
                comment = _(
                    "Comment by [@{bitbucket_user_name}]({bitbucket_user_url} "
                    "\"See @{bitbucket_user_name}'s BitBucket profile\") "
                    "from BitBucket.\nOrigin BitBucket issue: [bb#{number} - {subject}]({bitbucket_url} "
                    "\"Go to 'bb#{number} - {subject}'\")\n\n"
                    "{message}").format(
                        bitbucket_user_name=bitbucket_user_name,
                        bitbucket_user_url=bitbucket_user_url,
                        number=number,
                        subject=subject,
                        bitbucket_url=bitbucket_url,
                        message=comment_message)
            else:
                comment = _("Comment From BitBucket:\n\n{message}").format(
                    message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #3
0
    def process_event(self):
        if self.ignore():
            return

        data = self.get_data()

        if not all([data['subject'], data['url']]):
            raise ActionSyntaxException(_("Invalid issue information"))

        user = self.get_user(data['user_id'], self.platform_slug)

        issue = Issue.objects.create(
            project=self.project,
            subject=data['subject'],
            description=data['description'],
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=[self.platform_slug, data['url']],
            owner=user)
        take_snapshot(issue, user=user)

        comment = self.generate_new_issue_comment(**data)

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #4
0
    def process_event(self):
        if self.ignore():
            return

        data = self.get_data()

        if not all([data['subject'], data['url']]):
            raise ActionSyntaxException(_("Invalid issue information"))

        user = self.get_user(data['user_id'], self.platform_slug)

        issue = Issue.objects.create(
            project=self.project,
            subject=data['subject'],
            description=data['description'],
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=[self.platform_slug, data['url']],
            owner=user
        )
        take_snapshot(issue, user=user)

        comment = self.generate_new_issue_comment(**data)

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #5
0
    def process_event(self):
        if self.payload.get('action', None) != "opened":
            return

        subject = self.payload.get('issue', {}).get('title', None)
        description = self.payload.get('issue', {}).get('body', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user = self.payload.get('issue', {}).get('user', {}).get('id', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)

        if not all([subject, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=replace_github_references(project_url, description),
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['github', github_url],
            owner=get_github_user(github_user)
        )
        take_snapshot(issue, user=get_github_user(github_user))

        snapshot = take_snapshot(issue, comment=_("Created from GitHub"), user=get_github_user(github_user))
        send_notifications(issue, history=snapshot)
    def process_event(self):
        if self.payload.get('object_attributes', {}).get("action",
                                                         "") != "open":
            return

        subject = self.payload.get('object_attributes', {}).get('title', None)
        description = self.payload.get('object_attributes',
                                       {}).get('description', None)
        gitlab_reference = self.payload.get('object_attributes',
                                            {}).get('url', None)

        project_url = None
        if gitlab_reference:
            project_url = os.path.basename(os.path.basename(gitlab_reference))

        if not all([subject, gitlab_reference, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=replace_gitlab_references(project_url, description),
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['gitlab', gitlab_reference],
            owner=get_gitlab_user(None))
        take_snapshot(issue, user=get_gitlab_user(None))

        snapshot = take_snapshot(issue,
                                 comment=_("Created from GitLab"),
                                 user=get_gitlab_user(None))
        send_notifications(issue, history=snapshot)
Example #7
0
    def process_event(self):
        if self.payload.get('action', None) != "opened":
            return

        subject = self.payload.get('issue', {}).get('title', None)
        description = self.payload.get('issue', {}).get('body', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user = self.payload.get('issue', {}).get('user', {}).get('id', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)

        if not all([subject, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=replace_github_references(project_url, description),
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['github', github_url],
            owner=get_github_user(github_user)
        )
        take_snapshot(issue, user=get_github_user(github_user))

        snapshot = take_snapshot(issue, comment="Created from GitHub", user=get_github_user(github_user))
        send_notifications(issue, history=snapshot)
    def process_event(self):
        if self.ignore():
            return

        data = self.get_data()

        if not all([data["comment_message"], data["url"]]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        comment = self.generate_issue_comment_message(**data)

        issues = Issue.objects.filter(
            external_reference=[self.platform_slug, data["url"]]
        )
        tasks = Task.objects.filter(
            external_reference=[self.platform_slug, data["url"]]
        )
        uss = UserStory.objects.filter(
            external_reference=[self.platform_slug, data["url"]]
        )

        for item in list(issues) + list(tasks) + list(uss):
            snapshot = take_snapshot(
                item,
                comment=comment,
                user=self.get_user(data["user_id"], self.platform_slug),
            )
            send_notifications(item, history=snapshot)
    def _process_opened(self, number, subject, github_url, user, github_user_name, github_user_url, project_url, description):
        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=description,
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['github', github_url],
            owner=user
        )
        take_snapshot(issue, user=user)

        if number and subject and github_user_name and github_user_url:
            comment = _("Issue created by [@{github_user_name}]({github_user_url} "
                        "\"See @{github_user_name}'s GitHub profile\") "
                        "from GitHub.\nOrigin GitHub issue: [gh#{number} - {subject}]({github_url} "
                        "\"Go to 'gh#{number} - {subject}'\"):\n\n"
                        "{description}").format(github_user_name=github_user_name,
                                                github_user_url=github_user_url,
                                                number=number,
                                                subject=subject,
                                                github_url=github_url,
                                                description=description)
        else:
            comment = _("Issue created from GitHub.")

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #10
0
    def _change_status(self, ref, status_slug, gitlab_user):
        if Issue.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Issue
            statusClass = IssueStatus
        elif Task.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Task
            statusClass = TaskStatus
        elif UserStory.objects.filter(project=self.project, ref=ref).exists():
            modelClass = UserStory
            statusClass = UserStoryStatus
        else:
            raise ActionSyntaxException(_("The referenced element doesn't exist"))

        element = modelClass.objects.get(project=self.project, ref=ref)

        try:
            status = statusClass.objects.get(project=self.project, slug=status_slug)
        except statusClass.DoesNotExist:
            raise ActionSyntaxException(_("The status doesn't exist"))

        element.status = status
        element.save()

        snapshot = take_snapshot(element,
                                 comment=_("Status changed from GitLab commit"),
                                 user=get_gitlab_user(gitlab_user))
        send_notifications(element, history=snapshot)
Example #11
0
    def process_event(self):
        if self.payload.get('object_attributes', {}).get("action", "") != "open":
            return

        subject = self.payload.get('object_attributes', {}).get('title', None)
        description = self.payload.get('object_attributes', {}).get('description', None)
        gitlab_reference = self.payload.get('object_attributes', {}).get('url', None)

        project_url = None
        if gitlab_reference:
            project_url = os.path.basename(os.path.basename(gitlab_reference))

        if not all([subject, gitlab_reference, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=replace_gitlab_references(project_url, description),
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['gitlab', gitlab_reference],
            owner=get_gitlab_user(None)
        )
        take_snapshot(issue, user=get_gitlab_user(None))

        snapshot = take_snapshot(issue, comment=_("Created from GitLab"), user=get_gitlab_user(None))
        send_notifications(issue, history=snapshot)
Example #12
0
    def send_notifications(self, obj, history=None):
        """
        Shortcut method for resources with special save
        cases on actions methods that not uses standard
        `post_save` hook of drf resources.
        """
        if history is None:
            history = self.get_last_history()

        # If not history found, or it is empty. Do notthing.
        if not history:
            return

        if self._not_notify:
            return

        obj = self.get_object_for_snapshot(obj)

        # Process that analizes the corresponding diff and
        # some text fields for extract mentions and add them
        # to watchers before obtain a complete list of
        # notifiable users.
        services.analize_object_for_watchers(obj, history.comment, history.owner)

        # Get a complete list of notifiable users for current
        # object and send the change notification to them.
        services.send_notifications(obj, history=history)
Example #13
0
    def send_notifications(self, obj, history=None):
        """
        Shortcut method for resources with special save
        cases on actions methods that not uses standard
        `post_save` hook of drf resources.
        """
        if history is None:
            history = self.get_last_history()

        # If not history found, or it is empty. Do notthing.
        if not history:
            return

        if self._not_notify:
            return

        obj = self.get_object_for_snapshot(obj)

        # Process that analizes the corresponding diff and
        # some text fields for extract mentions and add them
        # to watchers before obtain a complete list of
        # notifiable users.
        services.analize_object_for_watchers(obj, history)

        # Get a complete list of notifiable users for current
        # object and send the change notification to them.
        services.send_notifications(obj, history=history)
Example #14
0
    def process_event(self):
        if self.payload.get('action', None) != "created":
            raise ActionSyntaxException(_("Invalid issue comment information"))

        github_url = self.payload.get('issue', {}).get('html_url', None)
        comment_message = self.payload.get('comment', {}).get('body', None)
        github_user = self.payload.get('sender', {}).get('id', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        comment_message = replace_github_references(project_url,
                                                    comment_message)

        if not all([comment_message, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(
            external_reference=["github", github_url])
        tasks = Task.objects.filter(external_reference=["github", github_url])
        uss = UserStory.objects.filter(
            external_reference=["github", github_url])

        for item in list(issues) + list(tasks) + list(uss):
            snapshot = take_snapshot(
                item,
                comment="From GitHub:\n\n{}".format(comment_message),
                user=get_github_user(github_user))
            send_notifications(item, history=snapshot)
Example #15
0
    def _process_commit(self, ref, status_slug, commit):
        element = get_element_from_ref(self.project, ref)
        status = get_status_from_slug(self.project, element, status_slug)
        element.status = status
        element.save()

        commit_id = commit.get("id", None)
        commit_url = commit.get("url", None)
        # @todo replace_gitlab_references()?
        commit_message = commit.get("message").strip()
        author_info = self.get_user_info_from_payload(commit)
        author_user = author_info.get('user')

        """ Do we care about pushed by vs authored by?
        if author_info.get('email') != self.pusher.get('email'):
            if self.pusher.get('user') is not None:
                user = self.pusher.get('user')
                pushed_by = _(" (Pushed by @{pusher_username})").format(
                    pusher_username=user.get_username()
                )
            else:
                pushed_by = _(" (Pushed by [{pusher_username}](mailto:{pusher_url}))").format(
                    pusher_username=self.pusher.get('name'),
                    pusher_url=self.pusher.get('email')
                )
        else:
            pushed_by = ""
        """

        if not all([commit_id, commit_url]):
            raise ActionSyntaxException(_("Invalid commit information"))

        # we can use a real user
        if author_user is not None and not author_user.is_system:
            comment = _(self.messages.get('native').get('push')).format(
                username=author_user.username,
                service_type=self.service_type,
                status=status.name,
                commit_id=commit_id[:7],
                commit_url=commit_url,
                commit_message=commit_message)

        # use what info we have
        elif "name" in author_info and "email" in author_info:
            comment = _(self.messages.get('system').get('push')).format(
                name=author_info.get("name'"),
                service_type=self.service_type,
                status=status.name,
                user_url=author_info.get("url"),
                commit_id=str(commit_id)[:7],
                commit_url=commit_url,
                commit_message=commit_message)

        snapshot = take_snapshot(element,
                                 comment=comment,
                                 user=author_user)
        send_notifications(element, history=snapshot)
Example #16
0
    def _process_status_changed(self, github_url, user, status):
        issues = Issue.objects.filter(external_reference=["github", github_url])

        for issue in list(issues):
            issue.status = IssueStatus.objects.get(project=self.project, slug=status)
            issue.save()

            snapshot = take_snapshot(issue,
                                    comment="Status changed from GitHub.",
                                    user=user)
            send_notifications(issue, history=snapshot)
Example #17
0
    def _process_edited(self, subject, github_url, user, description):
        issues = Issue.objects.filter(external_reference=["github", github_url])

        for issue in list(issues):
            issue.subject = subject
            issue.description = description
            issue.save()

            snapshot = take_snapshot(issue,
                                    comment="Edited from GitHub.",
                                    user=user)
            send_notifications(issue, history=snapshot)
Example #18
0
    def _change_status(self, ref, status_slug, github_user, commit):
        if Issue.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Issue
            statusClass = IssueStatus
        elif Task.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Task
            statusClass = TaskStatus
        elif UserStory.objects.filter(project=self.project, ref=ref).exists():
            modelClass = UserStory
            statusClass = UserStoryStatus
        else:
            raise ActionSyntaxException(
                _("The referenced element doesn't exist"))

        element = modelClass.objects.get(project=self.project, ref=ref)

        try:
            status = statusClass.objects.get(project=self.project,
                                             slug=status_slug)
        except statusClass.DoesNotExist:
            raise ActionSyntaxException(_("The status doesn't exist"))

        element.status = status
        element.save()

        github_user_id = github_user.get('id', None)
        github_user_name = github_user.get('login', None)
        github_user_url = github_user.get('html_url', None)
        commit_id = commit.get("id", None)
        commit_url = commit.get("url", None)
        commit_message = commit.get("message", None)

        if (github_user_id and github_user_name and github_user_url
                and commit_id and commit_url and commit_message):
            comment = _(
                "Status changed by [@{github_user_name}]({github_user_url} "
                "\"See @{github_user_name}'s GitHub profile\") "
                "from GitHub commit [#{commit_id}]({commit_url} "
                "\"See commit '#{commit_id}: {commit_message}'\").").format(
                    github_user_name=github_user_name,
                    github_user_url=github_user_url,
                    commit_id=commit_id[:7],
                    commit_url=commit_url,
                    commit_message=commit_message)

        else:
            comment = _("Status changed from GitHub commit.")

        snapshot = take_snapshot(element,
                                 comment=comment,
                                 user=get_github_user(github_user_id))
        send_notifications(element, history=snapshot)
Example #19
0
    def process_event(self):
        if self.payload.get('action', None) != "opened":
            return

        number = self.payload.get('issue', {}).get('number', None)
        subject = self.payload.get('issue', {}).get('title', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user_id = self.payload.get('issue', {}).get('user',
                                                           {}).get('id', None)
        github_user_name = self.payload.get('issue',
                                            {}).get('user',
                                                    {}).get('login', None)
        github_user_url = self.payload.get('issue',
                                           {}).get('user',
                                                   {}).get('html_url', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        description = self.payload.get('issue', {}).get('body', None)
        description = replace_github_references(project_url, description)

        user = get_github_user(github_user_id)

        if not all([subject, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(project=self.project,
                                     subject=subject,
                                     description=description,
                                     status=self.project.default_issue_status,
                                     type=self.project.default_issue_type,
                                     severity=self.project.default_severity,
                                     priority=self.project.default_priority,
                                     external_reference=['github', github_url],
                                     owner=user)
        take_snapshot(issue, user=user)

        if number and subject and github_user_name and github_user_url:
            comment = _(
                "Issue created by [@{github_user_name}]({github_user_url} "
                "\"See @{github_user_name}'s GitHub profile\") "
                "from GitHub.\nOrigin GitHub issue: [{number}: {subject}]({github_url} "
                "\"Go to '{number}: {subject}'\"):\n\n"
                "{description}").format(github_user_name=github_user_name,
                                        github_user_url=github_user_url,
                                        number=number,
                                        subject=subject,
                                        github_url=github_url,
                                        description=description)
        else:
            comment = _("Issue created from GitHub.")

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
    def process_event(self):
        if self.payload.get('object_attributes', {}).get(
                "noteable_type", None) != "Issue":
            return

        number = self.payload.get('issue', {}).get('iid', None)
        subject = self.payload.get('issue', {}).get('title', None)

        project_url = self.payload.get('repository', {}).get('homepage', None)

        gitlab_url = os.path.join(project_url, "issues", str(number))
        gitlab_user_name = self.payload.get('user', {}).get('username', None)
        gitlab_user_url = os.path.join(
            os.path.dirname(os.path.dirname(project_url)), "u",
            gitlab_user_name)

        comment_message = self.payload.get('object_attributes',
                                           {}).get('note', None)
        comment_message = replace_gitlab_references(project_url,
                                                    comment_message)

        user = get_gitlab_user(None)

        if not all([comment_message, gitlab_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(
            external_reference=["gitlab", gitlab_url])
        tasks = Task.objects.filter(external_reference=["gitlab", gitlab_url])
        uss = UserStory.objects.filter(
            external_reference=["gitlab", gitlab_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and gitlab_user_name and gitlab_user_url:
                comment = _(
                    "Comment by [@{gitlab_user_name}]({gitlab_user_url} "
                    "\"See @{gitlab_user_name}'s GitLab profile\") "
                    "from GitLab.\nOrigin GitLab issue: [gl#{number} - {subject}]({gitlab_url} "
                    "\"Go to 'gl#{number} - {subject}'\")\n\n"
                    "{message}").format(gitlab_user_name=gitlab_user_name,
                                        gitlab_user_url=gitlab_user_url,
                                        number=number,
                                        subject=subject,
                                        gitlab_url=gitlab_url,
                                        message=comment_message)
            else:
                comment = _("Comment From GitLab:\n\n{message}").format(
                    message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #21
0
    def process_event(self):
        number = self.payload.get('issue', {}).get('id', None)
        subject = self.payload.get('issue', {}).get('title', None)

        bitbucket_url = self.payload.get('issue', {}).get('links', {}).get('html', {}).get('href', None)

        bitbucket_user_id = self.payload.get('actor', {}).get('user', {}).get('uuid', None)
        bitbucket_user_name = self.payload.get('actor', {}).get('user', {}).get('username', None)
        bitbucket_user_url = self.payload.get('actor', {}).get('user', {}).get('links', {}).get('html', {}).get('href')

        project_url = self.payload.get('repository', {}).get('links', {}).get('html', {}).get('href', None)

        description = self.payload.get('issue', {}).get('content', {}).get('raw', '')
        description = replace_bitbucket_references(project_url, description)

        user = get_bitbucket_user(bitbucket_user_id)

        if not all([subject, bitbucket_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=description,
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['bitbucket', bitbucket_url],
            owner=user
        )
        take_snapshot(issue, user=user)

        if number and subject and bitbucket_user_name and bitbucket_user_url:
            comment = _("Issue created by [@{bitbucket_user_name}]({bitbucket_user_url} "
                        "\"See @{bitbucket_user_name}'s BitBucket profile\") "
                        "from BitBucket.\nOrigin BitBucket issue: [bb#{number} - {subject}]({bitbucket_url} "
                        "\"Go to 'bb#{number} - {subject}'\"):\n\n"
                        "{description}").format(bitbucket_user_name=bitbucket_user_name,
                                                bitbucket_user_url=bitbucket_user_url,
                                                number=number,
                                                subject=subject,
                                                bitbucket_url=bitbucket_url,
                                                description=description)
        else:
            comment = _("Issue created from BitBucket.")

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #22
0
    def process_event(self):
        number = self.payload.get('issue', {}).get('id', None)
        subject = self.payload.get('issue', {}).get('title', None)

        bitbucket_url = self.payload.get('issue', {}).get('links', {}).get('html', {}).get('href', None)

        bitbucket_user_id = self.payload.get('actor', {}).get('user', {}).get('uuid', None)
        bitbucket_user_name = self.payload.get('actor', {}).get('user', {}).get('username', None)
        bitbucket_user_url = self.payload.get('actor', {}).get('user', {}).get('links', {}).get('html', {}).get('href')

        project_url = self.payload.get('repository', {}).get('links', {}).get('html', {}).get('href', None)

        description = self.payload.get('issue', {}).get('content', {}).get('raw', '')
        description = replace_bitbucket_references(project_url, description)

        user = get_bitbucket_user(bitbucket_user_id)

        if not all([subject, bitbucket_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=description,
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['bitbucket', bitbucket_url],
            owner=user
        )
        take_snapshot(issue, user=user)

        if number and subject and bitbucket_user_name and bitbucket_user_url:
            comment = _("Issue created by [@{bitbucket_user_name}]({bitbucket_user_url} "
                        "\"See @{bitbucket_user_name}'s BitBucket profile\") "
                        "from BitBucket.\nOrigin BitBucket issue: [bb#{number} - {subject}]({bitbucket_url} "
                        "\"Go to 'bb#{number} - {subject}'\"):\n\n"
                        "{description}").format(bitbucket_user_name=bitbucket_user_name,
                                                bitbucket_user_url=bitbucket_user_url,
                                                number=number,
                                                subject=subject,
                                                bitbucket_url=bitbucket_url,
                                                description=description)
        else:
            comment = _("Issue created from BitBucket.")

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #23
0
    def _change_status(self, ref, status_slug, github_user, commit):
        if Issue.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Issue
            statusClass = IssueStatus
        elif Task.objects.filter(project=self.project, ref=ref).exists():
            modelClass = Task
            statusClass = TaskStatus
        elif UserStory.objects.filter(project=self.project, ref=ref).exists():
            modelClass = UserStory
            statusClass = UserStoryStatus
        else:
            raise ActionSyntaxException(_("The referenced element doesn't exist"))

        element = modelClass.objects.get(project=self.project, ref=ref)

        try:
            status = statusClass.objects.get(project=self.project, slug=status_slug)
        except statusClass.DoesNotExist:
            raise ActionSyntaxException(_("The status doesn't exist"))

        element.status = status
        element.save()

        github_user_id = github_user.get('id', None)
        github_user_name = github_user.get('login', None)
        github_user_url = github_user.get('html_url', None)
        commit_id = commit.get("id", None)
        commit_url = commit.get("url", None)
        commit_message = commit.get("message", None)

        if (github_user_id and github_user_name and github_user_url and
                commit_id and commit_url and commit_message):
            comment = _("Status changed by [@{github_user_name}]({github_user_url} "
                        "\"See @{github_user_name}'s GitHub profile\") "
                        "from GitHub commit [{commit_id}]({commit_url} "
                        "\"See commit '{commit_id} - {commit_message}'\").").format(
                                                               github_user_name=github_user_name,
                                                               github_user_url=github_user_url,
                                                               commit_id=commit_id[:7],
                                                               commit_url=commit_url,
                                                               commit_message=commit_message)

        else:
            comment = _("Status changed from GitHub commit.")

        snapshot = take_snapshot(element,
                                 comment=comment,
                                 user=get_github_user(github_user_id))
        send_notifications(element, history=snapshot)
Example #24
0
    def process_event(self):
        if self.payload.get('action', None) != "opened":
            return

        number = self.payload.get('issue', {}).get('number', None)
        subject = self.payload.get('issue', {}).get('title', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user_id = self.payload.get('issue', {}).get('user', {}).get('id', None)
        github_user_name = self.payload.get('issue', {}).get('user', {}).get('login', None)
        github_user_url = self.payload.get('issue', {}).get('user', {}).get('html_url', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        description = self.payload.get('issue', {}).get('body', None)
        description = replace_github_references(project_url, description)

        user = get_github_user(github_user_id)

        if not all([subject, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=description,
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['github', github_url],
            owner=user
        )
        take_snapshot(issue, user=user)

        if number and subject and github_user_name and github_user_url:
            comment = _("Issue created by [@{github_user_name}]({github_user_url} "
                        "\"See @{github_user_name}'s GitHub profile\") "
                        "from GitHub.\nOrigin GitHub issue: [gh#{number} - {subject}]({github_url} "
                        "\"Go to 'gh#{number} - {subject}'\"):\n\n"
                        "{description}").format(github_user_name=github_user_name,
                                                github_user_url=github_user_url,
                                                number=number,
                                                subject=subject,
                                                github_url=github_url,
                                                description=description)
        else:
            comment = _("Issue created from GitHub.")

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #25
0
    def _update_issue(self, data):
        issue = self.get_issue(data)

        if not issue:
            # The issue is not created yet, add it
            return self._create_issue(data)

        user = self.get_user(data["user_id"], self.platform_slug)

        issue.subject = data["subject"]
        issue.description = data["description"]
        issue.save()

        comment = self.generate_update_issue_comment(**data)

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
    def process_event(self):
        if self.ignore():
            return
        data = self.get_data()

        for commit in data:
            consumed_refs = []

            # Status changes
            p = re.compile("tg-(\d+) +#([-\w]+)")
            for m in p.finditer(commit["commit_message"].lower()):
                ref = m.group(1)
                status_slug = m.group(2)
                (element, src_status, dst_status) = self.set_item_status(
                    ref, status_slug
                )

                comment = self.generate_status_change_comment(
                    src_status=src_status, dst_status=dst_status, **commit
                )
                snapshot = take_snapshot(
                    element,
                    comment=comment,
                    user=self.get_user(commit["user_id"], self.platform_slug),
                )
                send_notifications(element, history=snapshot)
                consumed_refs.append(ref)

            # Reference on commit
            p = re.compile("tg-(\d+)")
            for m in p.finditer(commit["commit_message"].lower()):
                ref = m.group(1)
                if ref in consumed_refs:
                    continue
                element = self.get_item_by_ref(ref)
                type_name = element.__class__._meta.verbose_name
                comment = self.generate_commit_reference_comment(
                    type_name=type_name, **commit
                )
                snapshot = take_snapshot(
                    element,
                    comment=comment,
                    user=self.get_user(commit["user_id"], self.platform_slug),
                )
                send_notifications(element, history=snapshot)
                consumed_refs.append(ref)
Example #27
0
    def _process_label_changed(self, user, github_url):
        issues = Issue.objects.filter(external_reference=["github", github_url])
        
        l = self.payload.get('issue', {}).get('labels', [])
        labels = [x['name'] for x in l]

        issueType = IssueType.objects.filter(project=self.project, name__in=labels).order_by('order').first()

        for issue in list(issues):
            issue.tags = labels 
            issue.type = issueType
            issue.save()

            snapshot = take_snapshot(issue,
                                    comment="Edited from GitHub.",
                                    user=user)
            send_notifications(issue, history=snapshot)
Example #28
0
    def process_event(self):
        if self.payload.get('action', None) != "created":
            raise ActionSyntaxException(_("Invalid issue comment information"))

        number = self.payload.get('issue', {}).get('number', None)
        subject = self.payload.get('issue', {}).get('title', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user_id = self.payload.get('sender', {}).get('id', None)
        github_user_name = self.payload.get('sender', {}).get('login', None)
        github_user_url = self.payload.get('sender', {}).get('html_url', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        comment_message = self.payload.get('comment', {}).get('body', None)
        comment_message = replace_github_references(project_url,
                                                    comment_message)

        user = get_github_user(github_user_id)

        if not all([comment_message, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(
            external_reference=["github", github_url])
        tasks = Task.objects.filter(external_reference=["github", github_url])
        uss = UserStory.objects.filter(
            external_reference=["github", github_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and github_user_name and github_user_url:
                comment = _(
                    "Comment by [@{github_user_name}]({github_user_url} "
                    "\"See @{github_user_name}'s GitHub profile\") "
                    "from GitHub.\nOrigin GitHub issue: [{number}: {subject}]({github_url} "
                    "\"Go to '{number}: {subject}'\")\n\n"
                    "{message}").format(github_user_name=github_user_name,
                                        github_user_url=github_user_url,
                                        number=number,
                                        subject=subject,
                                        github_url=github_url,
                                        message=comment_message)
            else:
                comment = _("Comment From GitHub:\n\n{message}").format(
                    message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #29
0
    def process_event(self):
        if self.ignore():
            return

        data = self.get_data()

        if not all([data['comment_message'], data['url']]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        comment = self.generate_issue_comment_message(**data)

        issues = Issue.objects.filter(external_reference=[self.platform_slug, data['url']])
        tasks = Task.objects.filter(external_reference=[self.platform_slug, data['url']])
        uss = UserStory.objects.filter(external_reference=[self.platform_slug, data['url']])

        for item in list(issues) + list(tasks) + list(uss):
            snapshot = take_snapshot(item, comment=comment, user=self.get_user(data['user_id'], self.platform_slug))
            send_notifications(item, history=snapshot)
Example #30
0
    def process_event(self):
        attrs = self.payload.get('object_attributes', {})

        if attrs.get("noteable_type", None) != "Issue":
            return

        number = self.payload.get('issue', {}).get('iid', None)
        subject = self.payload.get('issue', {}).get('title', None)

        project_url = self.payload.get('repository', {}).get('homepage', None)

        gitlab_url = os.path.join(project_url, "issues", str(number))
        gitlab_user_name = self.payload.get('user', {}).get('username', None)
        gitlab_user_url = os.path.join(os.path.dirname(os.path.dirname(project_url)), "u", gitlab_user_name)

        comment_message = attrs.get('note', None)
        comment_message = replace_gitlab_references(project_url, comment_message)

        user = get_gitlab_user(None)

        if not all([comment_message, gitlab_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(external_reference=["gitlab", gitlab_url])
        tasks = Task.objects.filter(external_reference=["gitlab", gitlab_url])
        uss = UserStory.objects.filter(external_reference=["gitlab", gitlab_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and gitlab_user_name and gitlab_user_url:
                comment = _("Comment by [@{gitlab_user_name}]({gitlab_user_url} "
                            "\"See @{gitlab_user_name}'s GitLab profile\") "
                            "from GitLab.\nOrigin GitLab issue: [gl#{number} - {subject}]({gitlab_url} "
                            "\"Go to 'gl#{number} - {subject}'\")\n\n"
                            "{message}").format(gitlab_user_name=gitlab_user_name,
                                                gitlab_user_url=gitlab_user_url,
                                                number=number,
                                                subject=subject,
                                                gitlab_url=gitlab_url,
                                                message=comment_message)
            else:
                comment = _("Comment From GitLab:\n\n{message}").format(message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #31
0
    def _reopen_issue(self, data):
        issue = self.get_issue(data)

        if not issue:
            # The issue is not created yet, add it
            return self._create_issue(data)

        if not self.open_status:
            return

        user = self.get_user(data["user_id"], self.platform_slug)

        issue.status = self.open_status
        issue.save()

        comment = self.generate_reopen_issue_comment(**data)

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #32
0
    def _create_issue(self, data):
        user = self.get_user(data["user_id"], self.platform_slug)

        issue = Issue.objects.create(
            project=self.project,
            subject=data["subject"],
            description=data["description"],
            status=data.get("status", self.project.default_issue_status),
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=[self.platform_slug, data['url']],
            owner=user)
        take_snapshot(issue, user=user)

        comment = self.generate_create_issue_comment(**data)

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #33
0
    def _create_wiki_page_when_create_wiki_link_if_not_exist(self, request, wiki_link):
        try:
            self.check_permissions(request, "create_wiki_page", wiki_link)
        except exc.PermissionDenied:
            # Create only the wiki link because the user doesn't have permission.
            pass
        else:
            # Create the wiki link and the wiki page if not exist.
            wiki_page, created = models.WikiPage.objects.get_or_create(
                slug=wiki_link.href,
                project=wiki_link.project,
                defaults={"owner": self.request.user, "last_modifier": self.request.user})

            if created:
                # Creaste the new history entre, sSet watcher for the new wiki page
                # and send notifications about the new page created
                history = take_snapshot(wiki_page, user=self.request.user)
                analize_object_for_watchers(wiki_page, history.comment, history.owner)
                send_notifications(wiki_page, history=history)
Example #34
0
    def process_event(self):
        if self.payload.get('action', None) != "created":
            raise ActionSyntaxException(_("Invalid issue comment information"))

        number = self.payload.get('issue', {}).get('number', None)
        subject = self.payload.get('issue', {}).get('title', None)
        github_url = self.payload.get('issue', {}).get('html_url', None)
        github_user_id = self.payload.get('sender', {}).get('id', None)
        github_user_name = self.payload.get('sender', {}).get('login', None)
        github_user_url = self.payload.get('sender', {}).get('html_url', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        comment_message = self.payload.get('comment', {}).get('body', None)
        comment_message = replace_github_references(project_url, comment_message)

        user = get_github_user(github_user_id)

        if not all([comment_message, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(external_reference=["github", github_url])
        tasks = Task.objects.filter(external_reference=["github", github_url])
        uss = UserStory.objects.filter(external_reference=["github", github_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and github_user_name and github_user_url:
                comment = _("Comment by [@{github_user_name}]({github_user_url} "
                            "\"See @{github_user_name}'s GitHub profile\") "
                            "from GitHub.\nOrigin GitHub issue: [gh#{number} - {subject}]({github_url} "
                            "\"Go to 'gh#{number} - {subject}'\")\n\n"
                            "{message}").format(github_user_name=github_user_name,
                                                github_user_url=github_user_url,
                                                number=number,
                                                subject=subject,
                                                github_url=github_url,
                                                message=comment_message)
            else:
                comment = _("Comment From GitHub:\n\n{message}").format(message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #35
0
    def process_event(self):
        number = self.payload.get('issue', {}).get('id', None)
        subject = self.payload.get('issue', {}).get('title', None)

        bitbucket_url = self.payload.get('issue', {}).get('links', {}).get('html', {}).get('href', None)
        bitbucket_user_id = self.payload.get('actor', {}).get('user', {}).get('uuid', None)
        bitbucket_user_name = self.payload.get('actor', {}).get('user', {}).get('username', None)
        bitbucket_user_url = self.payload.get('actor', {}).get('user', {}).get('links', {}).get('html', {}).get('href')

        project_url = self.payload.get('repository', {}).get('links', {}).get('html', {}).get('href', None)

        comment_message = self.payload.get('comment', {}).get('content', {}).get('raw', '')
        comment_message = replace_bitbucket_references(project_url, comment_message)

        user = get_bitbucket_user(bitbucket_user_id)

        if not all([comment_message, bitbucket_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(external_reference=["bitbucket", bitbucket_url])
        tasks = Task.objects.filter(external_reference=["bitbucket", bitbucket_url])
        uss = UserStory.objects.filter(external_reference=["bitbucket", bitbucket_url])

        for item in list(issues) + list(tasks) + list(uss):
            if number and subject and bitbucket_user_name and bitbucket_user_url:
                comment = _("Comment by [@{bitbucket_user_name}]({bitbucket_user_url} "
                            "\"See @{bitbucket_user_name}'s BitBucket profile\") "
                            "from BitBucket.\nOrigin BitBucket issue: [bb#{number} - {subject}]({bitbucket_url} "
                            "\"Go to 'bb#{number} - {subject}'\")\n\n"
                            "{message}").format(bitbucket_user_name=bitbucket_user_name,
                                                bitbucket_user_url=bitbucket_user_url,
                                                number=number,
                                                subject=subject,
                                                bitbucket_url=bitbucket_url,
                                                message=comment_message)
            else:
                comment = _("Comment From BitBucket:\n\n{message}").format(message=comment_message)

            snapshot = take_snapshot(item, comment=comment, user=user)
            send_notifications(item, history=snapshot)
Example #36
0
    def process_event(self):
        if self.payload.get('action', None) != "created":
            raise ActionSyntaxException(_("Invalid issue comment information"))

        github_url = self.payload.get('issue', {}).get('html_url', None)
        comment_message = self.payload.get('comment', {}).get('body', None)
        github_user = self.payload.get('sender', {}).get('id', None)
        project_url = self.payload.get('repository', {}).get('html_url', None)
        comment_message = replace_github_references(project_url, comment_message)

        if not all([comment_message, github_url, project_url]):
            raise ActionSyntaxException(_("Invalid issue comment information"))

        issues = Issue.objects.filter(external_reference=["github", github_url])
        tasks = Task.objects.filter(external_reference=["github", github_url])
        uss = UserStory.objects.filter(external_reference=["github", github_url])

        for item in list(issues) + list(tasks) + list(uss):
            snapshot = take_snapshot(item,
                                     comment=_("From GitHub:\n\n{}".format(comment_message)),
                                     user=get_github_user(github_user))
            send_notifications(item, history=snapshot)
Example #37
0
    def process_event(self):
        if self.ignore():
            return
        data = self.get_data()

        for commit in data:
            consumed_refs = []

            # Status changes
            p = re.compile("tg-(\d+) +#([-\w]+)")
            for m in p.finditer(commit['commit_message'].lower()):
                ref = m.group(1)
                status_slug = m.group(2)
                (element, src_status, dst_status) = self.set_item_status(ref, status_slug)

                comment = self.generate_status_change_comment(src_status=src_status, dst_status=dst_status, **commit)
                snapshot = take_snapshot(element,
                                         comment=comment,
                                         user=self.get_user(commit['user_id'], self.platform_slug))
                send_notifications(element, history=snapshot)
                consumed_refs.append(ref)

            # Reference on commit
            p = re.compile("tg-(\d+)")
            for m in p.finditer(commit['commit_message'].lower()):
                ref = m.group(1)
                if ref in consumed_refs:
                    continue
                element = self.get_item_by_ref(ref)
                type_name = element.__class__._meta.verbose_name
                comment = self.generate_commit_reference_comment(type_name=type_name, **commit)
                snapshot = take_snapshot(element,
                                         comment=comment,
                                         user=self.get_user(commit['user_id'], self.platform_slug))
                send_notifications(element, history=snapshot)
                consumed_refs.append(ref)
Example #38
0
def test_send_notifications_using_services_method(mail):
    project = f.ProjectFactory.create()
    member1 = f.MembershipFactory.create(project=project)
    member2 = f.MembershipFactory.create(project=project)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete

    # Issues
    issue = f.IssueFactory.create(project=project)
    take_snapshot(issue)
    services.send_notifications(issue, history=history_create)

    services.send_notifications(issue, history=history_change)

    services.send_notifications(issue, history=history_delete)

    # Userstories
    us = f.UserStoryFactory.create()
    take_snapshot(us)
    services.send_notifications(us, history=history_create)

    services.send_notifications(us, history=history_change)

    services.send_notifications(us, history=history_delete)

    # Tasks
    task = f.TaskFactory.create()
    take_snapshot(task)
    services.send_notifications(task, history=history_create)

    services.send_notifications(task, history=history_change)

    services.send_notifications(task, history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create()
    take_snapshot(wiki)
    services.send_notifications(wiki, history=history_create)

    services.send_notifications(wiki, history=history_change)

    services.send_notifications(wiki, history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12
def test_send_notifications_using_services_method(mail):
    project = f.ProjectFactory.create()
    member1 = f.MembershipFactory.create(project=project)
    member2 = f.MembershipFactory.create(project=project)

    history_change = MagicMock()
    history_change.owner = member1.user
    history_change.comment = ""
    history_change.type = HistoryType.change

    history_create = MagicMock()
    history_create.owner = member1.user
    history_create.comment = ""
    history_create.type = HistoryType.create

    history_delete = MagicMock()
    history_delete.owner = member1.user
    history_delete.comment = ""
    history_delete.type = HistoryType.delete

    # Issues
    issue = f.IssueFactory.create(project=project)
    services.send_notifications(issue,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(issue,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(issue,
                                history=history_delete,
                                users={member1.user, member2.user})

    # Userstories
    us = f.UserStoryFactory.create()
    services.send_notifications(us,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(us,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(us,
                                history=history_delete,
                                users={member1.user, member2.user})
    # Tasks
    task = f.TaskFactory.create()
    services.send_notifications(task,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(task,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(task,
                                history=history_delete,
                                users={member1.user, member2.user})

    # Wiki pages
    wiki = f.WikiPageFactory.create()
    services.send_notifications(wiki,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(wiki,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(wiki,
                                history=history_delete,
                                users={member1.user, member2.user})

    assert len(mail.outbox) == 24
Example #40
0
def test_send_notifications_using_services_method_for_wiki_pages(
        settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project,
                                permissions=[
                                    'view_issues', 'view_us', 'view_tasks',
                                    'view_wiki_pages'
                                ])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    history_change = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="test:change",
        type=HistoryType.change,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[])

    history_create = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="",
        type=HistoryType.create,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[])

    history_delete = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="test:delete",
        type=HistoryType.delete,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[])
    take_snapshot(wiki, user=wiki.owner)
    services.send_notifications(wiki, history=history_create)

    services.send_notifications(wiki, history=history_change)

    services.send_notifications(wiki, history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 3
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 3

    # test headers
    domain = settings.SITES["api"]["domain"].split(
        ":")[0] or settings.SITES["api"]["domain"]
    for msg in mail.outbox:
        m_id = "{project_slug}/{msg_id}".format(project_slug=project.slug,
                                                msg_id=wiki.slug)

        message_id = "<{m_id}/".format(m_id=m_id)
        message_id_domain = "@{domain}>".format(domain=domain)
        in_reply_to = "<{m_id}@{domain}>".format(m_id=m_id, domain=domain)
        list_id = "Taiga/{p_name} <taiga.{p_slug}@{domain}>" \
            .format(p_name=project.name, p_slug=project.slug, domain=domain)

        assert msg.extra_headers
        headers = msg.extra_headers

        # can't test the time part because it's set when sending
        # check what we can
        assert 'Message-ID' in headers
        assert message_id in headers.get('Message-ID')
        assert message_id_domain in headers.get('Message-ID')

        assert 'In-Reply-To' in headers
        assert in_reply_to == headers.get('In-Reply-To')
        assert 'References' in headers
        assert in_reply_to == headers.get('References')

        assert 'List-ID' in headers
        assert list_id == headers.get('List-ID')

        assert 'Thread-Index' in headers

        # hashes should match for identical ids and times
        # we check the actual method in test_ms_thread_id()
        msg_time = headers.get('Message-ID').split('/')[2].split('@')[0]
        msg_ts = datetime.datetime.fromtimestamp(int(msg_time))
        assert services.make_ms_thread_index(
            in_reply_to, msg_ts) == headers.get('Thread-Index')
Example #41
0
def test_send_notifications_using_services_method(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project, permissions=['view_issues', 'view_us', 'view_tasks', 'view_wiki_pages'])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change
    history_change.is_hidden = False

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create
    history_create.is_hidden = False

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete
    history_delete.is_hidden = False

    # Issues
    issue = f.IssueFactory.create(project=project, owner=member2.user)
    take_snapshot(issue, user=issue.owner)
    services.send_notifications(issue,
                                history=history_create)

    services.send_notifications(issue,
                                history=history_change)

    services.send_notifications(issue,
                                history=history_delete)

    # Userstories
    us = f.UserStoryFactory.create(project=project, owner=member2.user)
    take_snapshot(us, user=us.owner)
    services.send_notifications(us,
                                history=history_create)

    services.send_notifications(us,
                                history=history_change)

    services.send_notifications(us,
                                history=history_delete)

    # Tasks
    task = f.TaskFactory.create(project=project, owner=member2.user)
    take_snapshot(task, user=task.owner)
    services.send_notifications(task,
                                history=history_create)

    services.send_notifications(task,
                                history=history_change)

    services.send_notifications(task,
                                history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    take_snapshot(wiki, user=wiki.owner)
    services.send_notifications(wiki,
                                history=history_create)

    services.send_notifications(wiki,
                                history=history_change)

    services.send_notifications(wiki,
                                history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12

    # test headers
    events = [issue, us, task, wiki]
    domain = settings.SITES["api"]["domain"].split(":")[0] or settings.SITES["api"]["domain"]
    i = 0
    for msg in mail.outbox:
        # each event has 3 msgs
        event = events[math.floor(i / 3)]

        # each set of 3 should have the same headers
        if i % 3 == 0:
            if hasattr(event, 'ref'):
                e_slug = event.ref
            elif hasattr(event, 'slug'):
                e_slug = event.slug
            else:
                e_slug = 'taiga-system'

            m_id = "{project_slug}/{msg_id}".format(
                project_slug=project.slug,
                msg_id=e_slug
            )

            message_id = "<{m_id}/".format(m_id=m_id)
            message_id_domain = "@{domain}>".format(domain=domain)
            in_reply_to = "<{m_id}@{domain}>".format(m_id=m_id, domain=domain)
            list_id = "Taiga/{p_name} <taiga.{p_slug}@{domain}>" \
                .format(p_name=project.name, p_slug=project.slug, domain=domain)

        assert msg.extra_headers
        headers = msg.extra_headers

        # can't test the time part because it's set when sending
        # check what we can
        assert 'Message-ID' in headers
        assert message_id in headers.get('Message-ID')
        assert message_id_domain in headers.get('Message-ID')

        assert 'In-Reply-To' in headers
        assert in_reply_to == headers.get('In-Reply-To')
        assert 'References' in headers
        assert in_reply_to == headers.get('References')

        assert 'List-ID' in headers
        assert list_id == headers.get('List-ID')

        assert 'Thread-Index' in headers
        # always is b64 encoded 22 bytes
        assert len(base64.b64decode(headers.get('Thread-Index'))) == 22

        # hashes should match for identical ids and times
        # we check the actual method in test_ms_thread_id()
        msg_time = headers.get('Message-ID').split('/')[2].split('@')[0]
        msg_ts = datetime.datetime.fromtimestamp(int(msg_time))
        assert services.make_ms_thread_index(in_reply_to, msg_ts) == headers.get('Thread-Index')

        i += 1
Example #42
0
def test_send_notifications_using_services_method(mail):
    project = f.ProjectFactory.create()
    member1 = f.MembershipFactory.create(project=project)
    member2 = f.MembershipFactory.create(project=project)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete

    # Issues
    issue = f.IssueFactory.create(project=project)
    take_snapshot(issue)
    services.send_notifications(issue,
                                history=history_create)

    services.send_notifications(issue,
                                history=history_change)

    services.send_notifications(issue,
                                history=history_delete)


    # Userstories
    us = f.UserStoryFactory.create()
    take_snapshot(us)
    services.send_notifications(us,
                                history=history_create)

    services.send_notifications(us,
                                history=history_change)

    services.send_notifications(us,
                                history=history_delete)

    # Tasks
    task = f.TaskFactory.create()
    take_snapshot(task)
    services.send_notifications(task,
                                history=history_create)

    services.send_notifications(task,
                                history=history_change)

    services.send_notifications(task,
                                history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create()
    take_snapshot(wiki)
    services.send_notifications(wiki,
                                history=history_create)

    services.send_notifications(wiki,
                                history=history_change)

    services.send_notifications(wiki,
                                history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12
Example #43
0
    def process_event(self):
        attrs = self.payload.get('object_attributes', {})

        if attrs.get("action", "") != "open":
            return

        subject = attrs.get('title', None)
        gitlab_reference = attrs.get('iid', None)
        gitlab_issue_url = attrs.get('url', None)
        gitlab_project_url = None
        user = self.user_info.get('user')

        if gitlab_issue_url:
            # the last two sections are always the "/issues/:id"
            gitlab_project_url = '/'.join(gitlab_issue_url.split('/')[:-2])

        description = replace_gitlab_references(gitlab_project_url, attrs.get('description', None))

        if not all([subject, gitlab_reference, gitlab_issue_url, gitlab_project_url]):
            raise ActionSyntaxException(_("Invalid issue information"))

        issue = Issue.objects.create(
            project=self.project,
            subject=subject,
            description=replace_gitlab_references(gitlab_project_url, description),
            status=self.project.default_issue_status,
            type=self.project.default_issue_type,
            severity=self.project.default_severity,
            priority=self.project.default_priority,
            external_reference=['gitlab', gitlab_reference],
            owner=user
        )

        take_snapshot(issue, user=user)

        comment = _("Issue created from GitLab.")

        if user is not None and not user.is_system:
            comment = _(self.messages.get('native').get('issue')).format(
                username=user.username,
                service_type=self.service_type,
                remote_ref=gitlab_reference,
                subject=subject,
                remote_url=gitlab_issue_url,
                description=description
            )

        # use what info we have
        elif "name" in self.user_info and "email" in self.user_info:
            comment = _(self.messages.get('system').get('issue')).format(
                name=self.user_info.get("name'"),
                user_url=self.user_info.get('url'),
                service_type=self.service_type,
                remote_ref=gitlab_reference,
                subject=subject,
                remote_url=gitlab_issue_url,
                description=description
            )

        snapshot = take_snapshot(issue, comment=comment, user=user)
        send_notifications(issue, history=snapshot)
Example #44
0
def test_send_notifications_using_services_method(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project,
                                permissions=[
                                    'view_issues', 'view_us', 'view_tasks',
                                    'view_wiki_pages'
                                ])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change
    history_change.is_hidden = False

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create
    history_create.is_hidden = False

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete
    history_delete.is_hidden = False

    # Issues
    issue = f.IssueFactory.create(project=project, owner=member2.user)
    take_snapshot(issue, user=issue.owner)
    services.send_notifications(issue, history=history_create)

    services.send_notifications(issue, history=history_change)

    services.send_notifications(issue, history=history_delete)

    # Userstories
    us = f.UserStoryFactory.create(project=project, owner=member2.user)
    take_snapshot(us, user=us.owner)
    services.send_notifications(us, history=history_create)

    services.send_notifications(us, history=history_change)

    services.send_notifications(us, history=history_delete)

    # Tasks
    task = f.TaskFactory.create(project=project, owner=member2.user)
    take_snapshot(task, user=task.owner)
    services.send_notifications(task, history=history_create)

    services.send_notifications(task, history=history_change)

    services.send_notifications(task, history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    take_snapshot(wiki, user=wiki.owner)
    services.send_notifications(wiki, history=history_create)

    services.send_notifications(wiki, history=history_change)

    services.send_notifications(wiki, history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12

    # test headers
    events = [issue, us, task, wiki]
    domain = settings.SITES["api"]["domain"].split(
        ":")[0] or settings.SITES["api"]["domain"]
    i = 0
    for msg in mail.outbox:
        # each event has 3 msgs
        event = events[math.floor(i / 3)]

        # each set of 3 should have the same headers
        if i % 3 == 0:
            if hasattr(event, 'ref'):
                e_slug = event.ref
            elif hasattr(event, 'slug'):
                e_slug = event.slug
            else:
                e_slug = 'taiga-system'

            m_id = "{project_slug}/{msg_id}".format(project_slug=project.slug,
                                                    msg_id=e_slug)

            message_id = "<{m_id}/".format(m_id=m_id)
            message_id_domain = "@{domain}>".format(domain=domain)
            in_reply_to = "<{m_id}@{domain}>".format(m_id=m_id, domain=domain)
            list_id = "Taiga/{p_name} <taiga.{p_slug}@{domain}>" \
                .format(p_name=project.name, p_slug=project.slug, domain=domain)

        assert msg.extra_headers
        headers = msg.extra_headers

        # can't test the time part because it's set when sending
        # check what we can
        assert 'Message-ID' in headers
        assert message_id in headers.get('Message-ID')
        assert message_id_domain in headers.get('Message-ID')

        assert 'In-Reply-To' in headers
        assert in_reply_to == headers.get('In-Reply-To')
        assert 'References' in headers
        assert in_reply_to == headers.get('References')

        assert 'List-ID' in headers
        assert list_id == headers.get('List-ID')

        assert 'Thread-Index' in headers
        # always is b64 encoded 22 bytes
        assert len(base64.b64decode(headers.get('Thread-Index'))) == 22

        # hashes should match for identical ids and times
        # we check the actual method in test_ms_thread_id()
        msg_time = headers.get('Message-ID').split('/')[2].split('@')[0]
        msg_ts = datetime.datetime.fromtimestamp(int(msg_time))
        assert services.make_ms_thread_index(
            in_reply_to, msg_ts) == headers.get('Thread-Index')

        i += 1
Example #45
0
 def _process_created(self, item, comment, user):
     snapshot = take_snapshot(item, comment=comment, user=user)
     send_notifications(item, history=snapshot)
def test_send_notifications_using_services_method(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project, permissions=['view_issues', 'view_us', 'view_tasks', 'view_wiki_pages'])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change
    history_change.is_hidden = False

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create
    history_create.is_hidden = False

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete
    history_delete.is_hidden = False

    # Issues
    issue = f.IssueFactory.create(project=project, owner=member2.user)
    take_snapshot(issue)
    services.send_notifications(issue,
                                history=history_create)

    services.send_notifications(issue,
                                history=history_change)

    services.send_notifications(issue,
                                history=history_delete)


    # Userstories
    us = f.UserStoryFactory.create(project=project, owner=member2.user)
    take_snapshot(us)
    services.send_notifications(us,
                                history=history_create)

    services.send_notifications(us,
                                history=history_change)

    services.send_notifications(us,
                                history=history_delete)

    # Tasks
    task = f.TaskFactory.create(project=project, owner=member2.user)
    take_snapshot(task)
    services.send_notifications(task,
                                history=history_create)

    services.send_notifications(task,
                                history=history_change)

    services.send_notifications(task,
                                history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    take_snapshot(wiki)
    services.send_notifications(wiki,
                                history=history_create)

    services.send_notifications(wiki,
                                history=history_change)

    services.send_notifications(wiki,
                                history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12
def test_send_notifications_using_services_method_for_issues(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(
        project=project, permissions=["view_issues", "view_us", "view_tasks", "view_wiki_pages"]
    )
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    issue = f.IssueFactory.create(project=project, owner=member2.user)
    history_change = f.HistoryEntryFactory.create(
        user={"pk": member1.user.id},
        comment="",
        type=HistoryType.change,
        key="issues.issue:{}".format(issue.id),
        is_hidden=False,
        diff=[],
    )

    history_create = f.HistoryEntryFactory.create(
        user={"pk": member1.user.id},
        comment="",
        type=HistoryType.create,
        key="issues.issue:{}".format(issue.id),
        is_hidden=False,
        diff=[],
    )

    history_delete = f.HistoryEntryFactory.create(
        user={"pk": member1.user.id},
        comment="test:delete",
        type=HistoryType.delete,
        key="issues.issue:{}".format(issue.id),
        is_hidden=False,
        diff=[],
    )

    take_snapshot(issue, user=issue.owner)
    services.send_notifications(issue, history=history_create)

    services.send_notifications(issue, history=history_change)

    services.send_notifications(issue, history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 3
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 3

    # test headers
    domain = settings.SITES["api"]["domain"].split(":")[0] or settings.SITES["api"]["domain"]
    for msg in mail.outbox:
        m_id = "{project_slug}/{msg_id}".format(project_slug=project.slug, msg_id=issue.ref)

        message_id = "<{m_id}/".format(m_id=m_id)
        message_id_domain = "@{domain}>".format(domain=domain)
        in_reply_to = "<{m_id}@{domain}>".format(m_id=m_id, domain=domain)
        list_id = "Taiga/{p_name} <taiga.{p_slug}@{domain}>".format(
            p_name=project.name, p_slug=project.slug, domain=domain
        )

        assert msg.extra_headers
        headers = msg.extra_headers

        # can't test the time part because it's set when sending
        # check what we can
        assert "Message-ID" in headers
        assert message_id in headers.get("Message-ID")
        assert message_id_domain in headers.get("Message-ID")

        assert "In-Reply-To" in headers
        assert in_reply_to == headers.get("In-Reply-To")
        assert "References" in headers
        assert in_reply_to == headers.get("References")

        assert "List-ID" in headers
        assert list_id == headers.get("List-ID")

        assert "Thread-Index" in headers
        # always is b64 encoded 22 bytes
        assert len(base64.b64decode(headers.get("Thread-Index"))) == 22

        # hashes should match for identical ids and times
        # we check the actual method in test_ms_thread_id()
        msg_time = headers.get("Message-ID").split("/")[2].split("@")[0]
        msg_ts = datetime.datetime.fromtimestamp(int(msg_time))
        assert services.make_ms_thread_index(in_reply_to, msg_ts) == headers.get("Thread-Index")
Example #48
0
def test_send_notifications_using_services_method(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project,
                                permissions=[
                                    'view_issues', 'view_us', 'view_tasks',
                                    'view_wiki_pages'
                                ])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    history_change = MagicMock()
    history_change.user = {"pk": member1.user.pk}
    history_change.comment = ""
    history_change.type = HistoryType.change
    history_change.is_hidden = False

    history_create = MagicMock()
    history_create.user = {"pk": member1.user.pk}
    history_create.comment = ""
    history_create.type = HistoryType.create
    history_create.is_hidden = False

    history_delete = MagicMock()
    history_delete.user = {"pk": member1.user.pk}
    history_delete.comment = ""
    history_delete.type = HistoryType.delete
    history_delete.is_hidden = False

    # Issues
    issue = f.IssueFactory.create(project=project, owner=member2.user)
    take_snapshot(issue, user=issue.owner)
    services.send_notifications(issue, history=history_create)

    services.send_notifications(issue, history=history_change)

    services.send_notifications(issue, history=history_delete)

    # Userstories
    us = f.UserStoryFactory.create(project=project, owner=member2.user)
    take_snapshot(us, user=us.owner)
    services.send_notifications(us, history=history_create)

    services.send_notifications(us, history=history_change)

    services.send_notifications(us, history=history_delete)

    # Tasks
    task = f.TaskFactory.create(project=project, owner=member2.user)
    take_snapshot(task, user=task.owner)
    services.send_notifications(task, history=history_create)

    services.send_notifications(task, history=history_change)

    services.send_notifications(task, history=history_delete)

    # Wiki pages
    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    take_snapshot(wiki, user=wiki.owner)
    services.send_notifications(wiki, history=history_create)

    services.send_notifications(wiki, history=history_change)

    services.send_notifications(wiki, history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 12
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 12
Example #49
0
def test_send_notifications_using_services_method_for_wiki_pages(settings, mail):
    settings.CHANGE_NOTIFICATIONS_MIN_INTERVAL = 1

    project = f.ProjectFactory.create()
    role = f.RoleFactory.create(project=project, permissions=['view_issues', 'view_us', 'view_tasks', 'view_wiki_pages'])
    member1 = f.MembershipFactory.create(project=project, role=role)
    member2 = f.MembershipFactory.create(project=project, role=role)

    wiki = f.WikiPageFactory.create(project=project, owner=member2.user)
    history_change = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="",
        type=HistoryType.change,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[]
    )

    history_create = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="",
        type=HistoryType.create,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[]
    )

    history_delete = f.HistoryEntryFactory.create(
        project=project,
        user={"pk": member1.user.id},
        comment="test:delete",
        type=HistoryType.delete,
        key="wiki.wikipage:{}".format(wiki.id),
        is_hidden=False,
        diff=[]
    )
    take_snapshot(wiki, user=wiki.owner)
    services.send_notifications(wiki,
                                history=history_create)

    services.send_notifications(wiki,
                                history=history_change)

    services.send_notifications(wiki,
                                history=history_delete)

    assert models.HistoryChangeNotification.objects.count() == 3
    assert len(mail.outbox) == 0
    time.sleep(1)
    services.process_sync_notifications()
    assert len(mail.outbox) == 3

    # test headers
    domain = settings.SITES["api"]["domain"].split(":")[0] or settings.SITES["api"]["domain"]
    for msg in mail.outbox:
        m_id = "{project_slug}/{msg_id}".format(
            project_slug=project.slug,
            msg_id=wiki.slug
        )

        message_id = "<{m_id}/".format(m_id=m_id)
        message_id_domain = "@{domain}>".format(domain=domain)
        in_reply_to = "<{m_id}@{domain}>".format(m_id=m_id, domain=domain)
        list_id = "Taiga/{p_name} <taiga.{p_slug}@{domain}>" \
            .format(p_name=project.name, p_slug=project.slug, domain=domain)

        assert msg.extra_headers
        headers = msg.extra_headers

        # can't test the time part because it's set when sending
        # check what we can
        assert 'Message-ID' in headers
        assert message_id in headers.get('Message-ID')
        assert message_id_domain in headers.get('Message-ID')

        assert 'In-Reply-To' in headers
        assert in_reply_to == headers.get('In-Reply-To')
        assert 'References' in headers
        assert in_reply_to == headers.get('References')

        assert 'List-ID' in headers
        assert list_id == headers.get('List-ID')

        assert 'Thread-Index' in headers

        # hashes should match for identical ids and times
        # we check the actual method in test_ms_thread_id()
        msg_time = headers.get('Message-ID').split('/')[2].split('@')[0]
        msg_ts = datetime.datetime.fromtimestamp(int(msg_time))
        assert services.make_ms_thread_index(in_reply_to, msg_ts) == headers.get('Thread-Index')
Example #50
0
def test_send_notifications_using_services_method(mail):
    project = f.ProjectFactory.create()
    member1 = f.MembershipFactory.create(project=project)
    member2 = f.MembershipFactory.create(project=project)

    history_change = MagicMock()
    history_change.owner = member1.user
    history_change.comment = ""
    history_change.type = HistoryType.change

    history_create = MagicMock()
    history_create.owner = member1.user
    history_create.comment = ""
    history_create.type = HistoryType.create

    history_delete = MagicMock()
    history_delete.owner = member1.user
    history_delete.comment = ""
    history_delete.type = HistoryType.delete

    # Issues
    issue = f.IssueFactory.create(project=project)
    services.send_notifications(issue,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(issue,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(issue,
                                history=history_delete,
                                users={member1.user, member2.user})

    # Userstories
    us = f.UserStoryFactory.create()
    services.send_notifications(us,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(us,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(us,
                                history=history_delete,
                                users={member1.user, member2.user})
    # Tasks
    task = f.TaskFactory.create()
    services.send_notifications(task,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(task,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(task,
                                history=history_delete,
                                users={member1.user, member2.user})

    # Wiki pages
    wiki = f.WikiPageFactory.create()
    services.send_notifications(wiki,
                                history=history_create,
                                users={member1.user, member2.user})

    services.send_notifications(wiki,
                                history=history_change,
                                users={member1.user, member2.user})

    services.send_notifications(wiki,
                                history=history_delete,
                                users={member1.user, member2.user})

    assert len(mail.outbox) == 24