def live_tester(request): notify.send(sender=request.user, recipient=request.user, verb='you loaded the page') return render(request, 'test_live.html', { 'unread_count': request.user.notifications.unread().count(), 'notifications': request.user.notifications.all() })
def groups_member_abort(request, pk): """ This API used to allow user to abort the specific Groups in the system. (API version 1) * Requires token authentication. """ if request.method == 'POST': group = get_object_or_404(Group, id=pk) group.members.remove(request.user) group.save() # send action to action stream action.send(request.user, verb="aborted", target=group) notify.send( request.user, recipient=group.creator, verb=u'has aborted from your Group', level='success') return Response({ "code": status.HTTP_202_ACCEPTED, "status": "ok", }, status=status.HTTP_202_ACCEPTED) else: return Response({ "code": status.HTTP_400_BAD_REQUEST, "status": "error" }, status=status.HTTP_400_BAD_REQUEST)
def copy(request, id): new_ann = get_object_or_404(Announcement, pk=id) new_ann.pk = None # autogen a new primary key (quest_id by default) new_ann.title = "Copy of " + new_ann.title form = AnnouncementForm(request.POST or None, instance = new_ann) if form.is_valid(): new_announcement = form.save(commit=False) new_announcement.author = request.user new_announcement.datetime_created = timezone.now new_announcement.save() form.save() affected_users = User.objects.all().filter(is_active=True) notify.send( request.user, action=new_announcement, target=new_announcement, recipient=request.user, affected_users=affected_users, verb='posted') # return redirect('announcements:list', id=new_announcement.id) return redirect(new_announcement) context = { "title": "", "heading": "Copy an Announcement", "form": form, "submit_btn_value": "Create", } return render(request, "announcements/form.html", context)
def comment_ban(request, profile_id, toggle=False): profile = get_object_or_404(Profile, id=profile_id) if toggle: profile.banned_from_comments = not profile.banned_from_comments else: profile.banned_from_comments = True profile.save() if profile.banned_from_comments: icon = "<span class='fa-stack'>" + \ "<i class='fa fa-comment-o fa-flip-horizontal fa-stack-1x'></i>" + \ "<i class='fa fa-ban fa-stack-2x text-danger'></i>" + \ "</span>" notify.send( request.user, # action=profile.user, target=profile.user, recipient=request.user, affected_users=[profile.user, ], verb='banned you from making public comments', icon=icon, ) messages.warning(request, "<a href='" + profile.get_absolute_url() + "'>" + profile.user.username + "</a> banned from commenting publicly") else: messages.success( request, "Commenting ban removed for <a href='" + profile.get_absolute_url() + "'>" + profile.user.username + "</a>") return redirect_to_previous_page(request)
def comment_ban_toggle(request, profile_id): profile = get_object_or_404(Profile, id=profile_id) profile.banned_from_comments = not profile.banned_from_comments profile.save() if profile.banned_from_comments: icon="<span class='fa-stack'>" + \ "<i class='fa fa-comment-o fa-flip-horizontal fa-stack-1x'></i>" + \ "<i class='fa fa-ban fa-stack-2x text-danger'></i>" + \ "</span>" notify.send( request.user, # action=profile.user, target= profile.user, recipient=request.user, affected_users=[profile.user,], verb='banned you from making public comments', icon=icon, ) messages.success(request, profile.user.username + " banned from commenting publicly") return redirect('profiles:profile_list')
def test_disable_timezone(self): from_user = User.objects.create(username="******", password="******", email="*****@*****.**") to_user = User.objects.create(username="******", password="******", email="*****@*****.**") notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user) notification = Notification.objects.get(recipient=to_user) delta = timezone.now() - notification.timestamp self.assertTrue(delta.seconds < 60)
def register(request): '''注册视图''' form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST.copy()) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password"] re_password = form.cleaned_data["re_password"] real_name = form.cleaned_data["real_name"] if password == re_password: user = User.objects.create_user(username, email, password) user.is_staff = 0 user.first_name=real_name user.save() try: custom = Custom(user=user, is_custom = True) custom.save() except IntegrityError: last_user = User.objects.all().order_by('-id')[0] last_user.delete() notify.send(User.objects.get(id=1),recipient=user, verb='register successfully!') _login(request, username, password) return HttpResponse('<script>alert("注册成功!");location.replace(document.referrer);;</script>') else: return HttpResponse('<script>alert("两次密码必须相同!");history.go(-1);</script>') else: reverse_lazy('404') else: reverse_lazy('501') return render_to_response("custom-register.html", locals(), context_instance = RequestContext(request))
def suggestion_create(request): template_name='suggestions/suggestion_form.html' form = SuggestionForm(request.POST or None) if form.is_valid(): new_suggestion = form.save(commit=False) new_suggestion.user = request.user new_suggestion.status_timestamp = timezone.now() new_suggestion.save() icon="<i class='fa fa-lg fa-fw fa-lightbulb-o'></i>" notify.send( request.user, # action=profile.user, target= new_suggestion, recipient=request.user, affected_users=User.objects.filter(is_staff=True), verb='suggested:', icon=icon, ) messages.success(request, "Thank you for your suggestion! Mr C \ has to it review before it will be publicly visible.") return redirect(new_suggestion.get_absolute_url()) return render(request, template_name, {'form':form})
def new_user_receiver(sender,instance,created,*args, **kwargs): if created: new_profile, is_created = UserProfile.objects.get_or_create(user=instance) print new_profile, is_created notify.send(instance, recipient=MyUser.objects.get(username="******"), verb="New User created")
def post(self, *args, **kwargs): form = self.get_form() if form.is_valid(): parent_id = self.request.POST.get("parent_id") parent_comment = None if parent_id: try: parent_comment = Comment.objects.get(id=parent_id) except: parent_comment = None clean_text = form.cleaned_data["text"] new_comment = Comment.objects.create_comment( user=self.request.user, text=clean_text, path=self.request.get_full_path(), video=self.get_object(), parent=parent_comment) if parent_comment: comment = parent_comment else: comment = new_comment affected_users = comment.get_affected_users() notify.send(self.request.user, recipient=comment.user, action=comment, target=new_comment.video, affected_users=affected_users, verb=u'commented', ) messages.success(self.request, "Thank you for your comment") return HttpResponseRedirect(self.get_object().get_absolute_url()) else: messages.error(self.request, "There was an error") return HttpResponseRedirect(self.get_object().get_absolute_url())
def vehicle_create(request, user_id): form = VehicleAddForm(request.POST or None, request.FILES or None) user = get_object_or_404(CustomUser, pk=user_id) if request.user != user: raise Http404 if user.user_type == 'Passenger': raise Http404 if form.is_valid(): ride = form.save(commit=False) ride.user = user ride.save() rides = Vehicle.objects.filter(user=user).order_by('pk').reverse() ride = Vehicle.objects.filter(user=user).latest('pk') notify.send(user, recipient=user, verb='Added a Ride', level='success', action_object=ride,description='Ride Created Sucessfully') return render(request, 'app/vehicles/view_vehicles.html', {'user': user, 'rides': rides, 'message':True, 'message_title':'Ride Added Successfully.', 'message_body':'Your ride has been added successfully, view more options below', }) context = { 'user': user, 'form': form, } return render(request, 'app/vehicles/vehicle_form.html', context)
def atwho(text, sender, targetcomment, targetarticle, targetopic , targetproducts): commmentdecode = text.decode("utf8") pattern = re.compile(u'@([\u4e00-\u9fa5\w\-]+)') results = pattern.findall(commmentdecode) #用正则把评论中有@的字符串分割开 userlist = [] for item in results: try: user = MyUser.objects.get(username = item.encode('utf8')) except: user = None if user: user = MyUser.objects.get(username = item.encode('utf8')) notify.send(sender=sender, target_object=targetcomment , recipient = user, verb="@" , text=text, target_article = targetarticle , target_products = targetproducts , target_topic = targetopic) cachekey = "user_unread_count" + str(user.id) if cache.get(cachekey) != None: cache.incr(cachekey) else: unread = Notification.objects.filter(recipient = user).filter(read = False).count() cache.set(cachekey, unread, settings.CACHE_EXPIRETIME) userlist.append(item.encode('utf8')) return userlist
def jobrequest_delete(sender,**kwargs): jobrequest=kwargs['instance'] job = jobrequest.job # notify users of changed JobRequest notify.send(job.creator, verb="deleted {0}".format(jobrequest), recipient=jobrequest.organization.group)
def follow_group(request, pk): """ Creates the follow relationship between ``request.user`` and the ``Group`` """ group = get_object_or_404(Group, id=pk) # Check user is not member of the group if not group.members.filter(id=request.user.id).exists(): actions.follow(request.user, group, send_action=True) notify.send( request.user, recipient=group.creator, verb=u'has followed your Group', level='success') request.user.userprofile.follow_groups.add(group) messages.success( request, 'Successed, you are now following this Group.') else: actions.follow(request.user, group, send_action=False) messages.success( request, 'You are the member of this Group and automatically become the follower.') return redirect('groups:groups-detail', pk)
def detail(request, pk): post = Post.objects.get(pk=pk) replies = post.reply_set.all() if request.method == 'POST': form = ReplyForm(data=request.POST) if form.is_valid(): reply_content = form.cleaned_data['reply_content'] Reply.objects.create(post=post, replyer=request.user, content=reply_content) post.reply_count += 1 post.last_reply_time = timezone.now() post.save() if request.user != post.author: notify.send(request.user, recipient=post.author, verb='reply', target=post, description=reply_content, level='success') at_list = re.findall(r'@([A-Za-z0-9]+)', reply_content) if at_list: for at_user in at_list: try: user = GripUser.objects.get(username=at_user) notify.send(request.user, recipient=user, verb='at', description=reply_content, target=post, level='success') except GripUser.DoesNotExist: pass return HttpResponseRedirect('/p/'+pk) else: form = ReplyForm() context = { 'post': post, 'replies': replies, 'form': form, } template_name = 'payment/detail.html' return render(request, template_name, context)
def suggestion_approve(request, id): suggestion = get_object_or_404(Suggestion, id=id) suggestion.status = Suggestion.APPROVED suggestion.status_timestamp = timezone.now() suggestion.save() icon="<span class='fa-stack'>" + \ "<i class='fa fa-lightbulb-o fa-stack-1x'></i>" + \ "<i class='fa fa-check fa-stack-2x text-success'></i>" + \ "</span>" suggestion_badge = get_object_or_404(Badge, name="Human Baby") grant_badge(request, suggestion_badge.id ,suggestion.user.id) notify.send( request.user, # action=profile.user, target= suggestion, recipient=suggestion.user, affected_users=[suggestion.user,], verb='approved', icon=icon, ) messages.success(request, "Suggestion by " + str(suggestion.user) + " approved.") return redirect(suggestion.get_absolute_url())
def assertion_delete(request, assertion_id): assertion = get_object_or_404(BadgeAssertion, pk=assertion_id) if request.method=='POST': user = assertion.user notify.send( request.user, # action=..., target=assertion.badge, recipient=user, affected_users=[user,], icon="<span class='fa-stack'>" + \ "<i class='fa fa-certificate fa-stack-1x text-warning'></i>" + \ "<i class='fa fa-ban fa-stack-2x text-danger'></i>" + \ "</span>", verb='revoked') messages.success(request, ("Badge " + str(assertion) + " revoked from " + str(assertion.user) )) assertion.delete() return redirect('profiles:profile_detail', pk = user.id) template_name='badges/assertion_confirm_delete.html' return render(request, template_name, {'object':assertion})
def suggestion_approve(request, id): suggestion = get_object_or_404(Suggestion, id=id) # Todo move this into the model, not view! suggestion.status = Suggestion.APPROVED suggestion.status_timestamp = timezone.now() suggestion.save() icon = "<span class='fa-stack'>" + \ "<i class='fa fa-lightbulb-o fa-stack-1x'></i>" + \ "<i class='fa fa-check fa-stack-2x text-success'></i>" + \ "</span>" # TODO don't hardcode this, put it in the settings! suggestion_badge = get_object_or_404(Badge, pk=config.hs_suggestion_badge) grant_badge(request, suggestion_badge.id, suggestion.user.id) notify.send( request.user, # action=profile.user, target=suggestion, recipient=suggestion.user, affected_users=[suggestion.user, ], verb='approved', icon=icon, ) messages.success(request, "Suggestion by " + str(suggestion.user) + " approved.") return redirect(suggestion.get_absolute_url())
def event_notify(request, event, verb1, verb2): #notify user and committee members notify.send(request.user, recipient=request.user, verb=verb1 + ' ', target=event) for committee_member in list(User.objects.filter(is_staff=True)): #don't norify an attending committee member twice if committee_member is not request.user: notify.send(request.user, recipient=committee_member, verb= ' ' + verb2 + ' ', target=event)
def confirm(self): self.declined = False self.accepted = True self.confirmed = True self.save() notify.send(self.organization, verb="confirmed", action_object=self.job, recipient=self.organization.group, url=reverse('organization_dash', kwargs={'organization_id': self.organization.id}) + "?jobrequestID=" + str(self.id) ) # iterate through all jobrequests in this job and remove permission # for other jobrequests job = self.job job.closed = True job.save() for jr in job.jobrequests.all(): if jr != self: remove_perm('view_jobrequest',jr.job.creator,jr) remove_perm('view_jobrequest',jr.organization.group,jr) notify.send(self.organization, verb="has closed the job: ", action_object=self.job, recipient=jr.organization.group, # questionable use of url since user will not have permission to view anymore # url=reverse('organization_dash', # kwargs={'organization_id': jr.organization.id}) + # "?jobrequestID=" + str(jr.id) )
def add_perms_job(sender,**kwargs): # check if this post_save signal was generated from a Model create job=kwargs['instance'] if 'created' in kwargs and kwargs['created']: # allow creator to view and edit job assign_perm('view_job',job.creator,job) assign_perm('edit_job',job.creator,job) # allow requested orgs to view job for org in job.organizations.all(): assign_perm('view_job',org.group,job) else: # notify users of changed JobRequest if job.closed: jobrequests = job.jobrequests_accepted() else: jobrequests = job.jobrequests_accepted() | job.jobrequests_pending() for jobrequest in jobrequests: notify.send(job.creator, verb="modified", action_object=jobrequest, recipient=jobrequest.organization.group, url=reverse('organization_dash', kwargs = {'organization_id':jobrequest.organization.id})+ "?jobrequestID="+str(jobrequest.id) )
def comment_create_view(request): if request.method == "POST" and request.user.is_authenticated(): parent_id = request.POST.get('parent_id') video_id = request.POST.get('video_id') origin_path = request.POST.get('origin_path') try: video = Video.objects.get(id=video_id) except: video = None parent_comment = None if parent_id is not None: try: parent_comment = Comment.objects.get(id=parent_id) except: parent_comment = None if parent_comment is not None and parent_comment.video is not None: video = parent_comment.video form = CommentForm(request.POST) if form.is_valid(): comment_text = form.cleaned_data['comment'] if parent_comment is not None: # parent comments exists new_comment = Comment.objects.create_comment( user=request.user, path=parent_comment.get_origin, text=comment_text, video = video, parent=parent_comment ) affected_users = parent_comment.get_affected_users() notify.send( request.user, action=new_comment, target=parent_comment, recipient=parent_comment.user, affected_users=affected_users, verb='replied to' ) messages.success(request, 'Thank you for your response.', extra_tags='safe') return HttpResponseRedirect(parent_comment.get_absolute_url()) else: new_comment = Comment.objects.create_comment( user=request.user, path=origin_path, text=comment_text, video = video ) messages.success(request, 'Thank you for your comment.') return HttpResponseRedirect(new_comment.get_absolute_url()) else: messages.error(request, 'There was an error with your comment.') return HttpResponseRedirect(origin_path) else: raise Http404
def setUp(self): self.message_count = 10 self.from_user = User.objects.create_user(username="******", password="******", email="*****@*****.**") self.to_user = User.objects.create_user(username="******", password="******", email="*****@*****.**") self.to_user.is_staff = True self.to_user.save() for _ in range(self.message_count): notify.send(self.from_user, recipient=self.to_user, verb='commented', action_object=self.from_user)
def topicomment(request): if request.is_ajax() and request.method == 'POST': # print request.POST.get('comment') text = request.POST.get('comment') topicid = request.POST.get('topicid') topic = Topic.objects.get(pk=topicid) # print request.POST.get('comment') # print request.POST.get('topicid') user = request.user # print user try: c = Comment(user=user, topic=topic, text=text) c.save() if topic.writer != user: notify.send(sender=user, target_object= None , recipient = topic.writer, verb='#' , text=text, target_article = None , target_products = None , target_topic = topic) cachekey = "user_unread_count" + str(topic.writer.id) if cache.get(cachekey) != None: cache.incr(cachekey) else: unread = Notification.objects.filter(recipient = topic.writer).filter(read = False).count() cache.set(cachekey, unread, settings.CACHE_EXPIRETIME) topic.updated = timezone.now() instancesave.delay(topic) cachekey = "topic_comment_" + str(topicid) if cache.get(cachekey) != None: cache.incr(cachekey) else: cache.set(cachekey, topic.comment_set.count(), settings.CACHE_EXPIRETIME) userlist = atwho(text = text, sender = user, targetcomment = None, targetproducts = None , targetarticle = None, targetopic = topic) for item in userlist: atwhouser = MyUser.objects.get(username = item) # test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' # text = text.replace('@'+item+' ', test); test = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' test1 = "@<a href='" +'/user/'+str(atwhouser.id)+'/informations/'+"'>"+atwhouser.username+"</a>"+' ' text = text.replace('@'+item+' ', test); text = text.replace('@'+item+' ', test1); # c = Comment(user=user, topic=topic, text=text) # c.save() data = { "user": user.username, "text": text, "commentid": c.id } # print data['commentid'] json_data = json.dumps(data) print 'data' return HttpResponse(json_data, content_type='application/json') except: traceback.print_exc() raise Http404(traceback) else: raise Http404
def test_use_timezone(self): from_user = User.objects.create(username="******", password="******", email="*****@*****.**") to_user = User.objects.create(username="******", password="******", email="*****@*****.**") notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user) notification = Notification.objects.get(recipient=to_user) delta = ( timezone.now().replace(tzinfo=utc) - localtime(notification.timestamp, pytz.timezone(settings.TIME_ZONE)) ) self.assertTrue(delta.seconds < 60)
def active(request, active_string): username = decrypt_active_string(bytes(active_string, encoding='utf-8')) user = GripUser.objects.get(username=username) user.is_active = True user.save() notify.send(user, recipient=user, verb='active', target=user, description="用户已经激活", level='success') auth_login(request, user); return HttpResponseRedirect('/')
def send(users=[], label='', extra_context={}): print("send fired") if label == 'postman_message': print("send in pm fired") msg = extra_context['pm_message'] User = get_user_model() user = User.objects.get(pk=msg.sender_id) notify.send(user, recipient=users[0], verb='New message', description=msg.subject)
def new_user_receiver(sender, instance, created, *args, **kwargs): print "signal sent" if created: new_profile, is_created = UserProfile.objects.get_or_create(user=instance) notify.send(instance, recipient_object=MyUser.objects.get(username='******'), #admin user action='new user created',) print "new_profile, is_created:" print new_profile, is_created
def comment_create_view(request): if request.method == 'POST': parent_id = request.POST.get('parent_id') video_id = request.POST.get('video_id') origin_path = request.POST.get('origin_path') redirect_url = origin_path parent_comment = None video = None comment_form = CommentForm(request.POST) if comment_form.is_valid(): if video_id: try: video = Video.objects.get(id=video_id) except: messages.error(request, 'There was an error with your comment for this video.') if parent_id: try: parent_comment = Comment.objects.get(id=parent_id) video = parent_comment.video origin_path = parent_comment.origin except: messages.error(request, 'There was an error with your reply for this comment.') comment_text = comment_form.cleaned_data['comment'] new_comment = Comment.objects.create_comment( user = request.user, text = comment_text, path = origin_path, video = video, parent = parent_comment, ) if new_comment.is_child: affected_users = parent_comment.get_affected_users() notify.send( request.user, action=new_comment, verb='replied to', target=parent_comment, affected_users = affected_users, recipient=parent_comment.user,) redirect_url = parent_comment.get_absolute_url() else: notify.send( request.user, action=new_comment, verb='commented on', target=video, recipient=MyUser.objects.get(username="******")) redirect_url = new_comment.get_absolute_url() messages.success(request, 'Your comment has been added.') # messages.success(request, 'Your comment has been added.', extra_tags='safe') # NOTE: add extra_tags='safe' if you add html to message else: messages.error(request, 'There was an error with your comment.') return redirect_to(redirect_url) raise Http404
def get_success_url(self): action.send(self.request.user, verb='aborted', target=self.object) actions.unfollow(self.request.user, self.object, send_action=False) notify.send( self.request.user, recipient=self.object.creator, verb=u'has aborted from your Group', level='success') return reverse("groups:groups-detail", kwargs={'pk': self.kwargs['pk']})
def post(self, request, *args, **kwargs): """处理post请求""" # 限制评论频率 if int(comment_count_validate(request).content) >= 10: return HttpResponse('403 comment too frequently') if self.is_comment_too_long(request): return HttpResponse('403 comment too long') article = self.get_article(request, self.kwargs.get('article_id')) comment_form = CommentForm(request.POST) # 暂时用这种方法来检查空值,需优化 if request.POST['body'] == '': return HttpResponse('403 blank comment') # 创建新评论 if comment_form.is_valid(): new_comment = comment_form.save(commit=False) article_type = request.POST['article_type'] # 对二级评论,赋值root节点的id if self.kwargs.get('node_id'): node_id = kwargs.get('node_id') # 判断回复属于博文、读书或视频 # 并赋值父级评论 parent_comment = Comment.objects.get(id=node_id) new_comment.parent_id = parent_comment.get_root().id new_comment.reply_to = parent_comment.user new_comment.content_object = article new_comment.user = request.user new_comment.save() # 对不是staff的父级评论发送通知 if not parent_comment.user.is_superuser: notify.send( request.user, recipient=parent_comment.user, verb='回复了你', target=article, description=article_type, action_object=new_comment, ) else: new_comment.reply_to = None new_comment.content_object = article new_comment.user = request.user new_comment.save() # 给staff发送通知 if not request.user.is_staff: notify.send( request.user, recipient=User.objects.filter(is_staff=1), verb='回复了你', target=article, description=article_type, action_object=new_comment, ) # 给博主发送通知邮件 # send_email_to_user(recipient='*****@*****.**') # 输入不合法 else: raise PermissionDenied redirect_url = article.get_absolute_url() + '#F' + str(new_comment.id) return redirect(redirect_url)
def my_handler(sender, instance, created, **kwargs): notify.send(instance, verb='was contributed')
def _send_add_comment_notifications(user, comment, entity, locale, translation): # On translation comment, notify: # - authors of other translation comments in the thread # - translation author # - translation reviewers if translation: recipients = set(translation.comments.values_list("author__pk", flat=True)) if translation.user: recipients.add(translation.user.pk) if translation.approved_user: recipients.add(translation.approved_user.pk) if translation.unapproved_user: recipients.add(translation.unapproved_user.pk) if translation.rejected_user: recipients.add(translation.rejected_user.pk) if translation.unrejected_user: recipients.add(translation.unrejected_user.pk) # On team comment, notify: # - project-locale translators or locale translators # - locale managers # - authors of other team comments in the thread # - authors of translation comments # - translation authors # - translation reviewers else: recipients = set() project_locale = ProjectLocale.objects.get( project=entity.resource.project, locale=locale, ) translations = Translation.objects.filter(entity=entity, locale=locale) # Only notify translators of the project if defined translators = project_locale.translators_group.user_set.values_list( "pk", flat=True ) if not translators: translators = locale.translators_group.user_set.values_list("pk", flat=True) recipients = recipients.union(translators) recipients = recipients.union( locale.managers_group.user_set.values_list("pk", flat=True) ) recipients = recipients.union( Comment.objects.filter(entity=entity, locale=locale).values_list( "author__pk", flat=True ) ) recipients = recipients.union( Comment.objects.filter(translation__in=translations).values_list( "author__pk", flat=True ) ) recipients = recipients.union(translations.values_list("user__pk", flat=True)) recipients = recipients.union( translations.values_list("approved_user__pk", flat=True) ) recipients = recipients.union( translations.values_list("unapproved_user__pk", flat=True) ) recipients = recipients.union( translations.values_list("rejected_user__pk", flat=True) ) recipients = recipients.union( translations.values_list("unrejected_user__pk", flat=True) ) for recipient in User.objects.filter(pk__in=recipients).exclude(pk=user.pk): notify.send( user, recipient=recipient, verb="has added a comment in", action_object=locale, target=entity, description=comment, )
def createCivi(request): ''' USAGE: use this function to insert a new connected civi into the database. :return: (200, ok) (400, missing required parameter) (500, internal error) ''' a = Account.objects.get(user=request.user) thread_id = request.POST.get('thread_id') data = { 'author': Account.objects.get(user=request.user), 'title': request.POST.get('title', ''), 'body': request.POST.get('body', ''), 'c_type': request.POST.get('c_type', ''), 'thread': Thread.objects.get(id=thread_id) } try: civi = Civi(**data) civi.save() # hashtags = request.POST.get('hashtags', '') # split = [x.strip() for x in hashtags.split(',')] # for str in split: # if not Hashtag.objects.filter(title=str).exists(): # hash = Hashtag(title=str) # hash.save() # else: # hash = Hashtag.objects.get(title=str) # # civi.hashtags.add(hash.id) links = request.POST.getlist('links[]', '') if links: for civi_id in links: linked_civi = Civi.objects.get(id=civi_id) civi.linked_civis.add(linked_civi) # If response related_civi = request.POST.get('related_civi', '') if related_civi: # parent_civi = Civi.objects.get(id=related_civi) # parent_civi.links.add(civi) parent_civi = Civi.objects.get(id=related_civi) parent_civi.responses.add(civi) if parent_civi.author.user.username != request.user.username: notify.send( request.user, # Actor User recipient=parent_civi.author.user, # Target User verb=u'responded to your civi', # Verb action_object=civi, # Action Object target=civi.thread, # Target Object popup_string="{user} responded to your civi in {thread}". format(user=a.full_name, thread=civi.thread.title), link="/{}/{}".format("thread", thread_id)) else: #not a reply, a regular civi c_qs = Civi.objects.filter(thread_id=thread_id) accounts = Account.objects.filter(pk__in=c_qs.distinct( 'author').values_list('author', flat=True)) data = { "command": "add", "data": json.dumps(civi.dict_with_score(a.id)), } # channels_Group("thread-%s" % thread_id).send({ # "text": json.dumps(data), # }) for act in accounts: if act.user.username != request.user.username: notify.send( request.user, # Actor User recipient=act.user, # Target User verb=u'created a new civi', # Verb action_object=civi, # Action Object target=civi.thread, # Target Object popup_string= "{user} created a new civi in the thread {thread}". format(user=a.full_name, thread=civi.thread.title), link="/{}/{}".format("thread", thread_id)) return JsonResponse({'data': civi.dict_with_score(a.id)}) except Exception as e: return HttpResponseServerError(reason=str(e))
def my_handler(sender, instance, created, **kwargs): notify.send(instance, recipient=User.objects.get(pk=10), verb='was saved')
def load_ports_table(ports): updated_port_objects = [] for port in ports: # any json object missing name, portdir, version will be ignored try: name = port['name'] portdir = port['portdir'] version = port['version'] except KeyError: continue # get or create an object for this port port_object, port_created = Port.objects.get_or_create( name__iexact=name, defaults={'name': name}) updated_port_objects.append(port_object) # cache the original object for comparison old_object = { 'version': port_object.version, 'replaced_by': port_object.replaced_by, 'license': port_object.license } # add or update rest of the fields port_object.portdir = portdir port_object.version = version port_object.description = port.get('description', '') port_object.homepage = port.get('homepage', '') port_object.epoch = port.get('epoch', 0) port_object.platforms = port.get('platforms') port_object.long_description = port.get('long_description', '') port_object.revision = port.get('revision', 0) port_object.closedmaintainer = port.get( 'closedmaintainer', False) port_object.license = parse_license(port.get('license', '')) port_object.replaced_by = port.get('replaced_by') port_object.active = True port_object.save() # This function also updates the version_update_at field if the the version # has changed. notification_verb = generate_notifications_verb( old_object, port_object) if not notification_verb == "": notify.send(port_object, recipient=port_object.subscribers.all(), verb=notification_verb, portdir=port_object.portdir, version=port_object.version) # first remove any related category and then add port_object.categories.clear() # remove any related objects categories = set() for category in port.get('categories', []): category_object, created = Category.objects.get_or_create( name__iexact=category, defaults={'name': category}) categories.add(category_object) port_object.categories.add(*categories) # remove any related maintainers and then add all port_object.maintainers.clear() for maintainer in port.get('maintainers', []): maintainer_name = maintainer.get('email', {}).get('name', '') maintainer_domain = maintainer.get('email', {}).get('domain', '') maintainer_github = maintainer.get('github', '') maintainer_object, created = Maintainer.objects.get_or_create( name__iexact=maintainer_name, domain__iexact=maintainer_domain, github__iexact=maintainer_github, defaults={ 'name': maintainer_name, 'domain': maintainer_domain, 'github': maintainer_github }) maintainer_object.ports.add(port_object) # delete all related variants and then add all port_object.variants.all().delete() for v in port.get('vinfo', []): try: variant = v['variant'] except KeyError: continue except TypeError: break v_obj, created = Variant.objects.get_or_create( port_id=port_object.id, variant__iexact=variant, defaults={'variant': variant}) v_obj.description = v.get('description') v_obj.requires = v.get('requires') v_obj.conflicts = v.get('conflicts') v_obj.is_default = True if v.get( 'is_default') is True else False v_obj.save() if port.get('notes'): port_object.notes = port.get('notes') port_object.save() print("Updated port: ", port_object.name) return updated_port_objects
def openvas_scanner(scan_ip, project_id, sel_profile, user): """ The function is launch the OpenVAS scans. :param scan_ip: :param project_id: :param sel_profile: :return: """ openvas = OpenVAS_Plugin(scan_ip, project_id, sel_profile) try: scanner = openvas.connect() except Exception as e: notify.send(user, recipient=user, verb='OpenVAS Setting not configured') subject = 'Archery Tool Notification' message = 'OpenVAS Scanner failed due to setting not found ' email_notify(user=user, subject=subject, message=message) return notify.send(user, recipient=user, verb='OpenVAS Scan Started') subject = 'Archery Tool Notification' message = 'OpenVAS Scan Started' email_notify(user=user, subject=subject, message=message) scan_id, target_id = openvas.scan_launch(scanner) date_time = datetime.now() save_all = scan_save_db(scan_id=str(scan_id), project_id=str(project_id), scan_ip=scan_ip, target_id=str(target_id), date_time=date_time, scan_status=0.0) save_all.save() openvas.scan_status(scanner=scanner, scan_id=scan_id) time.sleep(5) vuln_an_id(scan_id=scan_id, project_id=project_id) notify.send(user, recipient=user, verb='OpenVAS Scan Completed') all_openvas = scan_save_db.objects.all() all_vuln = '' total_high = '' total_medium = '' total_low = '' for openvas in all_openvas: all_vuln = openvas.total_vul total_high = openvas.high_total total_medium = openvas.medium_total total_low = openvas.low_total subject = 'Archery Tool Notification' message = 'OpenVAS Scan Completed <br>' \ 'Total: %s <br>Total High: %s <br>' \ 'Total Medium: %s <br>Total Low %s' % (all_vuln, total_high, total_medium, total_low) email_notify(user=user, subject=subject, message=message) return HttpResponse(status=201)
def launch_zap_scan(target_url, project_id, rescan_id, rescan, scan_id, user): """ The function Launch ZAP Scans. :param target_url: Target URL :param project_id: Project ID :return: """ # Connection Test zap_connect = zap_plugin.zap_connect() try: zap_connect.spider.scan(url=target_url) notify.send(user, recipient=user, verb='ZAP Scan Started') except Exception: notify.send(user, recipient=user, verb='ZAP Connection Not Found') subject = 'ZAP Connection Not Found' message = 'ZAP Scanner failed due to setting not found ' email_notify(user=user, subject=subject, message=message) print("ZAP Connection Not Found") return HttpResponseRedirect('/webscanners/') # Load ZAP Plugin zap = zap_plugin.ZAPScanner(target_url, project_id, rescan_id, rescan) zap.exclude_url() time.sleep(3) zap.cookies() time.sleep(3) date_time = datetime.now() try: save_all_scan = zap_scans_db(project_id=project_id, scan_url=target_url, scan_scanid=scan_id, date_time=date_time, rescan_id=rescan_id, rescan=rescan, vul_status='0') save_all_scan.save() notify.send(user, recipient=user, verb='ZAP Scan URL %s Added' % target_url) except Exception as e: print(e) zap.zap_spider_thread(thread_value=30) spider_id = zap.zap_spider() zap.spider_status(spider_id=spider_id) zap.spider_result(spider_id=spider_id) notify.send(user, recipient=user, verb='ZAP Scan Spider Completed') time.sleep(5) """ ZAP Scan trigger on target_url """ zap_scan_id = zap.zap_scan() zap.zap_scan_status(scan_id=zap_scan_id, un_scanid=scan_id) """ Save Vulnerability in database """ time.sleep(5) all_vuln = zap.zap_scan_result() time.sleep(5) save_all_vuln = zap.zap_result_save( all_vuln=all_vuln, project_id=project_id, un_scanid=scan_id, ) print(save_all_vuln) all_zap_scan = zap_scans_db.objects.all() total_vuln = '' total_high = '' total_medium = '' total_low = '' for data in all_zap_scan: total_vuln = data.total_vul total_high = data.high_vul total_medium = data.medium_vul total_low = data.low_vul notify.send(user, recipient=user, verb='ZAP Scan URL %s Completed' % target_url) subject = 'Archery Tool Scan Status - ZAP Scan Completed' message = 'ZAP Scanner has completed the scan ' \ ' %s <br> Total: %s <br>High: %s <br>' \ 'Medium: %s <br>Low %s' % (target_url, total_vuln, total_high, total_medium, total_low) email_notify(user=user, subject=subject, message=message)
def test_notificar_enviar(self): results = notify.send(self.emissor, recipient=self.recetor, verb='mensagem', action_object=self.emissor) for result in results: if result[0] is notify_handler: self.assertEqual(len(result[1]), 1) self.assertEqual(type(result[1][0]), Notificacao)
def favourite_updated(recipient, obj): notify.send(obj, recipient=recipient, verb="A favourited item has been changed:", target=obj)
def workgroup_item_new(recipient, obj): notify.send(obj, recipient=recipient, verb="was modified in the workgroup", target=obj.workgroup)
def write(request): if request.method == 'POST': # get form data subject = request.POST.get('subject') single = request.POST.get('single') to_customers = request.POST.get('toCustomer', 0) to_suppliers = request.POST.get('toSupplier', 0) email_list = json.loads(request.POST.get('emailList')) body = request.POST.get('body') # send notification/emails if single: try: user = Supplier.objects.get(email=single) context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() except: #user = Supplier.objects.get(email=single) context = {'user': single, 'body': body, 'subject': subject} emailit.api.send_mail(single, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=request.user, verb=subject, description=body, emailed=True) notif.save() return HttpResponse('success') for email in email_list: user = User.objects.get(email=email) if user.send_mail: context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=user, verb=subject, description=body, emailed=True) notif.save() else: notify.send(request.user, recipient=user, verb=subject, description=body) # check for bulk group mailing/notification if 1 == int(to_customers): customers = Customer.objects.all() for customer in customers: context = { 'user': customer.name, 'body': body, 'subject': subject } emailit.api.send_mail(customer.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=customer, verb=subject, description=body, emailed=True) notif.save() if 1 == int(to_suppliers): suppliers = Supplier.objects.all() for supplier in suppliers: context = { 'user': supplier.name, 'body': body, 'subject': subject } emailit.api.send_mail(supplier.email, context, 'notification/emails/notification_email', from_email=request.user.email) notif = Notification(actor=request.user, recipient=supplier, verb=subject, description=body, emailed=True) notif.save() HttpResponse(email_list) ctx = { 'users': User.objects.all().order_by('-id'), 'templates': EmailTemplate.objects.all().order_by('-id') } if request.method == 'GET': if request.GET.get('pk'): try: product = ProductVariant.objects.get( pk=int(request.GET.get('pk'))) ctx = { 'product': product, 'users': User.objects.all().order_by('-id'), 'templates': EmailTemplate.objects.all().order_by('-id') } return TemplateResponse( request, 'dashboard/notification/write_single.html', ctx) except Exception, e: return HttpResponse(e)
def post(self, request, *args, **kwargs): try: base_url = request.META.get('HTTP_HOST') user = request.user data = request.data shipment_status = data.get('shipmentStatus') activate = data.get('status') transaction_id = data.get('transactionId') transaction = Transaction.objects.get(tr_id=transaction_id) shipment = transaction.shipment if shipment_status == self.SHIPMENT_STATUS['NOT_SHIPPED']: if activate: shipment.not_shipped = True shipment.shipped = False shipment.arrived_at_port = False else: shipment.not_shipped = False elif shipment_status == self.SHIPMENT_STATUS[ 'APPROBATION_RECEIVED']: if activate: shipment.app_received = True else: shipment.app_received = False elif shipment_status == self.SHIPMENT_STATUS['SHIPPED']: if activate: shipment.shipped = True shipment.not_shipped = False else: shipment.not_shipped = True shipment.shipped = False shipment.arrived_at_port = False elif shipment_status == self.SHIPMENT_STATUS['ARRIVED_AT_PORT']: if activate: shipment.arrived_at_port = True shipment.shipped = True shipment.not_shipped = False else: shipment.arrived_at_port = False else: raise Exception('No Status Provided!') shipment.save() txt_status = shipment_status.replace('_', ' ') peers = user.profile.get_notification_peers() if activate: log = self.ACTIVATED_MESSAGE % txt_status notification_msg = '<strong> File Id %s</strong> %s status activated' % ( transaction.file_id, txt_status) TransactionChangeLog.add_change_log(user, log, transaction) notify.send(user, recipient=peers, verb=notification_msg, description='international_trade', state='dashboard.transactionView', state_params={'id': transaction.file_id}, user_image=user.profile.get_profile_pic()) else: log = self.DEACTIVATED_MESSAGE % txt_status notification_msg = '<strong> File Id %s</strong> %s status deactivated' % ( transaction.file_id, txt_status) TransactionChangeLog.add_change_log(user, log, transaction) notify.send(user, recipient=peers, verb=notification_msg, description='international_trade', state='dashboard.transactionView', state_params={'id': transaction.file_id}, user_image=user.profile.get_profile_pic()) return Response({ 'transactionObj': transaction.get_complete_obj(base_url, user), 'success': True, 'message': 'Transaction Shipment status changed successfully' }) except Exception, e: return Response({'success': False, 'message': str(e)})
def task_detail(request, assignment_id, submit_num=None, login=None): submits = Submit.objects.filter( assignment__pk=assignment_id, ).order_by('-id') if is_teacher(request.user): submits = submits.filter(student__username=login) else: submits = submits.filter(student__pk=request.user.id) if login != request.user.username: raise PermissionDenied() assignment = get_object_or_404(AssignedTask, id=assignment_id) testset = create_taskset(assignment.task, login if login else request.user.username) is_announce = False if (assignment.assigned > datetime.now() or not assignment.clazz.students.filter( username=request.user.username)) and not is_teacher( request.user): is_announce = True if not assignment.task.announce: raise Http404() data = { # TODO: task and deadline can be combined into assignment ad deal with it in template 'task': assignment.task, 'assigned': assignment.assigned if is_announce else None, 'deadline': assignment.deadline, 'submits': submits, 'text': testset.load_readme().announce if is_announce else testset.load_readme(), 'inputs': None if is_announce else testset, 'max_inline_content_bytes': MAX_INLINE_CONTENT_BYTES, 'has_pipeline': bool(testset.pipeline), 'upload': not is_teacher(request.user) or request.user.username == login, } current_submit = None if submit_num: try: current_submit = submits.get(submit_num=submit_num) except Submit.DoesNotExist: raise Http404() elif submits: current_submit = submits[0] return redirect( reverse('task_detail', kwargs={ 'assignment_id': current_submit.assignment_id, 'submit_num': current_submit.submit_num, 'login': current_submit.student.username, })) if current_submit: data = {**data, **get(current_submit)} data['comment_count'] = current_submit.comment_set.count() moss_res = moss_result(current_submit.assignment.task.id) if moss_res and (is_teacher(request.user) or moss_res.opts.get('show_to_students', False)): svg = moss_res.to_svg(login=current_submit.student.username, anonymize=not is_teacher(request.user)) if svg: data['has_pipeline'] = True res = PipeResult("plagiarism") res.title = "Plagiarism checker" prepend = "" if is_teacher(request.user): if not moss_res.opts.get('show_to_students', False): prepend = "<div class='text-muted'>Not shown to students</div>" prepend += f'<a href="/teacher/task/{current_submit.assignment.task_id}/moss">Change thresholds</a>' res.html = f""" {prepend} <style> #plagiarism svg {{ width: 100%; height: 300px; border: 1px solid rgba(0,0,0,.125); }} </style> <div id="plagiarism">{svg}</div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/svg-pan-zoom.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => {{ const observer = new MutationObserver((changes) => {{ if(changes[0].target.classList.contains('active')) {{ svgPanZoom('#plagiarism svg') }} }}); observer.observe(document.querySelector('#plagiarism svg').closest('.tab-pane'), {{ attributeFilter: ['class'] }}); }}); </script> """ data['results'].pipelines = [res] + data['results'].pipelines submit_nums = sorted(submits.values_list('submit_num', flat=True)) current_idx = submit_nums.index(current_submit.submit_num) if current_idx - 1 >= 0: data['prev_submit'] = submit_nums[current_idx - 1] if current_idx + 1 < len(submit_nums): data['next_submit'] = submit_nums[current_idx + 1] data['total_submits'] = submits.count() data['late_submit'] = assignment.deadline and submits.order_by( 'id').reverse()[0].created_at > assignment.deadline data['diff_versions'] = [(s.submit_num, s.created_at) for s in submits.order_by('id')] data['job_status'] = not get_submit_job_status( current_submit.jobid).finished if request.method == 'POST': s = Submit() s.student = request.user s.assignment = assignment s.submit_num = Submit.objects.filter( assignment__id=s.assignment.id, student__id=request.user.id).count() + 1 solutions = request.FILES.getlist('solution') tmp = request.POST.get('paths', None) if tmp: paths = [f.rstrip('\r') for f in tmp.split('\n') if f.rstrip('\r')] else: paths = [f.name for f in solutions] upload_submit_files(s, paths, solutions) # we need submit_id before putting the job to the queue s.save() s.jobid = evaluate_submit(request, s).id s.save() # delete previous notifications Notification.objects.filter( action_object_object_id__in=[str(s.id) for s in submits], action_object_content_type=ContentType.objects.get_for_model( Submit), verb='submitted', ).delete() if not is_teacher(request.user): notify.send( sender=request.user, recipient=[assignment.clazz.teacher], verb='submitted', action_object=s, important=any([s.assigned_points is not None for s in submits]), ) return redirect( reverse('task_detail', kwargs={ 'login': s.student.username, 'assignment_id': s.assignment.id, 'submit_num': s.submit_num }) + '#result') return render(request, 'web/task_detail.html', data)
def send_person_signals(sender, instance, created, **kwargs): """ This creates the notifications we use to send email alerts of changes to people """ if instance.action_type not in ('person-update', 'person-create'): return person = instance.person content_type = ContentType.objects.get_for_model(person) verb = 'updated' if created: verb = 'created' alerts = Alert.objects.filter(target_content_type=content_type, target_object_id=person.id) users_alerted = set() # This is here to make writing tests a bit easier as # it means you don't need to create a versions object # or add an extra if it's not required try: changes = person.extra.version_diffs[0] except (IndexError, ObjectDoesNotExist): changes = None for alert in alerts: if alert.user not in users_alerted: users_alerted.add(alert.user) notify.send(instance.user, action_object=person, verb=verb, recipient=alert.user, changes=changes) # FIXME: this doesn't handle people being removed from an area posts = PostExtra.objects.filter(base__memberships__person=person, elections__current=True) for post in posts: area = post.base.area if area is not None: content_type = ContentType.objects.get_for_model(area) alerts = Alert.objects.filter(target_content_type=content_type, target_object_id=area.id) for alert in alerts: if alert.user not in users_alerted: users_alerted.add(alert.user) notify.send(instance.user, action_object=person, verb=verb, recipient=alert.user, changes=changes) # TODO: not sure this is the correct way to do this memberships = Membership.objects.filter( person=person, on_behalf_of__classification='Party', extra__election__current=True) for membership in memberships: party = membership.on_behalf_of if party is not None: content_type = ContentType.objects.get_for_model(party) alerts = Alert.objects.filter(target_content_type=content_type, target_object_id=party.id) for alert in alerts: if alert.user not in users_alerted: users_alerted.add(alert.user) notify.send(instance.user, action_object=person, verb=verb, recipient=alert.user, changes=changes)
def ajax_add_comment(request, post_id): """ Function to add comments through AJAX. Currently IN USE. """ if request.method == "POST": post_pk = request.POST['post_pk'] parent_pk = request.POST['comment_pk'] comment_content = request.POST['comment_content'] # comment_content = comment_content.strip() # print(comment_content) parent = None post = None parent_qs = Comment.objects.filter(pk=parent_pk) post_qs = Post.objects.filter(pk=post_pk) # Check if parent comment exists if parent_qs is not None: parent = parent_qs.first() # Check if post exists if post_qs is not None: post = post_qs.first() # Create comment new_comment, created = Comment.objects.get_or_create( user=request.user, post=post, comment_text=comment_content, parent=parent, ) user_profile = UserProfile.objects.get(user=request.user) if user_profile.avatar: # URL of profile picture avatar_url = user_profile.avatar.url # Time at which comment is created timestamp = new_comment.timestamp # Count of children comment children_count = new_comment.children().count() if children_count == 1: count_str = str(children_count) + " Reply |" else: count_str = str(children_count) + " Replies |" # Sending notifications if created: # Check if comment is NOT a reply to other comment. if parent is None: # Check if comment author and post author are NOT same. if str(user_profile.user) != str(post.author): notify.send( user_profile, recipient=post.author, verb='commented on your post.', target=post, dp_url=user_profile.avatar.url, prof_url=reverse( "User Profile", kwargs={'username': user_profile.user.username}), post_url=reverse("post_detail", kwargs={'slug': post.slug}), actor_name=user_profile.user.first_name, timestamp_=timesince(timezone.now()), ) else: # This comment is reply to some other comment. # Check if comment author and post author are NOT same. if str(user_profile.user) != str(post.author): # Send notification to post author. notify.send( user_profile, recipient=post.author, verb='replied to a comment.', target=post, dp_url=user_profile.avatar.url, prof_url=reverse( "User Profile", kwargs={'username': user_profile.user.username}), post_url=reverse("post_detail", kwargs={'slug': post.slug}), actor_name=user_profile.user.first_name, timestamp_=timesince(timezone.now()), ) # Check if parent comment author and post author are NOT same. if str(parent.user) != str(user_profile.user): # Send notification to Parent comment author notify.send( user_profile, recipient=parent.user, verb='replied to your comment.', target=post, dp_url=user_profile.avatar.url, prof_url=reverse( "User Profile", kwargs={'username': user_profile.user.username}), post_url=reverse("post_detail", kwargs={'slug': post.slug}), actor_name=user_profile.user.first_name, timestamp_=timesince(timezone.now()), ) # Sending notifications ended # Other URL's add_comment_url = reverse('Add Comment', kwargs={'post_id': post_pk}) user_profile_url = reverse('User Profile', kwargs={'username': request.user.username}) if created: result = "SS" else: result = "ERR" """ Acronyms: SS: Success ERR: Error """ response_data = { 'result': result, 'avatarURL': avatar_url, 'userName': request.user.username, 'timestamp': timesince(timestamp), 'countStr': count_str, 'addCommentURL': add_comment_url, 'userProfileURL': user_profile_url, # 'commentCount': comment_count, # 'replyCount': reply_count, } return JsonResponse(response_data)
def launch_arachni_scan(target, project_id, rescan_id, rescan, scan_id, user): global scan_run_id, scan_status arachni_hosts = None arachni_ports = None username = user.username all_arachni = arachni_settings_db.objects.filter(username=username) for arachni in all_arachni: arachni_hosts = arachni.arachni_url arachni_ports = arachni.arachni_port arachni = PyArachniapi.arachniAPI(arachni_hosts, arachni_ports) check = [ "xss_event", "xss", "xss_script_context", "xss_tag", "xss_path", "xss_dom_script_context", "xss_dom", "sql_injection", "sql_injection_differential", "sql_injection_timing", "no_sql_injection", "no_sql_injection_differential", "code_injection", "code_injection_timing", "ldap_injection", "path_traversal", "file_inclusion", "response_splitting", "os_cmd_injection", "os_cmd_injection_timing", "rfi", "unvalidated_redirect", "unvalidated_redirect_dom", "xpath_injection", "xxe", "source_code_disclosure", "allowed_methods", "backup_files", "backup_directories", "common_admin_interfaces", "common_directories", "common_files", "http_put", "webdav", "xst", "credit_card", "cvs_svn_users", "private_ip", "backdoors", "htaccess_limit", "interesting_responses", "html_objects", "emails", "ssn", "directory_listing", "mixed_resource", "insecure_cookies", "http_only_cookies", "password_autocomplete", "origin_spoof_access_restriction_bypass", "form_upload", "localstart_asp", "cookie_set_for_parent_domain", "hsts", "x_frame_options", "insecure_cors_policy", "insecure_cross_domain_policy_access", "insecure_cross_domain_policy_headers", "insecure_client_access_policy", "csrf", "common_files", "directory_listing", ] data = {"url": target, "checks": check, "audit": {}} d = json.dumps(data) scan_launch = arachni.scan_launch(d) time.sleep(3) try: scan_data = scan_launch.data for key, value in scan_data.items(): if key == 'id': scan_run_id = value notify.send(user, recipient=user, verb='Arachni Scan Started on URL %s' % target) except Exception: notify.send(user, recipient=user, verb='Arachni Connection Not found') print("Arachni Connection Not found") return date_time = datetime.now() try: save_all_scan = arachni_scan_db( username=username, project_id=project_id, url=target, scan_id=scan_id, date_time=date_time, rescan_id=rescan_id, rescan=rescan, ) save_all_scan.save() except Exception as e: print(e) scan_data = scan_launch.data for key, value in scan_data.items(): if key == 'id': scan_run_id = value scan_sum = arachni.scan_summary(id=scan_run_id).data for key, value in scan_sum.items(): if key == 'status': scan_status = value while scan_status != 'done': status = '0' if scan_sum['statistics']['browser_cluster'][ 'queued_job_count'] and scan_sum['statistics'][ 'browser_cluster']['total_job_time']: status = 100 - scan_sum['statistics']['browser_cluster']['queued_job_count'] * 100 / \ scan_sum['statistics']['browser_cluster']['total_job_time'] arachni_scan_db.objects.filter( username=username, scan_id=scan_id).update(scan_status=int(status)) scan_sum = arachni.scan_summary(id=scan_run_id).data for key, value in scan_sum.items(): if key == 'status': scan_status = value time.sleep(3) if scan_status == 'done': xml_report = arachni.scan_xml_report(id=scan_run_id).data root_xml = ET.fromstring(xml_report) arachni_xml_parser.xml_parser(username=username, project_id=project_id, scan_id=scan_id, root=root_xml, target_url=target) arachni_scan_db.objects.filter( username=username, scan_id=scan_id).update(scan_status='100') print("Data uploaded !!!!") notify.send(user, recipient=user, verb='Arachni Scan Completed on URL %s' % target)
def update_order(request, pk): user = request.user order = get_object_or_404(Order, id=pk) if request.method == 'POST': print("Updated Order form submitted") form = NewOrderForm(request.POST or None, request.FILES or None) if form.is_valid(): print("Updated Order form Validated") prv_order = order try: order.design = request.FILES['design'] file_type = order.design.url.split('.')[-1] file_type = file_type.lower() if file_type not in DESIGN_FILE_TYPES: messages.error(request, 'Image file must be .zip, .rar or .gz') return render(request, 'client/update_order.html', {'form': form, 'order':order}) # order.design.url = str(datetime.now())+file_type except MultiValueDictKeyError: None shipping_address = form.cleaned_data.get('shipping_address') client_address = form.cleaned_data.get('client_address') order.client = user if not shipping_address or client_address is True: order.shipping_address = str(user.profile.address) + ", " + str(user.profile.city) + ", " \ + str(user.profile.state) + ", " + str(user.profile.country) + ", " \ + str(user.profile.zip_code) else: order.shipping_address = shipping_address order.submitted_by = user order.client_name = user.profile.get_screen_name() order.order_type = form.cleaned_data.get('order_type') order.deadline = form.cleaned_data.get('deadline') order.quantity = form.cleaned_data.get('quantity') order.budget = form.cleaned_data.get('budget') order.specification = form.cleaned_data.get('specification') order.order_status = prv_order.order_status order.save() # order_history = OrderHistory(order) # order_history.save() order_history = OrderHistory() order_history.copy(order) order_history.save() msg = "Client :{0} updated the order with id:{1}".format( request.user.profile.get_screen_name(), order.id) _recipient = User.objects.filter(Q(profile__account_type=1) | Q(profile__account_type=2)) print(_recipient) notify.send(request.user, recipient=_recipient, verb=msg, action_object=order) messages.success(request, 'The order is updated successfully.') else: messages.error(request, 'Order save failed.') return render(request, 'client/update_order.html', {'form': form, 'order':order}) form = NewOrderForm(instance=Order, initial={ 'order_type' : order.order_type, 'deadline' : order.deadline, 'quantity' : order.quantity, 'budget' : order.budget, 'shipping_address' : order.shipping_address, 'specification' : order.specification, }) # print(form) return render(request, 'client/update_order.html', {'form': form, 'order':order})
def launch_arachni_scan(target, project_id, rescan_id, rescan, scan_id, user): arachni_hosts = None arachni_ports = None username = user.username all_arachni = arachni_settings_db.objects.filter(username=username) for arachni in all_arachni: arachni_hosts = arachni.arachni_url arachni_ports = arachni.arachni_port arachni = PyArachniapi.arachniAPI(arachni_hosts, arachni_ports) check = [ "xss_event", "xss", "xss_script_context", "xss_tag", "xss_path", "xss_dom_script_context", "xss_dom", "sql_injection", "sql_injection_differential", "sql_injection_timing", "csrf", "common_files", "directory_listing", ] data = {"url": target, "checks": check, "audit": {}} d = json.dumps(data) scan_launch = arachni.scan_launch(d) time.sleep(3) try: scan_data = scan_launch.data for key, value in scan_data.items(): if key == 'id': scan_run_id = value notify.send(user, recipient=user, verb='Arachni Scan Started on URL %s' % target) except Exception: notify.send(user, recipient=user, verb='Arachni Connection Not found') print("Arachni Connection Not found") return date_time = datetime.now() try: save_all_scan = arachni_scan_db( username=username, project_id=project_id, url=target, scan_id=scan_id, date_time=date_time, rescan_id=rescan_id, rescan=rescan, ) save_all_scan.save() except Exception as e: print(e) scan_data = scan_launch.data for key, value in scan_data.items(): if key == 'id': scan_run_id = value scan_sum = arachni.scan_summary(id=scan_run_id).data for key, value in scan_sum.items(): if key == 'status': scan_status = value while scan_status != 'done': status = '0' if scan_sum['statistics']['browser_cluster'][ 'queued_job_count'] and scan_sum['statistics'][ 'browser_cluster']['total_job_time']: status = 100 - scan_sum['statistics']['browser_cluster']['queued_job_count'] * 100 / \ scan_sum['statistics']['browser_cluster']['total_job_time'] arachni_scan_db.objects.filter( username=username, scan_id=scan_id).update(scan_status=status) scan_sum = arachni.scan_summary(id=scan_run_id).data for key, value in scan_sum.items(): if key == 'status': scan_status = value time.sleep(3) if scan_status == 'done': xml_report = arachni.scan_xml_report(id=scan_run_id).data root_xml = ET.fromstring(xml_report) arachni_xml_parser.xml_parser(username=username, project_id=project_id, scan_id=scan_id, root=root_xml) arachni_scan_db.objects.filter( username=username, scan_id=scan_id).update(scan_status='100') print("Data uploaded !!!!") notify.send(user, recipient=user, verb='Arachni Scan Completed on URL %s' % target)
def complete(request, submission_id): """ When a student has completed a quest, or is commenting on an already completed quest, this view is called - The submission is marked as completed (by the student) - If the quest is automatically approved, then the submission is also marked as approved, and available quests are recalculated directly/synchromously, so that their available quest list is up to date """ submission = get_object_or_404(QuestSubmission, pk=submission_id) origin_path = submission.get_absolute_url() # http://stackoverflow.com/questions/22470637/django-show-validationerror-in-template if request.method == "POST": # for some reason Summernote is submitting the form in the background when an image is added or # dropped into the widget We need to ignore that submission # https://github.com/summernote/django-summernote/issues/362 if 'complete' not in request.POST and 'comment' not in request.POST: raise Http404("unrecognized submit button") # form = CommentForm(request.POST or None, wysiwyg=True, label="") # form = SubmissionQuickReplyForm(request.POST) form = SubmissionForm(request.POST, request.FILES) if form.is_valid(): comment_text = form.cleaned_data.get('comment_text') if not comment_text: if submission.quest.verification_required and not request.FILES: messages.error( request, "Please read the Submission Instructions more carefully. " "You are expected to attach something or comment to complete this quest!" ) return redirect(origin_path) else: comment_text = "(submitted without comment)" comment_new = Comment.objects.create_comment( user=request.user, path=origin_path, text=comment_text, target=submission, ) if request.FILES: for afile in request.FILES.getlist('attachments'): newdoc = Document(docfile=afile, comment=comment_new) newdoc.save() if 'complete' in request.POST: note_verb = "completed" if submission.quest.verification_required: note_verb += ", awaiting approval." else: note_verb += " and automatically approved." icon = "<i class='fa fa-shield fa-lg'></i>" # Notify teacher if they are specific to quest but are not the student's teacher if submission.quest.specific_teacher_to_notify \ and submission.quest.specific_teacher_to_notify not in request.user.profile.current_teachers(): affected_users = [ submission.quest.specific_teacher_to_notify, ] else: affected_users = None submission.mark_completed() if not submission.quest.verification_required: submission.mark_approved() # Immediate/synchronous recalculation of available quests: update_quest_conditions_for_user.apply( args=[request.user.id]) elif 'comment' in request.POST: note_verb = "commented on" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-comment-o fa-stack-2x text-info'></i>" + \ "</span>" affected_users = [] if request.user.is_staff: affected_users = [ submission.user, ] else: # student comment # student's teachers affected_users.extend( request.user.profile.current_teachers( )) # User.objects.filter(is_staff=True) # add quest's teacher if necessary if submission.quest.specific_teacher_to_notify: affected_users.append( submission.quest.specific_teacher_to_notify) # remove doubles/flatten affected_users = set(affected_users) else: raise Http404("unrecognized submit button") notify.send( request.user, action=comment_new, target=submission, recipient=submission.user, affected_users=affected_users, verb=note_verb, icon=icon, ) messages.success(request, ("Quest " + note_verb)) return redirect("quests:quests") else: context = { "heading": submission.quest.name, "submission": submission, # "comments": comments, "submission_form": form, "anchor": "submission-form-" + str(submission.quest.id), # "reply_comment_form": reply_comment_form, } return render(request, 'quest_manager/submission.html', context) else: raise Http404
def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) notify.send(instance, recipient=instance, verb='was saved')
def notify_followers(board, actor, verb, action_object): """Notify board followers of that have read permissions for the board.""" for follow in board.followers.all().select_related('user'): if follow.user != actor and board.can_read(follow.user): notify.send(actor, recipient=follow.user, actor=actor, verb=verb, action_object=action_object, target=board)
def approve_event(request, username, slug): if request.method == "POST": approve_comment = request.POST['approve_comment'] approve_comment = str(approve_comment) # Native user and profile native_user = User.objects.get(username=username) native_profile = UserProfile.objects.get(user=native_user) post = Post.objects.get(slug=slug) post_url = reverse('post_detail', kwargs={'slug': slug}) # Event's post's author and author's profile author = post.author author_profile = UserProfile.objects.get(user=author) if author_profile.is_subscribed: subject = "Request for conducting event approved." domain = Site.objects.filter() email_context = { 'teacher': native_user, 'post': post, 'domain': domain.first(), 'status': 'accepted', 'remark': approve_comment, } html_message = render_to_string( 'user_profile/mail_template_reply.html', context=email_context) plain_message = strip_tags(html_message) from_email = "noreply@ccwebsite" to = str(author.email) try: mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) except mail.BadHeaderError: messages.info(request, f"Invalid Header found, mail not sent!") # Sending notification to event's post's author. notify.send( native_profile, recipient=author, verb='granted permission for event.', target=post, dp_url=native_profile.avatar.url, prof_url=reverse("User Profile", kwargs={'username': native_user.username}), post_url=post_url, actor_name=native_profile.user.first_name, timestamp_=timesince(timezone.now()), ) tags = post.tags.all() notify_users = [] email_users = [] for tag in tags: subs = tag.subscribed_by.all() for sub in subs: if sub not in notify_users: notify_users.append(sub) sub_profile = UserProfile.objects.get(user=sub) if sub_profile.is_subscribed: if sub not in email_users: email_users.append(sub) # Sending notification to all users who have subscribed to tag in tags. """ This is giving error. Check why! """ # notify.send( # author, # recipient=notify_users, # verb='is hosting an event.', # target=post, # dp_url=author_profile.avatar.url, # prof_url=reverse("User Profile", kwargs={'username': author.username}), # post_url=post_url, # actor_name=author.first_name, # timestamp_=timesince(timezone.now()), # ) # Sending mail to subscribed users subject = 'Event of your interest' # Domain of link domain = Site.objects.filter() email_context = { 'post': post, 'domain': domain.first(), } html_message = render_to_string( 'user_profile/mail_template_event_notification.html', context=email_context) plain_message = strip_tags(html_message) from_email = "noreply@ccwebsite" try: mail.send_mail(subject, plain_message, from_email, email_users, html_message=html_message) except mail.BadHeaderError: messages.info(request, f"Invalid Header found, mail not sent!") post.verify_status = 1 post.draft = False post.save() messages.info(request, f"You have approved an event.") return HttpResponseRedirect(reverse('post_detail', kwargs={'slug': slug}))
def institutionyearprofile(request, id): institutionyearprofile = InstitutionYearProfile.objects.all().get(id=id) signatures = list( Signature.objects.all().filter(recipient=institutionyearprofile)) page_title = str( institutionyearprofile.yearbook_user ) + " " + institutionyearprofile.institution_year.school_year + " " + institutionyearprofile.institution_year.institution.institution_name if request.user.is_authenticated: queryset = Signature.objects.filter(author=request.user.yearbookuser) else: queryset = None signatureupdateforms = [] signaturedeleteforms = [] # If there are forms that the user can update if queryset: # Loop through all signatures to create respective update forms for signature in queryset: instance = signature update_form = SignatureUpdateForm(request.POST or None, instance=instance) delete_form = SignatureDeleteForm(request.POST or None, instance=instance) signatureupdateforms.append((update_form, instance, instance.id)) signaturedeleteforms.append((delete_form, instance, instance.id)) if request.method == "POST": for signatureupdateformtuple in signatureupdateforms: if "update" + str( signatureupdateformtuple[2]) in request.POST: # Select this form and save changes u_form = signatureupdateformtuple[0] if u_form.is_valid(): u_form.save() messages.success( request, 'Signature updated successfully.') return redirect( institutionyearprofile.get_absolute_url()) for signaturedeleteformtuple in signaturedeleteforms: if "delete" + str( signaturedeleteformtuple[2]) in request.POST: d_form = signaturedeleteformtuple[0] if d_form.is_valid(): d_form.instance.delete() messages.success( request, 'Signature deleted successfully.') return redirect( institutionyearprofile.get_absolute_url()) # IYP Update Form instance = get_object_or_404(InstitutionYearProfile, id=id) iypupdateform = IYPUpdateForm(request.POST or None, request.FILES or None, instance=instance) if iypupdateform.is_valid(): iypupdateform.save() messages.success(request, 'Profile updated successfully.') return redirect(instance.get_absolute_url()) # Signature Writing Form if request.method == "POST": signatureform = SignatureForm(request.POST) if signatureform.is_valid( ): # and not signatureupdateformset.is_valid(): # and True not in [form[0].is_valid() for form in signatureupdateforms]: signature = signatureform.save(commit=False) signature.author = request.user.yearbookuser signature.recipient = institutionyearprofile notify.send(request.user, recipient=institutionyearprofile.yearbook_user.user, verb='wrote a new signature', action_object=institutionyearprofile) signature.save() data = { 'data': str(signature.author) + ' wrote you a new signature', 'link': str(institutionyearprofile.get_absolute_url()) } posturl = '/users/' + str(institutionyearprofile.yearbook_user.id) result = firebase.post(posturl, data) return redirect(institutionyearprofile.get_absolute_url()) else: signatureform = SignatureForm() # IYP Delete Form iypdeleteform = IYPDeleteForm(request.POST or None, instance=instance) if iypdeleteform.is_valid(): iypdeleteform.instance.delete() return redirect(request.user.yearbookuser.get_absolute_url()) context = { 'institutionyearprofile': institutionyearprofile, 'signatures': signatures, 'page_title': page_title, 'iypupdateform': iypupdateform, 'signatureform': signatureform, 'signatureupdateforms': signatureupdateforms if queryset is not None else [], 'signaturedeleteforms': signaturedeleteforms if queryset is not None else [], 'iypdeleteform': iypdeleteform } return render(request, 'yearbook/institutionyearprofile.html', context)
def notificar(self, descripcion): notify.send(sender=self, recipient=self.pqs.nombreUsuario, verb='n', description=descripcion)
def submit_comments(request, assignment_id, login, submit_num): submit = get_object_or_404(Submit, assignment_id=assignment_id, student__username=login, submit_num=submit_num) if not is_teacher( request.user) and request.user.username != submit.student.username: raise PermissionDenied() submits = [] for s in Submit.objects.filter( assignment_id=assignment_id, student__username=login).order_by('submit_num'): submits.append({ 'num': s.submit_num, 'submitted': s.created_at, 'points': s.assigned_points, }) def get_comment_type(comment): if comment.author == comment.submit.student: return 'student' return 'teacher' notifications = { c.action_object.id: c for c in Notification.objects.filter( target_object_id=submit.id, target_content_type=ContentType.objects.get_for_model(Submit)) } def dump_comment(comment): notification = notifications.get(comment.id, None) unread = False notification_id = None if notification: unread = notification.unread notification_id = notification.id return { 'id': comment.id, 'author': comment.author.get_full_name(), 'author_id': comment.author.id, 'text': comment.text, 'can_edit': comment.author == request.user, 'type': get_comment_type(comment), 'unread': unread, 'notification_id': notification_id, } if request.method == 'POST': data = json.loads(request.body) comment = Comment() comment.submit = submit comment.author = request.user comment.text = data['text'] comment.source = data.get('source', None) comment.line = data.get('line', None) comment.save() notify.send( sender=request.user, recipient=comment_recipients(submit, request.user), verb='added new', action_object=comment, target=submit, public=False, important=True, ) return JsonResponse({**dump_comment(comment), 'unread': True}) elif request.method == 'PATCH': data = json.loads(request.body) comment = get_object_or_404(Comment, id=data['id']) if comment.author != request.user: raise PermissionDenied() Notification.objects.filter( action_object_object_id=comment.id, action_object_content_type=ContentType.objects.get_for_model( Comment)).delete() if not data['text']: comment.delete() return HttpResponse('{}') else: if comment.text != data['text']: comment.text = data['text'] comment.save() notify.send( sender=request.user, recipient=comment_recipients(submit, request.user), verb='updated', action_object=comment, target=submit, public=False, important=True, ) return JsonResponse(dump_comment(comment)) result = {} for source in submit.all_sources(): mime = mimedetector.from_file(source.phys) if mime and mime.startswith('image/'): SUPPORTED_IMAGES = [ 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml', ] result[source.virt] = { 'type': 'img', 'path': source.virt, 'src': reverse('submit_source', args=[submit.id, source.virt]) + ('?convert=1' if mime not in SUPPORTED_IMAGES else ''), } elif mime and mime.startswith("video/"): name = ('.'.join(source.virt.split('.')[:-1])) if name not in result: result[name] = { 'type': 'video', 'path': name, 'sources': [], } result[name]['sources'].append( reverse('submit_source', args=[submit.id, source.virt])) else: content = '' content_url = None error = None try: if is_file_small(source.phys): with open(source.phys) as f: content = f.read() else: content_url = reverse("submit_source", kwargs=dict(submit_id=submit.id, path=source.virt)) except UnicodeDecodeError: error = "The file contains binary data or is not encoded in UTF-8" except FileNotFoundError: error = "source code not found" result[source.virt] = { 'type': 'source', 'path': source.virt, 'content': content, 'content_url': content_url, 'error': error, 'comments': {}, } # add comments from pipeline resultset = get(submit) for pipe in resultset['results']: for source, comments in pipe.comments.items(): for comment in comments: try: line = min(result[source]['content'].count('\n'), comment['line']) - 1 if not any( filter( lambda c: c['text'] == comment['text'], result[source]['comments'].setdefault( line, []))): result[source]['comments'].setdefault(line, []).append( { 'id': -1, 'author': 'Kelvin', 'text': comment['text'], 'can_edit': False, 'type': 'automated', 'url': comment.get('url', None), }) except KeyError as e: logging.exception(e) summary_comments = [] for comment in Comment.objects.filter(submit_id=submit.id).order_by('id'): try: if not comment.source: summary_comments.append(dump_comment(comment)) else: max_lines = result[comment.source]['content'].count('\n') line = 0 if comment.line > max_lines else comment.line result[comment.source]['comments'].setdefault( comment.line - 1, []).append(dump_comment(comment)) except KeyError as e: logging.exception(e) priorities = { 'video': 0, 'img': 1, 'source': 2, } return JsonResponse({ 'sources': sorted(result.values(), key=lambda f: (priorities[f['type']], f['path'])), 'summary_comments': summary_comments, 'submits': submits, 'current_submit': submit.submit_num, 'deadline': submit.assignment.deadline, })
def comment_create_view(request): if request.method == "POST" and request.user.is_authenticated: parent_id = request.POST.get('parent_id') video_id = request.POST.get("video_id") origin_path = request.POST.get("origin_path") try: video = Video.objects.get(id=video_id) except: video = None print(video) parent_comment = None if parent_id is not None: try: parent_comment = Comment.objects.get(id=parent_id) except: parent_comment = None if parent_comment is not None and parent_comment.video is not None: video = parent_comment.video form = CommentForm(request.POST) if form.is_valid(): comment_text = form.cleaned_data['comment'] if parent_comment is not None: # parent comments exists new_comment = Comment.objects.create_comment( user=request.user, path=parent_comment.get_origin, text=comment_text, video = video, parent=parent_comment ) affected_users = parent_comment.get_affected_users() notify.send( request.user, action=new_comment, target=parent_comment, recipient=parent_comment.user, affected_users = affected_users, verb='replied to') messages.success(request, "Thank you for your response.", extra_tags='safe') return HttpResponseRedirect(parent_comment.get_absolute_url()) else: new_comment = Comment.objects.create_comment( user=request.user, path=origin_path, text=comment_text, video = video ) # option to send to super user or staff users # notify.send( # request.user, # recipient = request.user, # action=new_comment, # target = new_comment.video, # verb='commented on') #notify.send(request.user, recipient=request.user, action='New comment added') messages.success(request, "Thank you for the comment.") return HttpResponseRedirect(new_comment.get_absolute_url()) else: print(origin_path) messages.error(request, "There was an error with your comment.") return HttpResponseRedirect(origin_path) else: raise Http404
def form_valid(self, form): if (self.request.POST['action'] == 'confirm') and (self.request.user.task == CustomUser.USER_TASK_RECEIVE_FUNDING): # Delete relationship _user = CustomUser.objects.get(pk=form.cleaned_data['target']) _peer = Peer.objects.filter(user_from=_user).filter( user_to=self.request.user).delete() # Send Notification notify.send( sender=self.request.user, recipient=_user, verb=verbs.TRANSACTION_APPROVED_VERB, target=self.request.user, description=verbs.TRANSACTION_APPROVED_DESCRIPTION.format( self.request.user) ) # Log Transaction TransactionLog.objects.create( user=_user, amount=_user.level.entry_fee, status=TransactionLog.TRANSACTION_PAID, description=verbs.TRANSACTION_APPROVED_DESCRIPTION.format( self.request.user) ) # update user level _user.level = self.request.user.level _user.task = CustomUser.USER_TASK_RECEIVE_FUNDING _user.can_merge = True _user.save() _peer_count = Peer.objects.filter( user_to=self.request.user ).count() _peer_re_merge_count = Remerge.objects.filter( user=self.request.user ).count() messages.success(self.request, verbs.CONFIRMATION_MESSAGE) if (_peer_count == 0) and (_peer_re_merge_count == 0): # update user Level/task r_user = CustomUser.objects.get(pk=self.request.user.id) next_level = None try: next_level_order = self.request.user.level.order + 1 next_level = Level.objects.get( order=next_level_order) r_user.task = CustomUser.USER_TASK_SEND_FUNDING r_user.can_merge = True r_user.save() # Send Notification notify.send( sender=self.request.user, recipient=self.request.user, verb=verbs.NEW_LEVEL_VERB, target=self.request.user, description=verbs.NEW_TASK ) except Level.DoesNotExist: r_user.level = Level.objects.get( order=1) # Reset to level one r_user.task = CustomUser.USER_TASK_SEND_FUNDING r_user.can_merge = True r_user.save() # Send Notification notify.send( sender=self.request.user, recipient=self.request.user, verb=verbs.NEW_LEVEL_VERB, target=self.request.user, description=verbs.AUTO_SET_LEVEL.format( r_user.level.name) ) elif self.request.POST['action'] == 'purge': _user = CustomUser.objects.get(pk=form.cleaned_data['target']) # Penalize user reduce karma point _user.karma -= 2 if _user.karma <= 0: _user.active = False # TODO: Logout user _user.save() # Delete Relationship _peer = Peer.objects.filter(user_from=_user).filter( user_to=self.request.user).delete() # Re-merge User try: user_to_add = Remerge.objects.get(user=self.request.user) user_to_add.count = user_to_add.count + 1 user_to_add.save() except Remerge.DoesNotExist: Remerge.objects.create( user=self.request.user, level=self.request.user.level, count=1) # send Notification notify.send( sender=self.request.user, recipient=self.request.user, verb=verbs.PENDING_RE_MERGE_VERB, target=self.request.user, description=verbs.PENDING_RE_MERGE.format( _user) ) # Send Notification to defaulting user notify.send( sender=self.request.user, recipient=_user, verb=verbs.PURGE_VERB, target=self.request.user, description=verbs.PURGE.format( self.request.user) ) messages.success(request, verbs.PURGE_MESSAGE) # Log Transaction TransactionLog.objects.create( user=_user, amount=_user.level.entry_fee, status=TransactionLog.TRANSACTION_REJECTED, description=verbs.PENDING_RE_MERGE.format(_user) ) elif self.request.POST['action'] == 'purge_self': _user = CustomUser.objects.get(pk=form.cleaned_data['target']) # Delete Relationship _peer = Peer.objects.filter(user_from=self.request.user).filter( user_to=_user ).delete() # Re-merge User try: user_to_add = Remerge.objects.get(user=_user) user_to_add.count = user_to_add.count + 1 user_to_add.save() except Remerge.DoesNotExist: Remerge.objects.create( user=_user, level=_user.level, count=1) # send Notification notify.send( sender=self.request.user, recipient=_user, verb=verbs.PENDING_RE_MERGE_VERB, target=_user, description=verbs.PENDING_RE_MERGE.format( _user) ) notify.send( sender=self.request.user, recipient=self.request.user, verb=verbs.PURGE_VERB, target=_user, description=verbs.PURGE_SELF.format( _user) ) # Penalize user user = CustomUser.objects.get(pk=self.request.user.pk) user.karma -= 2 if _user.karma <= 0: user.active = False logout(self.request) user.save() elif self.request.POST['action'] == 'paid': _user = CustomUser.objects.get(pk=form.cleaned_data['target']) # send Notification notify.send( sender=self.request.user, recipient=_user, verb=verbs.ATTENTION, target=_user, description=verbs.CONFIRMATION_REQUEST.format( self.request.user) ) messages.success(request, verbs.SENT_MESSAGE) return super().form_valid(form)
def post_comment(request, article_id, parent_comment_id=None): article = get_object_or_404(ArticlePost, id=article_id) # 处理 POST 请求 if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.article = article new_comment.user = request.user # 二级回复 if parent_comment_id: parent_comment = Comment.objects.get(id=parent_comment_id) # 若回复层级超过二级,则转换为二级 new_comment.parent_id = parent_comment.get_root().id # 被回复人 new_comment.reply_to = parent_comment.user new_comment.save() # 给其他用户发送通知 if not parent_comment.user.is_superuser and not parent_comment.user == request.user: notify.send( request.user, recipient=parent_comment.user, verb='回复了你', target=article, action_object=new_comment, ) # JsonResponse返回的是json格式的数据,它将新评论的id传递出去。 return JsonResponse({"code": "200 OK", "new_comment_id": new_comment.id}) new_comment.save() # 给管理员发送通知 if not request.user.is_superuser: notify.send( request.user, recipient=User.objects.filter(is_superuser=1), verb='回复了你', target=article, action_object=new_comment, ) # 锚点 使界面停留在评论处 redirect_url = article.get_absolute_url() + '#comment_elem_' + str(new_comment.id) return redirect(redirect_url) # 返回到一个适当的url中-重新定向到文章详情页面 else: return HttpResponse("表单内容有误,请重新填写。") # 处理 GET 请求 elif request.method == 'GET': comment_form = CommentForm() context = { 'comment_form': comment_form, 'article_id': article_id, 'parent_comment_id': parent_comment_id } return render(request, 'comment/reply.html', context) # 处理其他请求 else: return HttpResponse("仅接受GET/POST请求。")
def approve(request, submission_id): submission = get_object_or_404(QuestSubmission, pk=submission_id) origin_path = submission.get_absolute_url() if request.method == "POST": # currently only the big form has files. Need a more robust way to determine... if request.FILES or request.POST.get("awards"): if request.user.is_staff: form = SubmissionFormStaff(request.POST, request.FILES) else: form = SubmissionForm(request.POST, request.FILES) else: form = SubmissionQuickReplyForm(request.POST) if form.is_valid(): # handle badge assertion comment_text_addition = "" badge = form.cleaned_data.get('award') if badge: badges = [badge] else: badges = form.cleaned_data.get('awards') if badges: for badge in badges: # badge = get_object_or_404(Badge, pk=badge_id) new_assertion = BadgeAssertion.objects.create_assertion( submission.user, badge, request.user) messages.success( request, ("Badge " + str(new_assertion) + " granted to " + str(new_assertion.user))) comment_text_addition += "<p></br><i class='fa fa-certificate text-warning'></i> The <b>" + \ badge.name + "</b> badge was granted for this quest " + \ "<i class='fa fa-certificate text-warning'></i></p>" # handle with quest comments blank_comment_text = "" if 'approve_button' in request.POST: note_verb = "approved" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-check fa-stack-2x text-success'></i>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "</span>" blank_comment_text = config.hs_blank_approval_text submission.mark_approved() elif 'comment_button' in request.POST: note_verb = "commented on" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-comment-o fa-stack-2x text-info'></i>" + \ "</span>" blank_comment_text = "(no comment added)" elif 'return_button' in request.POST: note_verb = "returned" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-ban fa-stack-2x text-danger'></i>" + \ "</span>" blank_comment_text = config.hs_blank_return_text submission.mark_returned() else: raise Http404("unrecognized submit button") comment_text_form = form.cleaned_data.get('comment_text') if not comment_text_form: comment_text = blank_comment_text else: comment_text = comment_text_form comment_new = Comment.objects.create_comment(user=request.user, path=origin_path, text=comment_text + comment_text_addition, target=submission) # handle files if request.FILES: for afile in request.FILES.getlist('attachments'): newdoc = Document(docfile=afile, comment=comment_new) newdoc.save() # don't say "with" in notification if no comment was entered if not comment_text_form: action = None else: action = comment_new affected_users = [ submission.user, ] notify.send( request.user, action=action, target=submission, recipient=submission.user, affected_users=affected_users, verb=note_verb, icon=icon, ) message_string = "<a href='" + origin_path + "'>Submission of " + \ submission.quest.name + "</a> " + note_verb + \ " for <a href='" + submission.user.profile.get_absolute_url() + "'>" + \ submission.user.username + "</a>" messages.success(request, message_string) return redirect("quests:approvals") else: # messages.error(request, "There was an error with your comment. Maybe you need to type something?") # return redirect(origin_path) # rendering here with the context allows validation errors to be displayed context = { "heading": submission.quest.name, "submission": submission, # "comments": comments, "submission_form": form, "anchor": "submission-form-" + str(submission.quest.id), # "reply_comment_form": reply_comment_form, } return render(request, 'quest_manager/submission.html', context) else: raise Http404