Ejemplo n.º 1
0
def assign(request):
    if request.method == 'POST':
        assignForm = AssignBugForm(request.POST)
        if assignForm.is_valid():
            bug = get_object_or_404(Bug, pk=assignForm.cleaned_data['bug_id'])
            bug.status = Bug.STATUS_ASSIGNED
            bug.resolver = User.objects.get(pk=assignForm.cleaned_data['user'])
            bug.original = None
            bug.save()
            # HAY QUE GUARDAR EN LOS COMENTARIOS EL CAMBIO DE STATUS
            c = Comment()
            c.content_type = ContentType.objects.get(app_label="bugs",
                                                     model="bug")
            c.object_pk = bug.pk
            c.site = Site.objects.get(id=settings.SITE_ID)
            c.comment = '{0} has assigned this bug to {1}. Its status has change to {2}'.format(
                request.user.username, bug.resolver.username,
                bug.get_status_display())
            c.save()
            return HttpResponseRedirect('/bugs/browse/{0}/{1}/{2}'.format(
                bug.component.application.id, bug.component.id, bug.id))
        else:
            messages.error(request,
                           "An error occur while trying to assign the bug.")
            return HttpResponseRedirect(reverse('BTS_home'))
    else:
        return Http404()
Ejemplo n.º 2
0
    def post(self, request, fingerprint=None):

        if request.user.is_authenticated():

            try:
                fp = Fingerprint.valid().get(fingerprint_hash=fingerprint)

                comment = Comment(content_object=fp,
                                  site=Site.objects.get_current(),
                                  user=request.user,
                                  user_name=(request.user.get_full_name()
                                             or request.user.email),
                                  user_email=request.user.email,
                                  user_url="",
                                  comment=request.POST['comment'],
                                  ip_address=request.META.get(
                                      "REMOTE_ADDR", None))
                comment.save()

                return Response({'comment': CommentSerializer(comment).data},
                                status=status.HTTP_200_OK)

            except Fingerprint.DoesNotExist:
                pass

        return Response({}, status=status.HTTP_403_FORBIDDEN)
Ejemplo n.º 3
0
def post(request):
    """Returns a serialized object
    :param obj_id: ID of comment object
    :type obj_id: int
    :returns: json
    """
    guid = request.POST.get('guid', None)
    res = Result()

    if guid:
        obj = getObjectsFromGuids([
            guid,
        ])[0]
        c = Comment()
        c.comment = request.POST.get('comment', 'No comment')
        c.user = request.user
        c.user_name = request.user.get_full_name()
        c.user_email = request.user.email
        c.content_object = obj
        c.site_id = 1
        c.save()
        obj.comment_count = obj.comment_count + 1
        obj.save()

        __email(c, obj)

        res.append({'id': c.id, 'comment': c.comment})
        res.isSuccess = True
    else:
        res.isError = True
        res.message = "No guid provided"

    return JsonResponse(res)
Ejemplo n.º 4
0
def submit_comment(request, event_slug):
    "submits a new comment associated with event"

    # checks for bad request
    if "comment_text" not in request.POST:
        return HttpResponseBadRequest()

    # get event object
    event = get_object_or_404(Event, slug=event_slug)

    # get participation object
    participation = get_object_or_404(Participation,
                                      accepted=True,
                                      person=request.user.get_profile(),
                                      event=event)

    # create a comment object and save
    comment = Comment(content_object=event,
                      user=request.user,
                      site=Site.objects.get_current(),
                      user_name=request.user.get_full_name(),
                      user_email=request.user.email,
                      comment=request.POST["comment_text"],
                      submit_date=datetime.now(),
                      ip_address=request.META["REMOTE_ADDR"],
                      is_public=True)
    comment.save()

    # return an empty response
    return HttpResponse()
Ejemplo n.º 5
0
def approve(request, id):
    config = get_object_or_404(Config, pk=id)
    if config.locked:
        error = ("This configuration is locked. Only admins can unlock "
                 "it.")
        return details(request, config.id, error=error)
    old_status = config.status
    message = ''
    if request.method == 'POST':  # If the form has been submitted...
        data = request.POST
        if data.get('approved', False):
            # check if domains and domains requests are null
            if not config.domains.all() and not config.domainrequests.all():
                error = """Can't approve this configuration. There is no
                        correlated domain."""
                return details(request, id, error=error)
            # check if domain names already exist
            for domain in config.domainrequests.all():
                if Domain.objects.filter(name=domain).exclude(
                        Q(config__status='deleted') |
                        Q(config__status='invalid')):
                    error = """Can't approve this configuration. Domain is
                            already used by another approved configuration."""
                    return details(request, id, error=error)
            config.status = 'approved'
            for domain in config.domainrequests.all():
                exists = Domain.objects.filter(name=domain)
                if exists:
                    claimed = exists[0]
                    claimed.config = config
                else:
                    claimed = Domain(name=domain.name,
                                     config=config)
                claimed.save()
                domain.delete()
        elif data.get('denied', False):
            # Check mandatory comment when invalidating
            if data['comment'] == 'Other - invalid':
                if not data['commenttext']:
                    error = "Enter a comment."
                    return details(request, id, error=error)
                message = data['commenttext']
            else:
                message = data['comment']
            config.status = 'invalid'
        else:
            raise ValueError("shouldn't get here")
        config.save()
        comment = Comment(user_name='ISPDB System',
                          site_id=settings.SITE_ID)
        c = "<ul><li><b>Status</b> changed from <b><i>%s</i></b> to \
             <b><i>%s</i></b> by %s</li></ul>\n %s" % (old_status,
            config.status, request.user.email, message)
        comment.comment = c
        comment.content_type = ContentType.objects.get_for_model(Config)
        comment.object_pk = config.pk
        comment.save()

    return HttpResponseRedirect('/details/' + id)  # Redirect after POST
Ejemplo n.º 6
0
    def testCommentNotifications(self):
        c = Client()

        u = User.objects.create(username="******", email="*****@*****.**", 
                                is_superuser=False, is_staff=False)
        u.set_password('abcde')
        u.save()
        self.assertEquals(c.login(username='******', 
                                  password='******'), True)        
        
        p = BasicPost.objects.published()[0]
        
        response = c.post('/notifications/notify_comment/?next=/', 
                          {'name' : 'comment',
                           'app_label': 'post',
                           'model': p.get_class_name().lower(),
                           'pk': p.pk}, 
                          follow=True)
        self.assertEquals(response.status_code, 200)
        
        from notifications.models import Notification, CommentNotification, Recipient
        
        notifications = Notification.objects.select_subclasses()
        self.assertEquals(len(notifications), 1)
        self.assertEquals(type(notifications[0]), CommentNotification)
        
        recipients = Recipient.objects.all()
        self.assertEquals(len(recipients), 1)

        from django.contrib.comments.models import Comment
        from django.contrib.contenttypes.models import ContentType
        
        ct = ContentType.objects.get(app_label='post', 
                                     model=p.get_class_name().lower()) 
        cmt = Comment(content_type=ct, 
                    object_pk=p.pk, 
                    site=Site.objects.get_current(), 
                    user_name="joe", 
                    user_email='*****@*****.**', 
                    comment="Test comment")        
        cmt.save()
        
        from notifications.management.commands.processnotifications import Command
        
        cmd = Command()
        self.assertEquals(cmd.execute_notifications(['comment']), 1)
        
        response = c.post('/notifications/remove_comment_notification/?next=/', 
                           {'name' : 'comment',
                           'app_label': 'post',
                           'model': p.get_class_name().lower(),
                           'pk': p.pk}, 
                          follow=True)
        self.assertEquals(response.status_code, 200)

        recipients = Recipient.objects.all()
        self.assertEquals(len(recipients), 0)
Ejemplo n.º 7
0
 def get_comment(self, new_data):
     "Helper function"
     return Comment(None, self.get_user_id(), new_data["content_type_id"],
         new_data["object_id"], new_data.get("headline", "").strip(),
         new_data["comment"].strip(), new_data.get("rating1", None),
         new_data.get("rating2", None), new_data.get("rating3", None),
         new_data.get("rating4", None), new_data.get("rating5", None),
         new_data.get("rating6", None), new_data.get("rating7", None),
         new_data.get("rating8", None), new_data.get("rating1", None) is not None,
         datetime.datetime.now(), new_data["is_public"], new_data["ip_address"], False, settings.SITE_ID)
Ejemplo n.º 8
0
 def test_get_user_name_from_comment(self):
     comment = Comment(user=None, user_name='')
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment),
                      "An Anonymous Contributor")
     comment.user_name = "Harry"
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment),
                      "Harry")
     user = UserFactory()
     comment.user = user
     self.assertEqual(publicweb_filters.get_user_name_from_comment(comment),
                      user.username)
Ejemplo n.º 9
0
	def setUp(self):
		self.username = '******'
		self.password = '******'
		self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
		self.c1 = Channel(
			slug='public',
			name='Public',
			site=Site.objects.get_current()
		)
		self.c2 = Channel(
			slug='another-channel',
			name='Another Channel',
			site=Site.objects.get_current()
		)
		self.p1 = Post(
			author=self.user,
			slug='unit-testing-unit-tests',
			title='Are you unit testing your unit tests? Learn all about the latest best practice: TDTDD',
			text='Lorem Ipsum etc.',
			status=Post.PUBLISHED_STATUS
		)
		self.p2 = Post(
			author=self.user,
			slug='tree-falls-forest',
			title='Tree Falls in Forest, No One Notices',
			published=datetime.now()+timedelta(days=1),
			status=Post.PUBLISHED_STATUS
		)
		self.p3 = Post(
			author=self.user,
			slug='tree-falls-forest-again',
			title='Tree Falls in Forest, Could There be a Tree Flu Epidemic?',
			status=Post.DRAFT_STATUS
		)
		self.i1 = Item(
			text='A Really Awesome Site',
			url='example.com',
			title='Example.com Homepage',
		)
		self.i2 = Item(
			text='Another Really Awesome Site',
			url='test.com',
			title='Test.com Homepage',
		)
		self.comment1 = Comment(
			site=Site.objects.get_current(),
			user=self.user,
			comment='Thanks for sharing.',
		
		)
Ejemplo n.º 10
0
def migrate_forum(db):
    category_id_map = {}
    for cat in fetch_all(db, "GDN_Category"):
        slug = CATEGORY_MAP.get(cat["UrlCode"], None)
        if not slug: continue
        category_id_map[cat["CategoryID"]] = (Category.objects.get(slug=slug),
                                              cat["UrlCode"])

    copied_posts, copied_comments = 0, 0
    for thread in fetch_all(db, "GDN_Discussion"):
        if thread["CategoryID"] not in category_id_map: continue
        cat, urlcode = category_id_map.get(thread["CategoryID"])
        new_post = Post(
            pk=thread["DiscussionID"],
            category=cat,
            title=(thread["Name"] if CATEGORY_MAP[urlcode] != "old" else
                   ("[%s] " % urlcode) + thread["Name"]),
            user=User.objects.get(pk=thread["InsertUserID"]),
            created_on=thread["DateInserted"],
            text=thread["Body"])
        new_post.save()
        new_post.created_on = thread["DateInserted"]
        new_post.save()
        patch("forum-post-%d" % new_post.id, thread["DateInserted"])

        comments = fetch_all(db,
                             "GDN_Comment",
                             DiscussionID=thread["DiscussionID"])
        for comment in comments:
            user = User.objects.get(pk=comment["InsertUserID"])
            new_comment = Comment(
                user=user,
                content_type=ContentType.objects.get_for_model(Post),
                object_pk=new_post.pk,
                comment=comment["Body"],
                site_id=settings.SITE_ID,
                submit_date=comment["DateInserted"])
            new_comment.save()
            patch("comment-%d" % new_comment.id, comment["DateInserted"])
            copied_comments += 1
        copied_posts += 1
        if copied_posts % 10 == 0:
            print "%d posts. %d comments." % (copied_posts, copied_comments)

    print "%d posts. %d comments." % (copied_posts, copied_comments)
Ejemplo n.º 11
0
    def parse_repo(self, project):
        starting_commit = project.svn_repo_commit
        client = pysvn.Client()
        client.set_interactive(False)
        client.set_default_username(project.svn_repo_username)
        client.set_default_password(project.svn_repo_password)
        commits = client.log(
            project.svn_repo_url,
            revision_start=pysvn.Revision(pysvn.opt_revision_kind.number,
                                          int(starting_commit)),
            revision_end=pysvn.Revision(pysvn.opt_revision_kind.head))

        match_string = re.compile('Fixes #[\d]+')
        issue_matches = []
        for x in commits:
            for message in match_string.findall(x.data['message']):
                issue_matches.append(x)

        number_string = re.compile('\d+')
        closed_status = models.Status.objects.get(slug="closed")
        for x in issue_matches:
            for y in number_string.findall(x.data['message']):
                try:
                    issue = models.Issue.objects.get(id=y)
                    if issue.status is closed_status:
                        continue
                except ObjectDoesNotExist:
                    continue

                issue.status = closed_status
                issue.save()
                comment = Comment()
                comment.user_name = "vcs_bot"
                comment.user_email = "*****@*****.**"
                comment.content_type = self.content_type
                comment.object_pk = issue.id
                comment.comment = x.data['message']
                comment.site = Site.objects.get(id=settings.SITE_ID)
                comment.save()
                project.git_repo_commit = x.data['revision'].number
                project.save()
Ejemplo n.º 12
0
def update_status(request, bug_id):
    bug = get_object_or_404(Bug, pk=bug_id)
    if request.method == 'POST':
        f = UpdateBugStatusForm(request.POST, bug=bug)
        if f.is_valid():
            if not (request.user == bug.resolver or
                    (bug.status != Bug.STATUS_ASSIGNED
                     and request.user.has_perm("users.gatekeeper"))):
                return Http404(
                    "You don't have privileges to change the status of this bug."
                )
            resolver = (get_object_or_404(User, pk=f.cleaned_data['resolver'])
                        if f.cleaned_data['resolver'] else request.user)
            original = (get_object_or_404(Bug, pk=f.cleaned_data['original'])
                        if f.cleaned_data['original'] else None)
            resolution = f.cleaned_data['resolution']
            if bug.update_status(status=f.cleaned_data['status'],
                                 resolver=resolver,
                                 original=original,
                                 resolution=resolution):
                bug.save()
                c = Comment()
                c.content_type = ContentType.objects.get(app_label="bugs",
                                                         model="bug")
                c.object_pk = bug.pk
                c.site = Site.objects.get(id=settings.SITE_ID)
                c.comment = '{0} has changed the status to {1}'.format(
                    request.user.username, bug.get_status_display())
                c.save()
                messages.success(request,
                                 "The status has been updated successfully.")
                return HttpResponseRedirect('/bugs/browse/{0}/{1}/{2}'.format(
                    bug.component.application.id, bug.component.id, bug.id))
    else:
        f = UpdateBugStatusForm(bug=bug)
    return render_to_response('bugs/detail.html', {
        'bug': bug,
        'update_form': f
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 13
0
def process_comment(request, commentform, post):
    print commentform.cleaned_data
    try:
        comment = Comment.objects.get(
            id=commentform.cleaned_data.get('id', None))
    except Comment.DoesNotExist:
        comment = Comment()
    comment.content_object = post
    comment.site = Site.objects.get_current()
    comment.user = request.user
    try:
        profile = UserProfile.objects.get(user=request.user)
        comment.user_url = profile.get_absolute_url()
    except UserProfile.DoesNotExist:
        pass
    comment.comment = strip_tags(commentform.cleaned_data['comment'])
    comment.submit_date = datetime.datetime.now()
    comment.ip_address = request.META['REMOTE_ADDR']
    comment.is_public = True
    comment.is_removed = False
    comment.save()
    return comment
Ejemplo n.º 14
0
    def parse_repo(self, project):
        repo = git.Repo(project.git_repo_path)
        starting_commit = project.git_repo_commit
        commits = repo.commits()
        for x in commits:
            if starting_commit == x.id:
                starting_commit = x
        index = commits.index(starting_commit)
        commits = commits[:index]
        match_string = re.compile('Fixes #[\d]+')
        issue_matches = []
        for x in commits:
            for message in match_string.findall(x.message):
                issue_matches.append(x)

        number_string = re.compile('\d+')
        closed_status = models.Status.objects.get(slug="closed")
        for x in issue_matches:
            for y in number_string.findall(x.message):
                try:
                    issue = models.Issue.objects.get(id=y)
                    if issue.status is closed_status:
                        continue
                except ObjectDoesNotExist:
                    continue

                issue.status = closed_status
                issue.save()
                comment = Comment()
                comment.user_name = "vcs_bot"
                comment.user_email = "*****@*****.**"
                comment.content_type = self.content_type
                comment.object_pk = issue.id
                comment.comment = x.message
                comment.site = Site.objects.get(id=settings.SITE_ID)
                comment.save()
                project.git_repo_commit = x.id
                project.save()
Ejemplo n.º 15
0
    def add_new_note(self, request, resource_type, resource_id):
        resource = request.resource

        if request.POST:

            #title = request.REQUEST.get('title');
            body = request.REQUEST.get('body')

            new_comment = Comment(content_object=resource,
                                  site=DjangoSite.objects.all()[0],
                                  user=request.user,
                                  user_name=request.user.username,
                                  user_email=request.user.email,
                                  user_url='',
                                  comment=body,
                                  ip_address=None,
                                  is_public=True,
                                  is_removed=False)

            new_comment.save()

            return self.response_success()

        return HttpResponse('')
Ejemplo n.º 16
0
    def import_comments(self, entry, comment_nodes):
        """Loops over comments nodes and import then
        in django.contrib.comments"""
        for comment_node in comment_nodes:
            is_pingback = comment_node.find('{%s}comment_type' %
                                            WP_NS).text == 'pingback'
            is_trackback = comment_node.find('{%s}comment_type' %
                                             WP_NS).text == 'trackback'

            title = 'Comment #%s' % (comment_node.find(
                '{%s}comment_id/' % WP_NS).text)
            self.write_out(' > %s... ' % title)

            content = comment_node.find('{%s}comment_content/' % WP_NS).text
            if not content:
                self.write_out(self.style.NOTICE('SKIPPED (unfilled)\n'))
                return

            submit_date = datetime.strptime(
                comment_node.find('{%s}comment_date' % WP_NS).text,
                '%Y-%m-%d %H:%M:%S')

            approvation = comment_node.find('{%s}comment_approved' %
                                            WP_NS).text
            is_public = True
            is_removed = False
            if approvation != '1':
                is_removed = True
            if approvation == 'spam':
                is_public = False

            comment_dict = {
                'content_object':
                entry,
                'site':
                self.SITE,
                'user_name':
                comment_node.find('{%s}comment_author/' % WP_NS).text[:50],
                'user_email':
                comment_node.find('{%s}comment_author_email/' % WP_NS).text
                or '',
                'user_url':
                comment_node.find('{%s}comment_author_url/' % WP_NS).text
                or '',
                'comment':
                content,
                'submit_date':
                submit_date,
                'ip_address':
                comment_node.find('{%s}comment_author_IP/' % WP_NS).text or '',
                'is_public':
                is_public,
                'is_removed':
                is_removed,
            }
            comment = Comment(**comment_dict)
            comment.save()
            if approvation == 'spam':
                comment.flags.create(user=entry.authors.all()[0], flag='spam')
            if is_pingback:
                comment.flags.create(user=entry.authors.all()[0],
                                     flag='pingback')
            if is_trackback:
                comment.flags.create(user=entry.authors.all()[0],
                                     flag='trackback')

            self.write_out(self.style.ITEM('OK\n'))
Ejemplo n.º 17
0
 def testGetApproveURL(self):
     c = Comment(id=12345)
     self.assertEqual(comments.get_approve_url(c), "/approve/12345/")
Ejemplo n.º 18
0
 def testGetDeleteURL(self):
     c = Comment(id=12345)
     self.assertEqual(comments.get_delete_url(c), "/delete/12345/")
Ejemplo n.º 19
0
 def testGetFlagURL(self):
     c = Comment(id=12345)
     self.assertEqual(comments.get_flag_url(c), "/flag/12345/")
Ejemplo n.º 20
0
    def _process_email(self, mail, verbosity):  # pylint: disable=R0914
        logger = logging.getLogger('econsensus')

        #handle multipart mails, cycle through mail
        #until find text type with a full payload.
        if mail.is_multipart():
            for message in mail.get_payload():
                if message.get_content_maintype() == 'text':
                    msg_string = self._strip_string(message.get_payload(),
                                                    verbosity)
                    if msg_string:
                        break
        else:
            msg_string = self._strip_string(mail.get_payload(), verbosity)

        if not msg_string:
            logger.error(
                "[EMAIL REJECTED] From '%s' Reason: Email payload empty" %
                mail['From'])
            return

        #Must match email 'from' address to user
        from_match = re.search('([\w\-\.]+@\w[\w\-]+\.+[\w\-]+)', mail['From'])
        if from_match:
            self._print_if_verbose(
                verbosity, "Found email 'from' '%s'" % from_match.group(1))
            try:
                user = User.objects.get(email=from_match.group(1))
            except ObjectDoesNotExist:
                logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known User" \
                             % (mail['From'], from_match.group(1)))
                return
            except MultipleObjectsReturned:
                logger.error("[EMAIL REJECTED] From '%s' Reason: Query returned several Users for id '%s'" \
                             % (mail['From'], from_match.group(1)))
                return
            self._print_if_verbose(verbosity,
                                   "Matched email to user '%s'" % user)
        else:
            logger.error(
                "[EMAIL REJECTED] From '%s' Reason: Unrecognised email address format"
                % mail['From'])
            return

        #Must match email 'to' address to organization
        org_match = re.search('([\w\-\.]+)@\w[\w\-]+\.+[\w\-]+', mail['To'])
        if org_match:
            self._print_if_verbose(
                verbosity, "Found email 'to' '%s'" % org_match.group(1))
            try:
                organization = Organization.objects.get(
                    slug=org_match.group(1))
            except ObjectDoesNotExist:
                logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known Organization" \
                             % (mail['From'], org_match.group(1)))
                return
            except MultipleObjectsReturned:
                logger.error("[EMAIL REJECTED] From '%s' Reason: Query returned several Organizations for id '%s'" \
                             % (mail['From'], org_match.group(1)))
                return
            self._print_if_verbose(
                verbosity,
                "Matched email to organization '%s'" % organization.name)
        else:
            logger.error(
                "[EMAIL REJECTED] From '%s' Reason: Couldn't pull Organization from '%s'"
                % (mail['From'], mail['To']))
            return

        #User must be a member of the Organization
        if organization not in Organization.active.get_for_user(user):
            self._print_if_verbose(
                verbosity, "User %s is not a member of Organization %s" %
                (user.username, organization.name))
            logger.error("[EMAIL REJECTED] From '%s' Reason: User '%s' is not a member of Organization '%s'" \
                         % (mail['From'], user.username, organization.name))
            return

        #Look for feedback types in the message body
        rating = Feedback.COMMENT_STATUS
        description = msg_string
        parse_feedback = re.match('(\w+)\s*:\s*([\s\S]*)', msg_string,
                                  re.IGNORECASE)
        if parse_feedback:
            description = parse_feedback.group(2)
            rating_match = re.match('question|danger|concerns|consent|comment',
                                    parse_feedback.group(1), re.IGNORECASE)
            if rating_match:
                self._print_if_verbose(
                    verbosity,
                    "Found feedback rating '%s'" % rating_match.group())
                rating = dict(Feedback.RATING_CHOICES).values().index(
                    rating_match.group().lower())

        # Determine whether email is in reply to a notification
        subject_match = re.search('\[EC#(\d+)(?:\\\\(\d+)(?:\\\\(\d+))?)?\]',
                                  mail['Subject'])
        if subject_match:
            #Check that the user has the right to comment against the decision.
            if subject_match.group(1):
                self._print_if_verbose(
                    verbosity, "Found decision id '%s' in Subject" %
                    subject_match.group(1))
                try:
                    decision = Decision.objects.get(pk=subject_match.group(1))
                except ObjectDoesNotExist:
                    logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known Decision" \
                                 % (mail['From'], subject_match.group(1)))
                    return
                except MultipleObjectsReturned:
                    logger.error("[EMAIL REJECTED] From '%s' Reason: Query returned several Decisions for id '%s'" \
                                 % (mail['From'], subject_match.group(1)))
                    return
                if user not in decision.organization.users.all():
                    logger.error("[EMAIL REJECTED] From '%s' Reason: User cannot reply to decision #%s because they are not a member of that organization." \
                                 % (mail['From'], subject_match.group(1)))
                    return

            #process comment or feedback against feedback
            if subject_match.group(2):
                self._print_if_verbose(
                    verbosity, "Found feedback id '%s' in Subject" %
                    subject_match.group(2))
                try:
                    feedback = Feedback.objects.get(pk=subject_match.group(2))
                except ObjectDoesNotExist:
                    logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known Feedback" \
                                 % (mail['From'], subject_match.group(2)))
                    return
                except MultipleObjectsReturned:
                    logger.error("[EMAIL REJECTED] From '%s' Reason: Query returned more than one Feedback for id '%s'" \
                                 % (mail['From'], subject_match.group(2)))
                    return

                if parse_feedback and rating_match:
                    decision = feedback.decision
                    self._print_if_verbose(
                        verbosity,
                        "Creating feedback with rating '%s' and description '%s'."
                        % (rating, description))
                    feedback = Feedback(author=user,
                                        decision=decision,
                                        rating=rating,
                                        description=description)
                    feedback.save()
                    logger.info(
                        "User '%s' added feedback via email to decision #%s" %
                        (user, decision.id))
                    self._print_if_verbose(
                        verbosity,
                        "Found corresponding object '%s'" % decision.excerpt)
                else:
                    comment_text = msg_string
                    self._print_if_verbose(
                        verbosity, "Creating comment '%s'." % (comment_text))
                    comment = Comment(user=user,
                                      user_name=user.get_full_name(),
                                      user_email=user.email,
                                      comment=comment_text,
                                      content_object=feedback,
                                      object_pk=feedback.id,
                                      content_type=ContentType.objects.get(
                                          app_label="publicweb",
                                          model="feedback"),
                                      submit_date=timezone.now(),
                                      site=Site.objects.get_current())
                    comment.save()
                    logger.info(
                        "User '%s' added comment via email to feedback #%s" %
                        (user, feedback.id))
                    self._print_if_verbose(
                        verbosity, "Found corresponding object '%s'" %
                        feedback.description)

            #process feedback against decision
            elif subject_match.group(1):
                self._print_if_verbose(
                    verbosity,
                    "Creating feedback with rating '%s' and description '%s'."
                    % (rating, description))
                feedback = Feedback(author=user,
                                    decision=decision,
                                    rating=rating,
                                    description=description)
                feedback.save()
                logger.info(
                    "User '%s' added feedback via email to decision #%s" %
                    (user, decision.id))
                self._print_if_verbose(
                    verbosity,
                    "Found corresponding object '%s'" % decision.excerpt)

            else:
                self._print_if_verbose(
                    verbosity,
                    "No id found in message subject: %s" % mail['Subject'])
                logger.error("[EMAIL REJECTED] From '%s' Reason: No id present." \
                             % mail['From'])
        # Email was not in reply to a notification so create a new proposal
        else:
            proposal_match = re.search('proposal', mail['Subject'],
                                       re.IGNORECASE)
            if proposal_match:
                decision = Decision(author=user, editor=user, status=Decision.PROPOSAL_STATUS, organization=organization, \
                                    description=msg_string)
                decision.save()
                self._print_if_verbose(
                    verbosity, "User '%s' created decision #%s via email" %
                    (user, decision.id))
                logger.info("User '%s' created decision #%s via email" %
                            (user, decision.id))

            else:
                logger.error("[EMAIL REJECTED] From '%s' Reason: Email was not in reply to a notification and body didn't contain keyword 'proposal'" \
                             % mail['From'])
Ejemplo n.º 21
0
    def parse_message(self, message, raw_data):
        ## Get project slug
        match = re.search("\[[\w-]+\]", message['subject'])
        project_slug = match.group().lstrip('[').rstrip(']')

        ## Get email address
        #print message['from']
        match = re.search(r'[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z]*.[a-zA-Z]+',
                               message['from'])
        #print match.group()
        email_addy = match.group()
        ## Get Issue Number (if exists)
        match = re.search("Issue #[\d]+", message['subject'])
        if match:
            issue_string = match.group()
            issue_num = issue_string.lstrip("Issue #")
            issue_title = message['subject'][match.end():].lstrip(" - ")
        else:
            issue_num = None
            match = re.search("\[[\w-]+\]", message['subject'])
            issue_title = message['subject'][match.end():]
            issue_title =  issue_title.lstrip(": ")

        ## Get our django objects
        try:
            project = models.Project.objects.get(slug=project_slug)
        except ObjectDoesNotExist:
            return

        try:
            user = User.objects.get(email=email_addy)
            can_comment = utils.check_permissions('comment', user, project)
        except ObjectDoesNotExist:
            can_comment = project.allow_anon_comment
            user = None

        try:
            issue = models.Issue.objects.get(id=issue_num)
        except ObjectDoesNotExist:
            issue = None

        body = raw_data[message.startofbody:]
        content_type = ContentType.objects.get(model='issue')

        #print can_comment
        if can_comment:
            if issue is not None:
                comment = Comment()
                if user is not None:
                    comment.user_name = user.username
                    comment.user_email = user.email
                else:
                    comment.user_name = email_addy
                    comment.user_email = email_addy

                comment.content_type = content_type
                comment.object_pk = issue.id
                comment.comment = body
                comment.site = Site.objects.get(id=settings.SITE_ID)
                comment.save()
            else:
                issue = models.Issue()
                issue.name = issue_title
                issue.project = project
                issue.description = body
                status = models.Status.objects.get(id=1)
                priority = models.Priority.objects.get(id=1)
                issue_type = models.IssueType.objects.get(id=1)
                issue.status = status
                issue.priority = priority
                issue.issue_type = issue_type
                issue.save()