def decline_invite(self, secret): """ Changes invite status to declined """ if self.single_use: self.status = "DECLINED" action.send(self.contact, verb='declined invite to', action_object=self.meal)
def save(self, *args, **kwargs): if self.pk is None: target = self.issue.number action.send(self.user, verb='placed a $' + str(self.price) + ' bounty on ', target=self.issue) super(Bounty, self).save(*args, **kwargs)
def join_quit_game(request): #userID = request.user.id response = '' if request.method == 'POST': game_id = request.POST['game_id'] print game_id game = Game.objects.get(id=game_id) if request.user in game.users.all(): game.users.remove(request.user) response = 'left' verb = request.user.first_name+' '+request.user.last_name+' left '+game.name description = '/game/'+str(game.id) notify.send(request.user,recipient=game.creator, verb=verb, description=description) action.send(request.user, verb="leave game", action_object=game) else: game.users.add(request.user) response = 'joined' verb = request.user.first_name+' '+request.user.last_name+' joined '+game.name description = '/game/'+str(game.id) notify.send(request.user,recipient=game.creator, verb=verb, description=description) action.send(request.user, verb="join game", action_object=game) #return HttpResponse(response) return redirect(request.META['HTTP_REFERER'])
def task_action(user, task, verb): """ A general action that contains tasks. Here we form whole send orders of a given action. A django.contrib.auth.models.User, projects.models.Task and verb instance needs to be passed to the function. """ action.send(user, verb=verb, action_object=task, target=task.group.project)
def edit_message(request, pk): message = get_object_or_404(Message, pk=pk) thread = message.thread if not request.user.write_perm(obj=message): return HttpResponse('You may not edit this message.', status=403) if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message.text = form.cleaned_data['content'] message.save() actions.follow(request.user, thread, actor_only=False) action.send(request.user, verb="a édité", action_object=message, target=thread) return HttpResponseRedirect(reverse('thread_show', args=[thread.id]) + "#message-" + str(message.id)) else: form = MessageForm({'content': message.text}) return render(request, 'telepathy/edit_message.html', { 'form': form, 'thread': thread, 'edited_message': message, 'edit': True, })
def create(self, request): if self.check_valid_vote(self.request.user, self.request.POST['comment']): vote = CommentVote(vote=True if self.request.POST.get('vote') == 'up' else False, user=self.request.user, date_voted = timezone.now(), comment=CustomComment.objects.get(pk=self.request.POST['comment'])) vote.save() action.send( request.user, action_object=vote.comment, verb= _(u"voted on"), vote = True if request.POST.get('vote') == 'up' else False ) suff = "up" if vote.vote else "down" notify( request.user, vote.comment.user, action_object=vote, action_target=vote.comment, verb=_(u"voted {} for your comment".format(suff)), key="vote" ) return Response({ 'success': True, 'message': _('Vote saved') }) else: return Response({ 'success': False, 'message': _('Already voted on this comment') })
def user_logged_out(user, **kwargs): """ receive signals when user logout """ logout_actor = Actor.objects.get(user=user) logout_activity = Verb.objects.get(name='logout') action.send(logout_actor, verb=logout_activity, description=logout_activity.description)
def form_valid(self, form, **kwargs): location = form.cleaned_data['location'] username = location.slug create_gallery(username) filepath = os.path.join(settings.MEDIA_ROOT, username) image = Image.open(form.cleaned_data['image']) filename = gallery_item_name() width, height = image.size if width > settings.IMAGE_MAX_SIZE[0] or height > settings.IMAGE_MAX_SIZE[1]: image.thumbnail(settings.IMAGE_MAX_SIZE) image.save(os.path.join(filepath, filename), "JPEG") create_gallery_thumbnail(username, filename) item = LocationGalleryItem( user = self.request.user, picture_name = filename, name = form.cleaned_data['name'], description = form.cleaned_data['description'], location = location ) item.save() action.send( self.request.user, action_object = item, target = item.location, verb = _('uploaded') ) self.request.user.profile.rank_pts += 2 self.request.user.profile.save() return redirect(reverse('locations:gallery', kwargs={'slug':location.slug}))
def form_valid(self, form): user = self.request.user blog_posts = BlogPost.objects.published(for_user=user).select_related().filter(user=user) if blog_posts and blog_posts[0]: blog_post = blog_posts[0] if blog_post.num_images < getattr(settings, 'MAX_IMAGES_PER_VENDOR', 10): blog_post.num_images += 1 blog_post.save() self.object = form.save(commit=False) if self.object.album.images.exists(): self.object.order = self.object.album.images.all().aggregate(Max('order'))['order__max'] + 1 #self.object.album.images.all().count() else: self.object.order = 0 self.object.user = self.request.user self.object.save() if self.object.album: self.object.album.save() if self.object.album.images.all().count() == 1: action.send(blog_post, verb=settings.ALBUM_ADD_VERB, target=self.object.album) else: ctype = ContentType.objects.get_for_model(blog_post) target_content_type = ContentType.objects.get_for_model(self.object.album) Action.objects.all().filter(actor_content_type=ctype, actor_object_id=blog_post.id, verb=settings.ALBUM_ADD_IMAGE_VERB, target_content_type=target_content_type, target_object_id=self.object.album.id ).delete() action.send(blog_post, verb=settings.ALBUM_ADD_IMAGE_VERB, target=self.object.album) return HttpResponseRedirect(self.get_success_url()) else: return json_error_response("'%s' has crossed maximum limit of images" % user)
def comment(request, template="generic/comments.html"): """ Handle a ``ReviewForm`` submission and redirect back to its related object. """ response = initial_validation(request, "comment") if isinstance(response, HttpResponse): return response obj, post_data = response form = ReviewForm(request, obj, request.POST ) if form.is_valid(): url = obj.get_absolute_url() if is_spam(request, form, url): return redirect(url) comment = form.save(request) response = redirect(add_cache_bypass(comment.get_absolute_url())) # Store commenter's details in a cookie for 90 days. for field in ReviewForm.cookie_fields: cookie_name = ReviewForm.cookie_prefix + field cookie_value = post_data.get(field, "") set_cookie(response, cookie_name, cookie_value) """ Send activity feed to those who follow this vendor page. """ if request.user.is_authenticated(): action.send(obj, verb=settings.GOT_REVIEW_VERB, target=comment ) return response elif request.is_ajax() and form.errors: return HttpResponse(dumps({"errors": form.errors})) # Show errors with stand-alone comment form. context = {"obj": obj, "posted_comment_form": form} response = render(request, template, context) return response
def create_game(request): if request.method == 'POST': form = GameForm(request.POST) if form.is_valid(): sport = form.cleaned_data['sport'] name = form.cleaned_data['name'] cap = form.cleaned_data['cap'] description = form.cleaned_data['description'] location_name = form.cleaned_data['location'] location = Location.objects.get(name=location_name) #Need to handle time zones datetimeStart = request.POST['dtp_input1'] sportObj = Sport.objects.get(name=sport.lower()) newGame = Game.objects.create(sport=sportObj,name=name,timeStart=datetimeStart, creator=request.user, location=location, cap=cap, description=description) newGame.dateCreated = datetime.datetime.now() newGame.users.add(request.user) newGame.save() action.send(request.user,verb="game created",action_object=newGame) return redirect('/game/'+str(newGame.id)) else: print 'invalid form' error_msg = 'Could not create your game. Please try again!' return render(request, 'create_game.html', {'gameForm':form, 'error_msg':error_msg}) else: gameForm = GameForm() return render(request, 'create_game.html', {'gameForm':gameForm})
def handle_cm_save(sender, created, instance, **kwargs): cmct = ContentType.objects.get(app_label="committees", model="committeemeeting") mct = ContentType.objects.get(app_label="mks", model="member") for m in instance.mks_attended.all(): if Action.objects.filter(actor_object_id=m.id, actor_content_type=mct, verb='attended', target_object_id=instance.id, target_content_type=cmct).count()==0: action.send(m, verb='attended', target=instance, description='committee meeting', timestamp=instance.date)
def report(request, lot_number): report = Report.objects.get(lot_number=lot_number) audit_log = target_stream(report) orders = OrderLineItem.objects.filter(report=report) newdoc = NewDocumentForm(None) if 'document_button' in request.POST: newdoc = NewDocumentForm(request.POST, request.FILES) if newdoc.is_valid(): doc = Document(type=newdoc.cleaned_data['type'], file=request.FILES['file'], created_by=request.user) doc.save() action.send(request.user, verb="created document", action_object=doc) rd = ReportDocument(report=report, document=doc, primary_document=newdoc.cleaned_data['primary'], created_by=request.user, internal_cert=newdoc.cleaned_data['internal']) rd.save() action.send(request.user, verb="attached document", action_object=rd, target=report) report.save() messages.success(request, 'Document upload successful.') return HttpResponseRedirect(reverse('reports.views.report', args=[report.lot_number])) return render_to_response('reports/report.html', { 'report': report, 'new_document_form': newdoc, 'orders': orders, 'audit_log': audit_log, }, context_instance=RequestContext(request))
def issue_beercoin(request): owner = get_object_or_404(User, username=request.GET.get("owner")) comment = request.GET.get("comment", None) what_for = request.GET.get("what_for", None) issuer = request.user if issuer.username == owner.username: raise BeerCoinTransactionError("You can't owe beers yourself") if issuer.profile.balance <= -10: raise BeerCoinTransactionError("You already owe a lot. Not acceptable.") # fixme: make better owner.profile.balance += 1 issuer.profile.balance -= 1 owner.profile.save() issuer.profile.save() action.send(issuer, verb="issued", action_object=owner, comment=comment, what_for=what_for) if owner.profile.balance == -10: action.send(issuer, verb="reached limit") return {"success": True}
def project_create_edit(request, project_slug=None): user = request.user site = Site.objects.get(id=current_site_id) if project_slug: project = get_object_or_404(Project, slug=project_slug) else: project = Project(user=user, site=site) if not project.is_editable(request): return HttpResponseForbidden('You are not the owner of this project.') project_form = ProjectForm( request.POST or None, request.FILES or None, instance=project ) if project_form.is_valid(): project_form.save() if project.is_published(): action.send(user, verb='updated', target=project) if 'save-add-step' in request.POST: redirect_args = ('project-step-create-edit', project.slug) else: redirect_args = (project,) return redirect(*redirect_args) return render(request, 'project/project_create_edit.html', { 'project': project, 'project_form': project_form, })
def dashboard_import(request): if request.user.is_authenticated(): if request.method == 'POST': import_project_form = ImportProjectForm(request.POST, request=request) if import_project_form.is_valid(): project_cleaned = import_project_form.cleaned_data user = HubUser.objects.get(user__username__iexact=request.user.username) github_request = urllib2.urlopen('https://api.github.com/repos/%s/%s' % (user.github, project_cleaned['name'])) json_data = json.loads(github_request.read()) new_project = Project.objects.create(name=project_cleaned['name'], status=project_cleaned['status'], descript=json_data['description'], language=json_data['language'], version='1.0', created_on=json_data['created_at'], url=json_data['url'], ) user = HubUser.objects.get(user__username__iexact=request.user.username) new_project.owners.add(user) new_project.save() Forum(project=new_project).save() action.send(request.user, verb="Added a project.") return HttpResponseRedirect("/dashboard") else: return render(request, 'dashboard_import.html', {'import_project_form': import_project_form}) else: import_project_form = ImportProjectForm(request=request) return render(request, 'dashboard_import.html', {'import_project_form': import_project_form}) else: return HttpResponseRedirect("/login")
def toggleproperty_post_save(sender, instance, created, **kwargs): if created: if instance.property_type in ("like", "bookmark"): if instance.property_type == "like": verb = "likes" elif instance.property_type == "bookmark": verb = "bookmarked" if instance.content_type == ContentType.objects.get_for_model(Image): image = instance.content_type.get_object_for_this_type(id = instance.object_id) if image.is_wip: return act.send(instance.user, verb = verb, target = instance.content_object) if instance.content_type == ContentType.objects.get_for_model(Image): push_notification( [instance.content_object.user], 'new_' + instance.property_type, { 'url': settings.ASTROBIN_BASE_URL + instance.content_object.get_absolute_url(), 'user': instance.user.userprofile, }) elif instance.property_type == "follow": user_ct = ContentType.objects.get_for_model(User) if instance.content_type == user_ct: followed_user = user_ct.get_object_for_this_type(pk = instance.object_id) push_notification([followed_user], 'new_follower', {'object': instance.user.userprofile, 'object_url': instance.user.get_absolute_url()})
def vote(request): """ Make vote (up/down) on idea. """ if request.method == 'POST': idea = Idea.objects.get(pk=request.POST['idea']) votes_check = Vote.objects.filter(user=request.user).filter(idea=idea) if len(votes_check) > 0: response = { 'success': False, 'message': _('You voted already on this idea'), 'votes': idea.get_votes(), } else: user_vote = Vote( user = request.user, idea = idea, vote = True if request.POST.get('vote') == 'up' else False ) user_vote.save() response = { 'success': True, 'message': _('Vote saved'), 'votes': idea.get_votes(), } action.send( request.user, action_object=user_vote, target=user_vote.idea, verb= _('voted on'), vote = True if request.POST.get('vote') == 'up' else False ) request.user.profile.rank_pts += 1 request.user.profile.save() return HttpResponse(json.dumps(response), content_type="application/json")
def RegisterUser(request): if request.method == 'POST': mainuser_form = MainUserForm(request.POST) hubuser_form = HubUserForm(request.POST) if mainuser_form.is_valid() and hubuser_form.is_valid(): user_cd = mainuser_form.cleaned_data new_user = User.objects.create_user(username=user_cd['username'], password=user_cd['password'], first_name=user_cd['first_name'], last_name=user_cd['last_name']) new_hubuser = hubuser_form.save(commit=False) new_hubuser.user = new_user new_hubuser.save() user = authenticate(username=user_cd['username'], password=user_cd['password']) if user is not None: if user.is_active: login(request, user) action.send(request.user, verb="Joined Coderzhub.") return HttpResponseRedirect("/dashboard") else: mainuser_form = MainUserForm() hubuser_form = HubUserForm() return render(request, 'register.html', {'mainuser_form': mainuser_form, 'hubuser_form': hubuser_form})
def _handle_bill_update(self, cm, request): bill_id = request.POST.get('bill_id') if not bill_id: raise Http404() if bill_id.isdigit(): bill = get_object_or_404(Bill, pk=bill_id) else: # not a number, maybe its p/1234 m = re.findall('\d+', bill_id) if len(m) != 1: raise ValueError( "didn't find exactly 1 number in bill_id=%s" % bill_id) pp = PrivateProposal.objects.get(proposal_id=m[0]) bill = pp.bill if bill.stage in ['1', '2', '-2', '3']: # this bill is in early stage, so cm must be one of the first meetings bill.first_committee_meetings.add(cm) else: # this bill is in later stages v = bill.first_vote # look for first vote if v and v.time.date() < cm.date: # and check if the cm is after it, bill.second_committee_meetings.add( cm) # if so, this is a second committee meeting else: # otherwise, assume its first cms. bill.first_committee_meetings.add(cm) bill.update_stage() action.send(request.user, verb='added-bill-to-cm', description=cm, target=bill, timestamp=datetime.datetime.now())
def series_new(request): """ A logged in user can create a series. Series serve as a linking mechanism to connect related stories and to share assets between them. Series allow users to create planning notes at a series level have planning discussions and upload assets. Assets are always associated with a series so they are easily accessible to stories and all facets. This means that even single stories technically have a series, but in that case the user does not interact with any series interface. """ seriesform = SeriesForm(request=request) if request.method == "POST": seriesform = SeriesForm(request.POST, request=request) if seriesform.is_valid(): series = seriesform.save(commit=False) series.owner = request.user series.organization = request.user.organization series.creation_date = timezone.now() discussion = Discussion.objects.create_discussion("SER") series.discussion = discussion series.save() seriesform.save_m2m() # record action for activity stream action.send(request.user, verb="created", action_object=series) return redirect('series_detail', pk=series.pk) else: seriesform = SeriesForm(request=request) return render(request, 'editorial/seriesnew.html', {'seriesform': seriesform})
def post(self, request, **kwargs): object_id = kwargs['pk'] if not object_id: return HttpResponseBadRequest() vote = None bill = get_object_or_404(Bill, pk=object_id) user_input_type = request.POST.get('user_input_type') if user_input_type == 'approval vote': vote = Vote.objects.get(pk=request.POST.get('vote_id')) bill.approval_vote = vote bill.update_stage() if user_input_type == 'first vote': vote = Vote.objects.get(pk=request.POST.get('vote_id')) bill.first_vote = vote bill.update_stage() if user_input_type == 'pre vote': vote = Vote.objects.get(pk=request.POST.get('vote_id')) bill.pre_votes.add(vote) bill.update_stage() action.send(request.user, verb='added-vote-to-bill', description=vote, target=bill, timestamp=datetime.datetime.now()) return HttpResponseRedirect(".")
def create_action(self, record): try: action.send(record.added_by, verb='recorded', action_object=record, target=record.garden, timestamp=record.added) except AttributeError: # Record is missing some attributes. Skip it. pass
def post(self, request, pk): """ Send message to selected users. """ users = request.POST.getlist('user[]') if users: for u in users: user = User.objects.get(pk=u) translation.activate(user.profile.lang) # Send email email = mails.InviteUsersMail() email.send(user.email, { 'inviting_user': request.user, 'location': self.get_object(pk), }) # Record action for actstream action.send( request.user, action_object = self.get_object(pk), target = user, verb = _("invited you to follow") ) ctx = { 'success': True, 'message': _("Successfully send invitation"), 'level' : 'success', } else: ctx = { 'success': False, 'message': _("User field cannot be empty"), 'level' : 'danger', } return HttpResponse(json.dumps(ctx))
def handle_annotation_save(sender, created, instance, **kwargs): if created: action.send(instance.content_object.meeting, verb='annotation-added', target=instance, description=unicode(instance.flag_value)) action.send(instance.user, verb='annotated', target=instance, description=unicode(instance.flag_value)) follow(instance.user, instance.content_object.meeting)
def on_comment_posted(sender, comment, request, **kwargs): """ rs = redis.StrictRedis() opt = dict(size=(70, 70), crop=True, bw=True, quality=80) try: image = get_thumbnailer(request.user.profile_set.all()[0].image).get_thumbnail(opt).url except: image = None message = { 'user': request.user.username, 'image': image, 'comment': comment.comment, 'comment_html': re.sub('<[^<]+?>', '', comment.comment).replace('\n','<br>\n'), 'route': comment.content_object.get_api_url(), 'type': 'message' #'timestamp': comment.submit_date } rs.publish('push_chat', json.dumps(message)) """ from actstream import action action.send(request.user, verb='commented on', target=comment.content_object) from pushy.util import pushy_custom body = { 'comment': comment.comment, 'user': request.user.username } pushy_custom(comment.content_object.uuid, body=body, type='update') """ Send email notification of a new comment to site staff when email notifications have been requested. """ # This code is copied from django.contrib.comments.moderation. # That code doesn't offer a RequestContext, which makes it really # hard to generate proper URL's with FQDN in the email # # Instead of implementing this feature in the moderator class, the signal is used instead # so the notification feature works regardless of a manual moderator.register() call in the project. if not appsettings.FLUENT_COMMENTS_USE_EMAIL_NOTIFICATION: return return recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] site = get_current_site(request) content_object = comment.content_object subject = '[{0}] New comment posted on "{1}"'.format(site.name, content_object) context = { 'site': site, 'comment': comment, 'content_object': content_object } message = render(request, "comments/comment_notification_email.txt", context) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
def project_step_create_edit(request, project_slug, project_step_number=None): user = request.user project = get_object_or_404(Project, slug=project_slug) if not project.is_editable(request): return HttpResponseForbidden('You are not the owner of this project.') if 'add' in request.path and project.steps.count() >= 20: messages.add_message(request, messages.WARNING, 'This project already contains 20 steps.') return redirect('project-detail', project.slug) if project_step_number is not None: project_step = get_object_or_404( ProjectStep, project=project, _order=project_step_number ) else: project_step = ProjectStep(project=project) project_step_form = ProjectStepForm( request.POST or None, instance=project_step ) if project_step_form.is_valid(): project_step_form.save() if project.is_published(): action.send(user, verb='updated', action_object=project_step, target=project) # User clicked "save and add another" if 'save-add' in request.POST: redirect_args = ('project-step-create-edit', project.slug) # User clicked "save" (catch anything else) else: redirect_args = (project,) return redirect(*redirect_args) return render(request, 'project/project_step_create_edit.html', { 'project': project, 'project_step': project_step, 'project_step_form': project_step_form, })
def POST(self, object_id, **kwargs): vote = None bill = get_object_or_404(Bill, pk=object_id) user_input_type = self.request.POST.get("user_input_type") if user_input_type == "approval vote": vote = Vote.objects.get(pk=self.request.POST.get("vote_id")) bill.approval_vote = vote bill.update_stage() if user_input_type == "first vote": vote = Vote.objects.get(pk=self.request.POST.get("vote_id")) bill.first_vote = vote bill.update_stage() if user_input_type == "pre vote": vote = Vote.objects.get(pk=self.request.POST.get("vote_id")) bill.pre_votes.add(vote) bill.update_stage() action.send( self.request.user, verb="added-vote-to-bill", description=vote, target=bill, timestamp=datetime.datetime.now(), ) return HttpResponseRedirect(".")
def accept_invite(self, secret, user): """ Checks a secret and allows an invitee to become a guest if it is valid and they are logged in somehow. """ if self.check_secret(secret): # Secret matches if self.status == "INVITED" or not self.single_use: # If the code is not used or can be used multiple times then continue. # If the user has an email or a facebook we should try and match it to a profile perhaps. if user: # We have a user print user if self.meal.add_guest(user, self, self.plusones): # We have allocated the space at the table # Set status to accepted self.status = "ACCEPTED" self.save() action.send(self.invitee, verb='accepted invite to', action_object=self.meal) # We should save any other info we have about the user to the user profile for display else: # There is not space at the table, we could try with less plusones in future pass else: # No user (not even a lazy one!) pass else: # The secret doesn't match print("Bad secret") print self.secret print secret pass
def comment_action_hook(sender, instance, created, **kwargs): """ Action hook for comments - inform other people about the fact that this comment was created and increase the amount of user points accordingly. """ if not created: return True prof = UserProfile.objects.get(user=instance.user) prof.rank_pts += 3 prof.save() # Send action for user and location activity streams action.send( instance.user, action_object = instance, target = instance.content_object, verb = _(u"commented"), comment = instance.comment, comment_url = instance.content_object.get_absolute_url() ) # Send notification to parent comment author (if this is answer for comment) if instance.parent is not None: notify( instance.user, instance.parent.user, key="customcomment", verb=_(u"answered your comment"), action_object=instance, action_target=instance.parent )
def form_valid(self, form): workflow = self.object if workflow.closed: messages.error(self.request, u"You can't add tasks to a closed workflow.") return redirect(self.get_success_url()) workflow.updated_by_user = self.request.user workflow.tasks.add(*(form.cleaned_data['tasks'])) for task in form.cleaned_data['tasks']: action.send(workflow.updated_by_user, verb='added', action_object=task, target=workflow, place_code=workflow.place.place_code) messages.success( self.request, u"Added %d tasks to this workflow." % len(form.cleaned_data['tasks'])) return redirect(self.get_success_url())
def lireArticle(request, slug): article = get_object_or_404(Article, slug=slug) if not article.estPublic and not request.user.is_permacat: return render( request, 'notPermacat.html', ) commentaires = Commentaire.objects.filter( article=article).order_by("date_creation") form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.article = article comment.auteur_comm = request.user article.date_dernierMessage = comment.date_creation article.dernierMessage = ("(" + str(comment.auteur_comm) + ") " + str(comment.commentaire))[:96] + "..." article.save() comment.save() url = article.get_absolute_url() suffix = "_permacat" if article.estPublic else "" action.send(request.user, verb='article_message' + suffix, action_object=article, url=url, description="a réagi à l'article: '%s'" % article.titre) return redirect(request.path) return render( request, 'blog/lireArticle.html', { 'article': article, 'form': form, 'commentaires': commentaires }, )
def reference_add(request, pk, slug, reference_pk, edit=False): project = get_object_or_404(Project, pk=pk, slug=slug) reference = get_object_or_404(Reference, pk=reference_pk) with transaction.atomic(): project_reference, created = ProjectReference.objects.get_or_create( reference=reference, project=project, defaults={'owner': request.user} ) if created: action.send(request.user, verb='added', action_object=project_reference, target=project) messages.success( request, 'Reference added successfully! If you are finished adding references, ' 'you can return to the <a href="{}">bibliography list</a>.'.format(project.get_bibliography_url())) else: messages.info(request, "The reference you selected was already added to this project by {}.".format( project_reference.owner.get_full_name())) if request.is_ajax(): context = { 'messages': render_to_string('bootstrap3/messages.html', {}, request=request), } return JsonResponse(context) return redirect(project.get_bibliography_url())
def post_save_work(sender, instance, **kwargs): """ Cascade changes to linked documents """ if not kwargs['raw'] and not kwargs['created']: # cascade updates to ensure documents # pick up changes to inherited attributes for doc in instance.document_set.all(): # forces call to doc.copy_attributes() doc.updated_by_user = instance.updated_by_user doc.save() # Send action to activity stream, as 'created' if a new work if kwargs['created']: action.send(instance.created_by_user, verb='created', action_object=instance, place_code=instance.place.place_code) else: action.send(instance.updated_by_user, verb='updated', action_object=instance, place_code=instance.place.place_code)
def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) comment_flag_ct = ContentType.objects.get_for_model(CommentFlag) comment_flag_permissions = Permission.objects.filter( content_type=comment_flag_ct) action.send(instance, verb='joined framebuzz') try: # Start following framebuzz, and framebuzz follows you. fbz_user = User.objects.get(username__iexact='framebuzz') follow(fbz_user, instance) follow(instance, fbz_user) except User.DoesNotExist: # No framebuzz user, probably on a dev machine. pass for perm in comment_flag_permissions: profile.user.user_permissions.add(perm.id) return
def create_list(account: Account, user_input: Dict) -> Dict[str, Any]: expected_keys = [ 'id', 'name', 'enable_scans', 'scan_type', 'automated_scan_frequency', 'scheduled_next_scan' ] if sorted(user_input.keys()) != sorted(expected_keys): return operation_response(error=True, message="Missing settings.") frequency = validate_list_automated_scan_frequency( user_input['automated_scan_frequency']) data = { 'account': account, 'name': validate_list_name(user_input['name']), 'enable_scans': bool(user_input['enable_scans']), 'scan_type': validate_list_scan_type(user_input['scan_type']), 'automated_scan_frequency': frequency, 'scheduled_next_scan': UrlList.determine_next_scan_moment(frequency), } urllist = UrlList(**data) urllist.save() # make sure the account is serializable. data['account'] = account.id # adding the ID makes it possible to add new urls to a new list. data['id'] = urllist.pk # empty list, no warnings. data['list_warnings'] = [] # give a hint if it can be scanned: data['scan_now_available'] = urllist.is_scan_now_available() # Sprinkling an activity stream action. action.send(account, verb='created list', target=urllist, public=False) return operation_response(success=True, message="List created.", data=data)
def taskGroupCreate(request: HttpRequest, projectid): if not request.user.is_authenticated: return redirect('projectMgr:homepage') ''' :param request: :return: ''' print(request.method) print(request.POST) thisProject = models.Project.objects.get(id=projectid) if request.method == "POST": form = forms.createTaskgroup(request.POST) if form.is_valid(): name = form.cleaned_data['name'] description = form.cleaned_data['description'] newTaskGroup = models.TaskGroup.objects.create(name=name, description=description, creator=request.user,created=datetime.now) newTaskGroup.people.add(request.user) newTaskGroup.save() thisProject = models.Project.objects.get(id=projectid) thisProject.taskgroup_set.add(newTaskGroup) thisProject.save() # create taskgroup activitiy action.send(request.user, verb="added taskgroup", action_object=newTaskGroup, target=thisProject) # print('projectid',projectid,'taskgroupid',newTask.id) if "Choose team" in request.POST: return redirect('projectMgr:chooseTaskGroupMates', projectid=projectid, taskGroupId=newTaskGroup.id) else: return redirect('projectMgr:taskGroupDetail', projectid=projectid, taskGroupId=newTaskGroup.id) else: form = forms.createTaskgroup() return render(request, "projectMgr/createTaskGroup.html", {'form': form, 'project': thisProject, "thisUser": request.user})
def send_comment_notification(sender, instance, created, **kwargs): if created: action.send(instance.author, verb='commented', action_object=instance, target=instance.video) if instance.author != instance.video.channel: Notification.objects.create( notification_type=Notification.NotificationType.COMMENT, actor=instance.author, action_object=instance, target_object=instance.video, recipient=instance.video.channel.user) tags = re.findall('@\(\w+\)\[([aA-zZ0-9-_]+)\]', instance.text) if tags: for channel in Channel.objects.filter(channel_id__in=tags): if instance.author != channel: Notification.objects.create( notification_type=Notification.NotificationType.TAG, actor=instance.author, action_object=instance, target_object=instance.video, recipient=channel.user)
def get(self, request, *args, **kwargs): jardin = get_object_or_404(Jardin, pk=self.kwargs.get('jardin_id')) cultivateur = get_object_or_404(Cultivateur, pk=self.kwargs.get('cultivateur_id')) if cultivateur.jardin != jardin: return HttpResponseForbidden() if cultivateur.adherant.user != request.user: return HttpResponseForbidden() if cultivateur.pending or not cultivateur.accepte: return HttpResponseForbidden() cultivateur.accepte = False cultivateur.save() action.send(request.user, verb='quit', action_object=cultivateur) unfollow(cultivateur.adherant.user, jardin) CultivateurQuitMessageView(cultivateur, request).send() return redirect('s5appadherant:jardin_detail', jardin_id=jardin.id)
def do_like(self, user_from, timestamp=None): self.can_vote(user_from) self.clear_previous_votes(user_from) data = { 'verb': settings.FORUM_ACTION_UP_VOTE, 'action_object': self, } if timestamp: data['timestamp'] = timestamp action.send(user_from, **data) if self.is_post: new_action_post.send( sender=self.__class__, instance=self, action=settings.FORUM_ACTION_UP_VOTE, ) else: new_action_answer.send( sender=self.__class__, instance=self, action=settings.FORUM_ACTION_UP_VOTE, )
def get_report(account: Account, report_id: int): report = UrlListReport.objects.all().filter( urllist__account=account, urllist__is_deleted=False, pk=report_id ).values('id', 'urllist_id', 'calculation', 'average_internet_nl_score', 'total_urls', 'at_when', 'report_type', 'urllist__name', 'is_publicly_shared', 'public_report_code', 'public_share_code' ).first() # todo: add report metadata... if not report: return [] # Sprinkling an activity stream action. log_report = UrlListReport.objects.all().filter( urllist__account=account, urllist__is_deleted=False, pk=report_id ).only('id').first() action.send(account, verb='viewed report', target=log_report, public=False) return f"{dump_report_to_text_resembling_json(report)}"
def handle(self, sender, signal, **kwargs): # only add things to the activity stream if there's a user if kwargs.get("user", None) is None: return target = self.getTargetObj(**kwargs) # invalidate cache for target followers users = followers(target) for user in users: update_activity_stream_for_user.delay(user.username) update_activity_stream_for_user.delay(kwargs['user'].username, actor=True) if signal == signals.create: action.send(kwargs['user'], verb=self.createVerb, action_object=kwargs['instance'], target=target) if signal == signals.modify: action.send(kwargs['user'], verb=self.modifyVerb, action_object=kwargs['instance'], target=target)
def on_failure(self, exc, task_id, args, kwargs, einfo): if isinstance(exc, SkipException): return None doc_id = args[0] print("Document {} failed.".format(doc_id)) document = Document.objects.get(id=doc_id) document.state = "ERROR" document.save() action.send(document.user, verb="upload failed", action_object=document, target=document.course, public=False) # Warn the admins DocumentError.objects.create( document=document, task_id=task_id, exception=exc, traceback=einfo.traceback, )
def record_bill_proposal(**kwargs): if kwargs['action'] != "post_add": return private_proposal_ct = ContentType.objects.get(app_label="laws", model="privateproposal") member_ct = ContentType.objects.get(app_label="mks", model="member") proposal = kwargs['instance'] if str(kwargs['sender']).find('proposers') >= 0: verb = 'proposed' else: verb = 'joined' for mk_id in kwargs['pk_set']: if Action.objects.filter( actor_object_id=mk_id, actor_content_type=member_ct, verb=verb, target_object_id=proposal.id, target_content_type=private_proposal_ct).count() == 0: mk = Member.objects.get(pk=mk_id) action.send(mk, verb=verb, target=proposal, timestamp=proposal.date)
def update_node_property(user, action_object, property_key, value_before, value_after): """ Creates an Action with the extra information needed to present the user with a history. :param user: Django user instance :param action_object: NodeHandle instance :param property_key: String :param value_before: JSON supported value :param value_after: JSON supported value :return: None """ action_object.modifier = user action_object.save() action.send( user, verb='update', action_object=action_object, noclook={ 'action_type': 'node_property', 'property': property_key, 'value_before': value_before, 'value_after': value_after } )
def delete_relationship(user, relationship): """ :param user: Django user instance :param relationship: norduniclient relationship model :return: None """ start_nh = NodeHandle.objects.get(pk=relationship.start['handle_id']) start_nh.modifier = user start_nh.save() end_nh = NodeHandle.objects.get(pk=relationship.end['handle_id']) end_nh.modifier = user end_nh.save() action.send( user, verb='delete', action_object=start_nh, target=end_nh, noclook={ 'action_type': 'relationship', 'relationship_type': relationship.type, 'object_name': u'{}'.format(relationship.data) } )
def _handle_add_mk(self, cm, request): mk_id = request.POST.get('mk_id') mk_name = request.POST.get('mk_name') if not mk_id and mk_name: mk_names = Member.objects.values_list('name', flat=True) possible_matches = difflib.get_close_matches(mk_name, mk_names) if possible_matches: mk_name = possible_matches[0] mk = Member.objects.get(name=mk_name) else: raise Http404() elif mk_id: mk = Member.objects.get(id=mk_id) else: raise Http404() cm.mks_attended.add(mk) cm.save() # just to signal, so the attended Action gets created. action.send(request.user, verb='added-mk-to-cm', description=cm, target=mk, timestamp=datetime.datetime.now())
def save(self, *args, **kwargs): """Extend save() with reel thumbnail fetching. If reel is set, fetch thumbnail_url via micawber and set it as reel_thumbnail. """ super().save(*args, **kwargs) if self.reel == '': log.debug('Skipping thumbnail fetch for reel of profile %i' % self.user_id) return if self.data_changed(['reel']): log.debug('Updating reel thumbnail for user %i' % self.user_id) dillo.tasks.profile.update_profile_reel_thumbnail(self.user_id) # Create activity for reel update action.send(self.user, verb='updated their reel', action_object=self) if self.data_changed(['name']): log.debug('Updating newsletter information for user') dillo.tasks.profile.update_mailing_list_subscription( self.user.email)
def video_signup(request, slug): if not request.method == 'POST': raise Exception('This view is meant to be called via a POST request.') video, created = get_or_create_video(slug) login_success = False outbound_message = dict() outbound_message[DATA_KEY] = {} form = SignupForm(data=json.loads(request.raw_post_data)) if form.is_valid(): user = form.save(request) perform_login(request, user) login_success = True action.send(user, verb='registered account', action_object=video) action.send(user, verb='viewed video', action_object=video) userSerializer = UserSerializer(user) userSerialized = JSONRenderer().render(userSerializer.data) outbound_message[DATA_KEY]['user'] = json.loads(userSerialized) outbound_message[DATA_KEY]['share_url'] = reverse('profiles-share', args=[ user.username, slug, ]) else: outbound_message[DATA_KEY]['errors'] = \ json.loads(errors_to_json(form.errors)) outbound_message[EVENT_TYPE_KEY] = 'FB_SIGNUP' outbound_message[CHANNEL_KEY] = \ '/framebuzz/session/%s' % request.session.session_key outbound_message[DATA_KEY]['login_success'] = login_success return HttpResponse(json.dumps(outbound_message), content_type="application/json")
def post(self, request, **kwargs): cm = get_object_or_404(CommitteeMeeting, pk=kwargs['pk']) bill = None request = self.request user_input_type = request.POST.get('user_input_type') if user_input_type == 'bill': bill_id = request.POST.get('bill_id') if bill_id.isdigit(): bill = get_object_or_404(Bill, pk=bill_id) else: # not a number, maybe its p/1234 m = re.findall('\d+',bill_id) if len(m)!=1: raise ValueError("didn't find exactly 1 number in bill_id=%s" % bill_id) pp = PrivateProposal.objects.get(proposal_id=m[0]) bill = pp.bill if bill.stage in ['1','2','-2','3']: # this bill is in early stage, so cm must be one of the first meetings bill.first_committee_meetings.add(cm) else: # this bill is in later stages v = bill.first_vote # look for first vote if v and v.time.date() < cm.date: # and check if the cm is after it, bill.second_committee_meetings.add(cm) # if so, this is a second committee meeting else: # otherwise, assume its first cms. bill.first_committee_meetings.add(cm) bill.update_stage() action.send(request.user, verb='added-bill-to-cm', description=cm, target=bill, timestamp=datetime.datetime.now()) if user_input_type == 'mk': mk_names = Member.objects.values_list('name', flat=True) mk_name = difflib.get_close_matches(request.POST.get('mk_name'), mk_names)[0] mk = Member.objects.get(name=mk_name) cm.mks_attended.add(mk) cm.save() # just to signal, so the attended Action gets created. action.send(request.user, verb='added-mk-to-cm', description=cm, target=mk, timestamp=datetime.datetime.now()) if user_input_type == 'remove-mk': mk_names = Member.objects.values_list('name', flat=True) mk_name = difflib.get_close_matches(request.POST.get('mk_name'), mk_names)[0] mk = Member.objects.get(name=mk_name) cm.mks_attended.remove(mk) cm.save() # just to signal, so the attended Action gets created. action.send(request.user, verb='removed-mk-to-cm', description=cm, target=mk, timestamp=datetime.datetime.now()) return HttpResponseRedirect(".")
def BadgeWearAddView(request, pk=0): if pk == 0: return HttpResponseRedirect(reverse('badges_home_view')) form = BadgeWearForm() badge = get_object_or_404(Badge, pk=pk) badgeWear = request.user.badgewear_set.filter(badge=badge) if not badgeWear or badgeWear[0].level != "MAI": return HttpResponseForbidden("Vous n'avez pas \ les droits pour effectuer cette action") if request.method == "POST": form = BadgeWearForm(request.POST) if form.is_valid(): badgeWear = BadgeWear(user=form.cleaned_data['user']) badgeWear.badge = badge badgeWear.level = form.cleaned_data['level'] badgeWear.action_counter = 0 badgeWear.timestamp = timezone.now() badgeWear.attributor = request.user badgeWear.save() if not badge.hidden: djaction.send(form.cleaned_data['user'], verb='a recu le badge', action_object=badge) return HttpResponseRedirect( reverse('badge_view', kwargs={"pk": pk})) else: return render(request, 'add_badgewear.html', { 'form': form, 'badge': badge })
def new_group_post(request): image_url = '' viewer = request.user owner_user = request.user owner_user_role = UserProfile.objects.get(user_id=owner_user.id) if request.method == 'POST': eform = freeCrop(request.POST) # A form bound to the POST data if eform.is_valid(): # All validation rules pass new_event = eform.save() #return HttpResponseRedirect('/user/profile/'+request.user.username) #return HttpResponseRedirect('/file-upload/cicu-freecrop/?id='+str(new_event.id)) a = new_event.id if uploadedImage.objects.get(id=a).image: image_url = "###uploaded_image###" + uploadedImage.objects.get( id=a).image.url + "##!uploaded_image!##" form = Group_Post_Form(request.POST) if form.is_valid(): ######## form values ########### content = form.cleaned_data['content'] + image_url actor_name = form.cleaned_data['actor_name'] group_id = form.cleaned_data['group_id'] ##################### owner_user_role = UserProfile.objects.get(user_id=owner_user.id) org = Organization.objects.get(id=group_id) content = rendered_content(content, request) action.send(viewer, verb='posted', action_object=org, target=org, post_content=content) # action creation else: print "ERROR IN VALIDATION" print form.errors else: form = Group_Post_Form() return HttpResponseRedirect('/groups/' + group_id)
def promote_user(request, action="", username="", pk=""): user = get_object_or_404(User, username=username) badge = get_object_or_404(Badge, pk=int(pk)) badge_wear = get_object_or_404(BadgeWear, badge=badge, user=user) if get_object_or_404(BadgeWear, badge=badge, user=request.user).level != "MAI": return HttpResponseForbidden("Vous n'avez pas les droits requis pour \ effectuer cette action") if action == "up": if badge_wear.level == "DIS": badge_wear.level = "MAI" elif badge_wear.level == "INI": badge_wear.level = "DIS" elif badge_wear.level == "RAC": badge_wear.level = "INI" if not badge.hidden: djaction.send(user, verb='a été promu "{}" pour le badge'.format( badge_wear.get_level_display()), action_object=badge) elif action == "down": if badge_wear.level == "INI": badge_wear.level = "RAC" elif badge_wear.level == "DIS": badge_wear.level = "INI" elif badge_wear.level == "MAI": badge_wear.level = "DIS" else: return HttpResponseForbidden( "L'action que vous tentez d'effectuer n'existe pas") badge_wear.timestamp = timezone.now() badge_wear.save() return HttpResponseRedirect(reverse("badge_view", args=[pk]))
def save(self, *args, **kwargs): #add issue status to activity feed if self.status == Issue.IN_REVIEW_STATUS: action.send(self.user, verb="is in review now", target=self.number) elif self.status == Issue.OPEN_STATUS: action.send(self.user, verb="is open now", target=self.number) else: action.send(self.user, verb="is closed", target=self.number) super(Issue, self).save(*args, **kwargs)
def project_step_create_edit(request, project_slug, project_step_number=None): user = request.user project = get_object_or_404(Project, slug=project_slug) if not project.is_editable(request): return HttpResponseForbidden('You are not the owner of this project.') if 'add' in request.path and project.steps.count() >= 20: messages.add_message(request, messages.WARNING, 'This project already contains 20 steps.') return redirect('project-detail', project.slug) if project_step_number is not None: project_step = get_object_or_404(ProjectStep, project=project, _order=project_step_number) else: project_step = ProjectStep(project=project) project_step_form = ProjectStepForm(request.POST or None, instance=project_step) if project_step_form.is_valid(): project_step_form.save() if project.is_published(): action.send(user, verb='updated', action_object=project_step, target=project) # User clicked "save and add another" if 'save-add' in request.POST: redirect_args = ('project-step-create-edit', project.slug) # User clicked "save" (catch anything else) else: redirect_args = (project, ) return redirect(*redirect_args) return render( request, 'project/project_step_create_edit.html', { 'project': project, 'project_step': project_step, 'project_step_form': project_step_form, })
def on_created_like(sender, instance: dillo.models.mixins.Likes, created, **kwargs): """Actions to perform once a Like is created.""" if ( isinstance(instance.content_object, dillo.models.comments.Comment) and instance.content_object.parent_comment ): target = instance.content_object.parent_comment else: target = None log.debug('Generating like activity') # TODO(fsiddi) Prevent duplicate activity. # If the user likes a post or comment after having unliked it, do not generate activity. action.send(instance.user, verb='liked', action_object=instance.content_object, target=target) # Increase likes_count for profile of content owner their content is liked. if not created: return target_user = instance.content_object.user dillo.models.profiles.Profile.objects.filter(user=target_user).update( likes_count=F('likes_count') + 1 ) log.debug('Increased like count for user %s' % target_user)
def website_post_add_or_edit(sender, instance, **kwargs): """ receive signals when user adding/editing Post Website """ user = instance.author if kwargs.get('created', False): add_actor = Actor.objects.get(user=user) add_activity = Verb.objects.get(name='website_post_adding') add_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.title) action.send(add_actor, verb=add_activity, description=add_activity.description, action_object=add_object) else: edit_actor = Actor.objects.get(user=user) edit_activity = Verb.objects.get(name='website_post_editing') edit_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.title) action.send(edit_actor, verb=edit_activity, description=edit_activity.description, action_object=edit_object)
def event_assessment_add_or_edit(sender, instance, **kwargs): """ receive signals when user adding/editing Event Assessment Disaster Rehabilitation """ user = get_current_user() if kwargs.get("created", False): add_actor = Actor.objects.get(user=user) add_activity = Verb.objects.get(name='event_assessment_adding') add_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.name) action.send(add_actor, verb=add_activity, description=add_activity.description, action_object=add_object) else: edit_actor = Actor.objects.get(user=user) edit_activity = Verb.objects.get(name='event_assessment_editing') edit_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.name) action.send(edit_actor, verb=edit_activity, description=edit_activity.description, action_object=edit_object)
def website_video_add_or_edit(sender, instance, **kwargs): """ receive signals when user adding/editing Video Website """ user = get_current_user() if kwargs.get("created", False): add_actor = Actor.objects.get(user=user) add_activity = Verb.objects.get(name='website_video_adding') add_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.title) action.send(add_actor, verb=add_activity, description=add_activity.description, action_object=add_object) else: edit_actor = Actor.objects.get(user=user) edit_activity = Verb.objects.get(name='website_video_editing') edit_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.title) action.send(edit_actor, verb=edit_activity, description=edit_activity.description, action_object=edit_object)
def waterlevel_report_add_or_edit(sender, instance, **kwargs): """ receive signals when user adding/editing WaterLevelReport """ user = get_current_user() if kwargs.get('created', False): add_actor = Actor.objects.get(user=user) add_activity = Verb.objects.get(name='waterlevel_report_adding') add_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.watergate) action.send(add_actor, verb=add_activity, description=add_activity.description, action_object=add_object) else: edit_actor = Actor.objects.get(user=user) edit_activity = Verb.objects.get(name='sensor_report_adding') edit_object = Object.objects.create(obj_id=instance.pk, obj_text=instance.watergate) action.send(edit_actor, verb=edit_activity, description=edit_activity.description, action_object=edit_object)