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)
def get_context_data(self, **kwargs): context = super(DetailItem, self).get_context_data(**kwargs) if self.object.__class__.__name__ == 'Serial': votes = Voting(self.object, self.request.user) context['watched'] = False context['truecomment'] = 0 context['actors'] = self.object.actor_set.all()[:10] context['seasons'] = self.object.season_set.all() context['reviews'] = self.object.review_set.all()[:3] context['has_review'] = True context['votes'] = votes context['vote_succes'] = False if context['reviews'] == 0: context['has_review'] = False if self.request.user.is_authenticated(): profile = self.request.user.get_profile() if profile.watched(self.object): context['watched'] = True if 'postcomment' in self.request.POST and self.request.POST['comment'] is not None: type = ContentType.objects.get(app_label='sdata', model='serial') site = Site.objects.get(id=1) comments_count = str(Comment.objects.all().count()) comment = Comment(content_type=type, content_object=self.object, object_pk=comments_count, site=site, user=self.request.user, comment=self.request.POST['comment']) comment.save() context['truecomment'] = 1 if 'watch' in self.request.GET: profile.watch.add(serial) profile.save() context['watched'] = True if 'vote' in self.request.POST: votes.set_votes(self.request.POST['vote']) context['vote_succes'] = True return context
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()
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)
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('')
def comment(request): context = {} rid = request.POST['id'] recipe = Recipe.objects.get(id = rid) context['recipe'] = recipe context['ingredients'] = recipe.ingredients.all() context['steps'] = recipe.steps.all() context['user'] = request.user context['rating'] = RatingForm() context['comment'] = CommentForm() context['comments'] = recipe.comments.all() context['autocompleteform'] = AutocompleteSearchForm() if request.method == 'GET': print 1 return render(request, 'foodchaser/recipe_view.html', context) if request.method == 'POST': print 3 comment = CommentForm(request.POST) if not comment.is_valid(): return render(request, 'foodchaser/recipe_view.html', context) text = Comment(text=comment.cleaned_data['comment'], \ owner=request.user) text.save() recipe.comments.add(text) context['comments'] = recipe.comments.all() return render(request, 'foodchaser/recipe_view.html', context)
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()
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()
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'))
def anon_comment(request): if request.META.has_key('HTTP_REFERER'): referer = request.META.get('HTTP_REFERER', '') else: referer = str(followee_username) name = request.POST['anon_name'] comment = request.POST['comment'] inv_code = request.POST['inv_code'] content_type_id= request.POST['content_type'] object_id=request.POST['object_pk'] if name and comment and inv_code : anon_invite = get_object_or_404(Anon_Conversation_Invite, code=inv_code) email = anon_invite.receiver # code to create an inactive user user = User.objects.filter(email='anon_'+email) if not user: user=User(username='******'+email,email='anon_'+email,password='******',is_active=0) user.save() random_hash = sha.new(str(user.email)+str(random.random())).hexdigest()[:10] user_profile = User_Profile(user=user,display_name=user.username,hash=random_hash,quip_repeat_total=1,quip_total=1) user_profile.save() page_setting = PageSetting(user=user) page_setting.save() not_setting = NotificationSetting(user=user) not_setting.save() #adding default followee, this should be the one who invited him to conv #invitee = anon_invite.sender #follow_user_nomail(user,invitee.username,0) else: user = user[0] # code to add comment from that user, ip not being captured content_type_kwip = get_object_or_404(ContentType,name='quip') comment = Comment(user=user,content_type=content_type_kwip,object_pk=object_id,comment=comment,is_public=1,site_id=1,valid_rating=0,is_removed=0) comment.save() quip = get_object_or_404(Quip,id=object_id) quip.comment_count+=1 # increment comment count quip.last_comment_at=datetime.datetime.now() # last comment time updated quip.save() cache_key = '%s_quip%s' % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,object_id,) cache.delete(cache_key) obj_user = quip.account.user timestamp = quip.created_at.strftime("%Y/%b/%d/%H%M%S") link = str(obj_user.username)+'/kwips/'+timestamp.lower() subscribe_comments = request.POST.get('subscribe_comments', False) if subscribe_comments: anon_follow_comments(user, quip) #link = str(request['url'][1:]) params_for_mail = {'#_1':obj_user.username,'#_2':name, '#_3':format_it(quip.original),'#_4':link,'#_5':datetime.datetime.now().ctime()} if user != obj_user: send_mail(str(obj_user.email),'kwippy <*****@*****.**>','comment_anon',params_for_mail) send_im(obj_user,'comment',params_for_mail) # follow up notifications to users for comment by an anon send_commentbyanon_emails(quip,user,name,params_for_mail,link) # follow up notifications to anons for comment by an anon send_anon_comment_emails(quip,user,params_for_mail,link) return HttpResponseRedirect(referer) # code to add follow up notification settings else: # flash msg return HttpResponseRedirect(referer)
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)
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
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)
def add(request): form = AddForm() message = None if request.method == "POST": form = AddForm(request.POST) if form.is_valid(): #create the objects with form.cleaned_data #can't use form.save() here, because it's not a modelform... print "form.cleaned_data",form.cleaned_data location,new = Location.objects.get_or_create(name=form.cleaned_data['location']) embed = SavedEmbed.objects.get(url=form.cleaned_data['url']) #TODO: convert date_uploaded to consistent format provider_name = embed.response['provider_name'] try: date_uploaded = dateutil.parser.parse(form.cleaned_data['date_uploaded']) #TEMP, may fail except ValueError,e: return HttpResponseServerError("I don't know how to parse this date:",form.cleaned_data['date_uploaded'],"from",provider_name) #could start with copy of form.cleaned_data, but that would pull in shared form fields media_dict = { 'date_uploaded':date_uploaded, 'title':form.cleaned_data['title'], 'slug':slugify(form.cleaned_data['title']), 'location':location, 'url':form.cleaned_data['url'], 'embed':embed, 'resolution':form.cleaned_data['resolution'], 'author_name':form.cleaned_data['author_name'], 'author_url':form.cleaned_data['author_url'], 'license':form.cleaned_data['license'], 'views':form.cleaned_data['views'], 'tags':form.cleaned_data['tags'], } print "media_dict",media_dict media = Media(**media_dict) print "media obj",media media.save() comment_dict = { 'user_name':form.cleaned_data['name'], 'comment':form.cleaned_data['review'], 'submit_date':datetime.now(), 'ip_address':request.META['REMOTE_ADDR'], 'content_type':ContentType.objects.get(app_label="mediacurate",model="media"), 'object_pk':media.pk, 'site_id':1 #assuming we're only using one site } print "comment_dict",comment_dict review = Comment(**comment_dict) review.save() message = "Thanks for adding <a href='%s'>%s</a>. Want to add another?" % (media.get_absolute_url(), media.title) #give the user a new form form = AddForm()
def process_doc_from_aries(go_xml_file, force=False): def should_restart_merops(art): if force: return True cutoff_state = State.objects.get(unique_name = 'finish_out') most_advanced_arts = art.most_advanced_article_state(same_typesetter=False) logger.debug("most_advanced_arts: %s" % most_advanced_arts) if most_advanced_arts: return (most_advanced_arts.state.progress_index < cutoff_state.progress_index) return False # add article to AI # extract doi from go.xml si_guid = os.path.basename(go_xml_file).split('.go.xml')[0] zip_file = os.path.join(os.path.dirname(go_xml_file), si_guid + '.zip') doi = PlosDoi(man_e.doi(zip_file)).short logger.info("Identified new aries-merops delivery {guid: %s} as %s" % (si_guid,doi)) celery_logger.info("watch_docs_from_aries identified new file for %s" % doi) art, new = Article.objects.get_or_create(doi=doi) art.typesetter = Typesetter.objects.get(name='Merops') art.si_guid = si_guid art.save() old_state = art.current_state if art.current_state.unique_name == 'new': delivery_state = State.objects.get(unique_name='delivered_from_aries') art_s = ArticleState(article=art, state=delivery_state) make_articlestate_if_new(art_s) if should_restart_merops(art): # extract manuscript, rename to doi.doc(x) logger.info("%s, delivery arrived, extracting manuscript and queueing for initial processing" % art.doi) user = get_or_create_user("aries_delivery_watch_bot", first_name="Aries Delivery Watch Robot") note = Comment(user=user, content_type=ContentType.objects.get_for_model(Article), object_pk = art.pk, submit_date = datetime.datetime.utcnow().replace(tzinfo=utc), comment = "A new package for this article was just delivered by Aries and AI will automatically attempt to extract a manuscript for Merops initial processing.", site_id = settings.SITE_ID) note.save() extract_manuscript_from_aries(zip_file, art ) else: # do nothing but write a note indicating there's a new export logger.info("%s, delivery arrived, but article in too advanced a state to automatically process, %s" % (art.doi, art.current_state.name)) user = get_or_create_user("aries_delivery_watch_bot", first_name="Aries Delivery Watch Robot") note = Comment(user=user, content_type=ContentType.objects.get_for_model(Article), object_pk = art.pk, submit_date = datetime.datetime.utcnow().replace(tzinfo=utc), comment = "A new package for this article was just delivered by Aries but was not automatically processed. Please review this package and repull the article if desired.", site_id = settings.SITE_ID) note.save()
def test_comment_post_save(self): content_type = ContentType.objects.get(model='issue') comment = Comment() comment.user_name = self.user.username comment.user_email = self.user.email comment.content_type = content_type comment.object_pk = 1 comment.comment = "This is a test comment" comment.site = Site.objects.get(id=settings.SITE_ID) comment.save() print comment.comment
def do_comments(cursor,ID,entry): cursor.execute('select comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content from wp_comments where comment_approved=1 and comment_post_ID=%s'%ID) comments=cursor.fetchall() for comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content in comments: comm=Comment(content_object=entry,site=SITE,user_name=unic(comment_author)[:49],user_email=comment_author_email,user_url=comment_author_url,comment=unic(comment_content),ip_address='127.0.0.1',submit_date=comment_date,is_public=True,is_removed=False) try: comm.save(force_insert=True) except Exception, e: print comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content print Exception, e if 'Incorrect string value' in e: comm.comment=comment_content.decode('latin1') comm.save(force_insert=True)
def test_notify_on_comment(self): # post some comment comment = Comment() content_type = ContentType.objects.get(model='issue') comment = Comment() comment.user_name = 'somebody' comment.user_email = '*****@*****.**' comment.content_type = content_type comment.object_pk = 1 comment.comment = "This is a test comment" comment.site = Site.objects.get(id=settings.SITE_ID) comment.save() self.assertEquals(len(mail.outbox), 3) self.check_outbox(self.recipient_list, "DjTracker: [unittest-project]: New Comment on Issue #1 by somebody", comment.comment)
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("{http://wordpress.org/export/1.0/}comment_type").text == "pingback" is_trackback = comment_node.find("{http://wordpress.org/export/1.0/}comment_type").text == "trackback" title = "Comment #%s" % (comment_node.find("{http://wordpress.org/export/1.0/}comment_id/").text) self.write_out(" > %s... " % title) content = comment_node.find("{http://wordpress.org/export/1.0/}comment_content/").text if not content: self.write_out(self.style.NOTICE("SKIPPED (unfilled)\n")) return submit_date = datetime.strptime( comment_node.find("{http://wordpress.org/export/1.0/}comment_date").text, "%Y-%m-%d %H:%M:%S" ) approvation = comment_node.find("{http://wordpress.org/export/1.0/}comment_approved").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("{http://wordpress.org/export/1.0/}comment_author/").text[:50], "user_email": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_email/").text or "", "user_url": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_url/").text or "", "comment": content, "submit_date": submit_date, "ip_address": comment_node.find("{http://wordpress.org/export/1.0/}comment_author_IP/").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"))
def newComment(model, request, comment): user = request.user c = Comment() c.user = user c.user_name = user.username c.user_email = user.email c.ip_address = request.META.get('REMOTE_ADDR') c.comment = comment # c.site = Site.objects.get(id=settings.SITE_ID) c.site_id = settings.SITE_ID c.content_type = ContentType.objects.get_for_model(model) c.object_pk = model.id c.save()
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)
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)
def handle_pingback(sender, source_url, view, args, author, excerpt, **kwargs): if view == entry: item = Entry.objects.get(id=args[0]) elif view == link: item = Link.objects.get(id=args[0]) else: return comment = Comment( content_type = ContentType.objects.get_for_model(item), object_pk = force_unicode(item.id), user_name = author, user_url = source_url, comment = excerpt, submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = True, is_removed = False) comment.save()
def test_get_one_comment_count(self): entry = Entry( author=self.user, slug='first-post', title='My First Post title', ) entry.save() comment = Comment( content_object=entry, site=Site.objects.get(pk=settings.SITE_ID), comment='iamcomment', ) comment.save() self.failUnlessEqual(entry._get_comment_count(), 1) entry.delete() comment.delete()
def create_comment(oldcomment): current_site = Site.objects.get(id=settings.SITE_ID) content_type = ContentType.objects.get(app_label='blog', model='post') fields = oldcomment['fields'] comment = Comment() comment.comment = fields['comment'] comment.ip_address = fields['ip_address'] comment.is_public = fields['is_public'] comment.is_removed = fields['is_removed'] comment.object_pk = fields['object_pk'] comment.submit_date = fields['submit_date'] comment.user = None comment.user_email = fields['user_email'] comment.user_name = fields['user_name'] comment.user_url = fields['user_url'] comment.content_type = content_type comment.site = current_site comment.save()
def comment_reply_post_create_handler(sender, instance, action, model, pk_set, using, **kwargs): if action == 'post_add': for replied_to_comment in instance.replied_to_comments.all(): moderator_settings = getattr(settings, 'MODERATOR', None) offset_timedelta = timedelta(seconds=1) if moderator_settings: if 'REPLY_BEFORE_COMMENT' in moderator_settings: if moderator_settings['REPLY_BEFORE_COMMENT']: offset_timedelta = timedelta(seconds=-1) created = False # We use try except DoesNotExist instead of get or create to # allow us to add a is_reply_comment to a newly created comment # which facilitates realtime_comment_classifier below to distinguish # between normal comments and reply comments. try: comment_obj = Comment.objects.get( content_type=replied_to_comment.content_type, object_pk=replied_to_comment.object_pk, site=replied_to_comment.site, submit_date=replied_to_comment.submit_date + offset_timedelta, user=instance.user, ) except Comment.DoesNotExist: comment_obj = Comment( content_type=replied_to_comment.content_type, object_pk=replied_to_comment.object_pk, site=replied_to_comment.site, submit_date=replied_to_comment.submit_date + offset_timedelta, user=instance.user, comment=instance.comment_text, ) comment_obj.is_reply_comment = True comment_obj.save() created = True if not created: comment_obj.comment = instance.comment_text comment_obj.save() if comment_obj not in instance.reply_comments.all(): instance.reply_comments.add(comment_obj)
def test_members_with_comment_by_same_user(self): user = random_user() idea = models.Idea(creator=user, title='Transit subsidy to Mars', text='Aliens need assistance.', state=self.state) idea.save() commenter = user comment = Comment() comment.user = commenter comment.content_object = idea comment.comment = 'Test' comment.is_public = True comment.is_removed = False comment.site_id = 1 comment.save() self.assertEqual(len(idea.members), 1) self.assertIn(user, idea.members)
def process_comment(request, commentform, post): 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
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()
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))
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()
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
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()
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()
def send_diet(request, diet_id): diet = get_object_or_404(Diet, pk = diet_id) form = SendDietForm(request.POST) if request.method == 'POST' and form.is_valid(): comment = Comment( content_object= diet.user, user_name = request.user.username, user_email = request.user.email, comment = form.cleaned_data["message"], submit_date = datetime.datetime.now(), site_id = settings.SITE_ID, is_public = True, is_removed = False, ) comment.save() diet.state='sent' diet.save() request.user.message_set.create(message="Zapisano dietę i wysłano wiadomość do pacjenta") return redirect(reverse('patients_list')) return direct_to_template(request, 'diet/send_diet.html', locals())
def serial(request, _name=''): name = ' '.join(_name.split('_')) try: profile = request.user.get_profile() dd = True except: dd = None serial = Serial.objects.get(original_name__iexact=name) truecomment = 0 if 'postcomment' in request.POST and request.POST['comment'] is not None: type = ContentType.objects.get(app_label='sdata', model='serial') site = Site.objects.get(id=1) comments_count = str(Comment.objects.all().count()) comment = Comment(content_type=type, content_object=serial, object_pk=comments_count, site=site, user=request.user, comment=request.POST['comment']) comment.save() truecomment = 1 watched = False if 'watch' in request.GET: profile.watch.add(serial) profile.save() watched = True if dd and profile.watched(serial): watched = True actors = serial.actor_set.all()[:10] seasons = Season.objects.filter(serial__original_name__iexact=name) reviews = Review.objects.filter(serial__original_name__iexact=name)[0:3] genres = serial.genre.all() countries = serial.country.all() votes = Voting(serial, request.user) vote_succes = False has_review = True if len(reviews) == 0: has_review = False if 'vote' in request.POST: votes.set_votes(request.POST['vote']) vote_succes = True return render_to_response('serial.html', {'watched': watched, 'serial': serial, 'seasons': seasons, 'vote_succes': vote_succes, 'reviews': reviews, 'has_review': has_review, 'genres': genres, 'countries': countries, 'actors': actors, 'votes': votes, 'truecomment': truecomment}, context_instance=RequestContext(request, processors=[_context]))
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('')
def handle(self, *args, **options): try: user = User.objects.get(username='******') except User.DoesNotExist: user = User.objects.create_user('dan', '*****@*****.**') self.author = user dom = parse(options['file']) # Create all the images images = {} for image in dom.getElementsByTagName('ATImage'): images.update(dict([self.image(image)])) self.site = Site.objects.get_current() for entry in dom.getElementsByTagName('BlogEntry'): post = self.entry(entry, images) comments = entry.getElementsByTagName('reply') for comment in comments: user_id = childElement(comment, 'id') submit_date = childDateElement(comment, 'date') if user_id == 'danfairs': comment_user = user else: comment_user = None ct = ContentType.objects.get_for_model(post) if not Comment.objects.filter(object_pk=post.pk, content_type=ct, submit_date=submit_date): # cheat, but works comment = Comment( user_name=childElement(comment, 'name'), user=comment_user, comment=childElement(comment, 'text'), content_object=post, site=self.site, submit_date=submit_date, ) comment.save()
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)) self._print_if_verbose(verbosity, "Matched email to user '%s'" % user) except: logger.error("[EMAIL REJECTED] From '%s' Reason: Email address does not correspond to any known User" % mail['From']) return 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)) self._print_if_verbose(verbosity, "Matched email to organization '%s'" % organization.name) except: logger.error("[EMAIL REJECTED] From '%s' Reason: '%s' does not correspond to any known Organization" \ % (mail['From'], org_match.group(1))) return 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 = rating_int(rating_match.group().lower()) # Determine whether email is in reply to a notification subject_match = re.search('\[(\d+)(?:\\\\(\d+)(?:\\\\(\d+))?)?\]', mail['Subject']) if subject_match: #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: logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known Feedback" \ % (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, 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, "Found decision id '%s' in Subject" % subject_match.group(1)) try: decision = Decision.objects.get(pk=subject_match.group(1)) except: logger.error("[EMAIL REJECTED] From '%s' Reason: id '%s' does not correspond to any known Decision" \ % (mail['From'], subject_match.group(1))) return 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'])
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'))
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'])
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()
def add(request): form = AddForm() message = None if request.method == "POST": form = AddForm(request.POST) if form.is_valid(): #first, check to see if it already exists try: exists = Media.objects.get(url=form.cleaned_data['url']) messages.info(request, "Thanks for adding that video. It's so good, we already have a copy. Want to add your review and tags?") #redirect, so we can clear url parameters return HttpResponseRedirect(exists.get_absolute_url()) except Media.DoesNotExist: #it's new, continue with the form pass #create the objects with form.cleaned_data #can't use form.save() here, because it's not a modelform... location,new = Location.objects.get_or_create(name=form.cleaned_data['location']) embed = SavedEmbed.objects.get(url=form.cleaned_data['url']) #TODO: convert date_uploaded to consistent format provider_name = embed.response['provider_name'] try: date_uploaded = dateutil.parser.parse(form.cleaned_data['date_uploaded']) #TEMP, may fail except ValueError,e: try: date_uploaded = datetime.fromtimestamp(float(form.cleaned_data['date_uploaded'])) except ValueError,e: date_uploaded = datetime.now() messages.debug("I don't know how to parse this date: %s from %s" % (form.cleaned_data['date_uploaded'],provider_name)) #could start with copy of form.cleaned_data, but that would pull in shared form fields media_dict = { 'date_uploaded':date_uploaded, 'title':form.cleaned_data['title'], 'slug':slugify(form.cleaned_data['title'])[:50], 'location':location, 'url':form.cleaned_data['url'], 'embed':embed, 'resolution':form.cleaned_data['resolution'], 'author_name':form.cleaned_data['author_name'], 'author_url':form.cleaned_data['author_url'], 'license':form.cleaned_data['license'], 'views':form.cleaned_data['views'], } media = Media(**media_dict) media.save() #have to do this after first save, so we get an object_id Tag.objects.update_tags(media,form.cleaned_data['tags']) media.save() if form.cleaned_data['review']: comment_dict = { 'user_name':form.cleaned_data['name'], 'comment':form.cleaned_data['review'], 'submit_date':datetime.now(), 'ip_address':request.META['REMOTE_ADDR'], 'content_type':ContentType.objects.get(app_label="mediacurate",model="media"), 'object_pk':media.pk, 'site_id':1 #assuming we're only using one site } review = Comment(**comment_dict) review.save() messages.success(request, "Thanks for adding <a href='%s'>%s</a>. Want to add another?" % (media.get_absolute_url(), media.title)) #redirect, so we can clear url parameters return HttpResponseRedirect('/add')