def send_document_notifications(sender, instance=None, **kwargs): if instance is None: return document = instance if not document.is_public(): return subs = Subscription.objects.filter(author=document.author) for org in document.author.organization_set.all(): subs |= Subscription.objects.filter(organization=org) for tag in document.tags.all(): subs |= Subscription.objects.filter(tag=tag) recipients = [] if document.in_reply_to_id: campaign = None try: campaign = document.in_reply_to.campaign except Campaign.DoesNotExist: pass if campaign: subs |= Subscription.objects.filter(campaign=campaign) for sub in subs: if NotificationBlacklist.objects.filter(email=sub.subscriber.email).exists(): continue if document.adult and not sub.subscriber.profile.show_adult_content: continue log, created = DocumentNotificationLog.objects.get_or_create(recipient=sub.subscriber, document=document) if created: recipients.append(sub.subscriber) if recipients: notification.send(recipients, "new_post", {"document": document})
def notification_post_delete_resource(instance, sender, **kwargs): """ Send a notification when a layer, map or document is deleted """ notice_type_label = '%s_deleted' % instance.class_name.lower() recipients = get_notification_recipients(notice_type_label) notification.send(recipients, notice_type_label, {'resource': instance}) send_queued_notifications.delay()
def reply_to_thread(thread,sender, body): new_message = Message.objects.create(body=body, sender=sender) new_message.parent_msg = thread.latest_msg thread.latest_msg = new_message thread.all_msgs.add(new_message) thread.replied = True thread.save() new_message.save() recipients = [] for participant in thread.participants.all(): participant.deleted_at = None participant.save() if sender != participant.user: # dont send emails to the sender! recipients.append(participant.user) sender_part = Participant.objects.get(thread=thread, user=sender) sender_part.replied_at = sender_part.read_at = datetime.datetime.now() sender_part.save() if notification: for r in recipients: if tm_settings.THREADED_MESSAGES_USE_SENDGRID: reply_email = sendgrid_parse_api.utils.create_reply_email(tm_settings.THREADED_MESSAGES_ID, r, thread) notification.send(recipients, "received_email", {"thread": thread, "message": new_message}, from_email=reply_email.get_reply_email()) else: notification.send([r], "received_email", {"thread": thread, "message": new_message}) return (thread, new_message)
def promo_add(request): """ Process a new promo submission. """ if request.method == "POST": form = PromoForm(request.POST) if form.is_valid(): promo = form.save(commit=False) promo.submitter = request.user promo.save() if notification: to_user = User.objects.all()[0] from_user = User.objects.all()[0] notification.send([to_user], "promo_submitted", "you have received a promo.", [from_user]) request.user.message_set.create( message='Your promo has been submitted.') return HttpResponseRedirect(reverse('promos_promo_list')) else: form = PromoForm() return render_to_response( 'promos/promo_add.html', {'form':form}, context_instance=RequestContext(request))
def undelete(request, message_id, success_url=None): """ Recovers a message from trash. This is achieved by removing the ``(sender|recipient)_deleted_at`` from the model. """ user = request.user message = get_object_or_404(Message, id=message_id) undeleted = False if success_url is None: success_url = reverse('messages_inbox') if request.GET.has_key('next'): success_url = request.GET['next'] if message.sender == user: message.sender_deleted_at = None undeleted = True if message.recipient == user: message.recipient_deleted_at = None undeleted = True if undeleted: message.save() messages.info(request, _(u"Message successfully recovered.")) if notification: notification.send([user], "messages_recovered", {'message': message,}) return HttpResponseRedirect(success_url) raise Http404
def mem_vip_appl(request, **kwargs): """ VIP申请提醒 """ template_name = "member/memmin_upgrade_appl.html" MinUpgradeRecord = "" has_appl = False try: UserBasic = user_basic.objects.defer(None).get(user=request.user) except: raise Http404 if request.method == "POST": bank_name_list = request.POST.get("bank_name_list") MinUpgradeRecord = min_upgrade_record(user=UserBasic) form = MemVipApllForm(request.POST, user=request.user) print form if form.is_valid(): form = MemVipApllForm(request.POST, user=request.user, instance=MinUpgradeRecord) form.save() extra_context = UserBasic.number + "申请成为VIP" print extra_context users = User.objects.filter(is_superuser=True) notification.send(users, "vip_appl", extra_context, True, request.user) return HttpResponseRedirect(reverse("member_details")) else: MinUpgradeRecord = min_upgrade_record.objects.defer(None).filter(user=UserBasic) form = MemVipApllForm() if MinUpgradeRecord: has_appl = True ctx = {"form": form, "has_appl": has_appl} return render_to_response(template_name, RequestContext(request, ctx))
def undelete(request, message_id, success_url=None): """ Recovers a message from trash. This is achieved by removing the ``(sender|recipient)_deleted_at`` from the model. """ user = request.user message = get_object_or_404(Message, id=message_id) undeleted = False if success_url is None: success_url = reverse('messages_inbox') if 'next' in request.GET: success_url = request.GET['next'] if message.sender == user: message.sender_deleted_at = None undeleted = True if message.recipient == user: message.recipient_deleted_at = None undeleted = True if undeleted: message.save() messages.info(request, _(u"Message successfully recovered.")) #signals added by [email protected] # signals.message_state_change.send(sender=user.__class__, # request=request, # user=user) if notification: notification.send([user], "messages_recovered", {'message': message,}) return HttpResponseRedirect(success_url) raise Http404
def new(request, form_class=BlogForm, template_name="blog/new.html"): profile = request.user.get_profile() if request.method == "POST": if request.POST["action"] == "create": blog_form = form_class(request.user, request.POST) if blog_form.is_valid(): blog = blog_form.save(commit=False) blog.author = request.user blog.body = blog.body.replace("\n","<br>") blog.body = blog.body.replace("\n\r","<br>") blog.body = blog.body.replace("\r","<br>") if getattr(settings, 'BEHIND_PROXY', False): blog.creator_ip = request.META["HTTP_X_FORWARDED_FOR"] else: blog.creator_ip = request.META['REMOTE_ADDR'] blog.save() # @@@ should message be different if published? request.user.message_set.create(message=_("Successfully saved post '%s'") % blog.title) if notification: if blog.status == 2: # published if friends: # @@@ might be worth having a shortcut for sending to all friends notification.send((x['friend'] for x in Friendship.objects.friends_for_user(blog.author)), "blog_friend_post", {"post": blog}) return HttpResponseRedirect(reverse("blog_list_yours")) else: blog_form = form_class() else: blog_form = form_class() return render_to_response(template_name, { "blog_form": blog_form, "profile": profile, }, context_instance=RequestContext(request))
def change_info_appl(request, **kwargs): """ 会员信息修改申请 """ UserBasic = kwargs.pop("Mem") template_name = "member/change_info_appl.html" if request.method == "POST": form = ChangeInfoApplForm(request.POST, user=request.user) has_exit = "信息错误" print form if form.is_valid(): UserModifyRecord = user_modify_record.objects.filter(user=UserBasic, state="wait") if not UserModifyRecord: UserModifyRecord = user_modify_record(user=UserBasic, state="wait") form = ChangeInfoApplForm(request.POST, user=request.user, instance=UserModifyRecord) form.save() extra_context = UserBasic.name + "提交了信息修改申请" users = User.objects.filter(is_superuser=True) notification.send(users, "announcement_notice", extra_context, True, request.user) return HttpResponseRedirect(reverse("member_index")) else: has_exit = "您已经有申请在处理中,请耐心等候" else: form = ChangeInfoApplForm() has_exit = "" ctx = {"UserBasic": UserBasic, "form": form, "has_exit": has_exit} return render_to_response(template_name, RequestContext(request, ctx))
def price_add(request, form_class=PriceForm, template_name="product/price_add.html"): if request.user.is_authenticated() and request.method == "POST": if request.POST["action"] == "create": product_form = form_class(request.POST) if product_form.is_valid(): product = product_form.save(commit=False) product.creator = request.user product.save() # product.members.add(request.user) # product.save() if notification: # @@@ might be worth having a shortcut for sending to all users notification.send(User.objects.all(), "product_new_product", {"product": product}, queue=True) if friends: # @@@ might be worth having a shortcut for sending to all friends notification.send((x['friend'] for x in Friendship.objects.friends_for_user(product.creator)), "product_friend_product", {"product": product}) #return render_to_response("base.html", { #}, context_instance=RequestContext(request)) return HttpResponseRedirect(product.get_absolute_url()) else: product_form = form_class() else: product_form = form_class() return render_to_response(template_name, { "product_form": product_form, }, context_instance=RequestContext(request))
def edit(request,incident_id=None,form_class=EditIncidentForm, template_name='incidents/create.html'): incident = get_object_or_404(Incident,id=incident_id) incdict = incident.__dict__ incdict['priority'] = incdict['priority_id'] incdict['status'] = incdict['status_id'] incident_form = form_class(request.POST or incdict) if request.POST and incident_form.is_valid(): fcd = incident_form.cleaned_data for k in fcd.keys(): incident.__dict__[k] = fcd[k] isaved = incident_form.save(commit=False) incident.priority = isaved.priority incident.status = isaved.status incident.mentor = request.user incident.save() if incident.priority.hierarchy == 5: admins = User.objects.filter(is_superuser = 1) for admin in admins: notification.send([admin], "new_high_priority_manager", {"date": datetime.now(), "incident":incident, "categories":incident.categories, "author":request.user, "description":incident.description}) return HttpResponseRedirect('/incidents/incident/'+str(incident_id)+'/') return render_to_response(template_name, { "incident_form" : incident_form, "action" : 'Edit', }, context_instance = RequestContext(request))
def save(self, sender, parent_msg=None): r = self.cleaned_data['recipient'] subject = self.cleaned_data['subject'] body = self.cleaned_data['body'] message_list = [] r = User.objects.get(id=r) msg = Message( sender = sender, recipient = r, subject = subject, body = body, ) if parent_msg is not None: msg.parent_msg = parent_msg parent_msg.replied_at = datetime.datetime.now() parent_msg.save() msg.save() message_list.append(msg) if notification: if parent_msg is not None: notification.send([sender], "messages_replied", {'message': msg,}) else: notification.send([sender], "messages_sent", {'message': msg,}) return message_list
def accept(self, user): """Accept this nomination for the nominee. Also awards, if already approved. """ if not self.allows_accept(user): raise NominationAcceptNotAllowedException() self.accepted = True nomination_will_be_accepted.send(sender=self.__class__, nomination=self) self.save() nomination_was_accepted.send(sender=self.__class__, nomination=self) if notification: if self.badge.creator: notification.send([self.badge.creator], 'nomination_accepted', dict(nomination=self, protocol=DEFAULT_HTTP_PROTOCOL)) if self.creator: notification.send([self.creator], 'nomination_accepted', dict(nomination=self, protocol=DEFAULT_HTTP_PROTOCOL)) return self
def new_comment(sender, instance, **kwargs): if isinstance(instance.content_object, Topic): topic = instance.content_object topic.modified = datetime.now() topic.save() if notification: notification.send([topic.creator], "tribes_topic_response", {"user": instance.user, "topic": topic})
def edit(request, id, form_class=BlogForm, template_name="blog/edit.html"): post = get_object_or_404(Post, id=id) if request.method == "POST": if post.author != request.user: request.user.message_set.create(message="You can't edit posts that aren't yours") return HttpResponseRedirect(reverse("blog_list_yours")) if request.POST["action"] == "update": blog_form = form_class(request.user, request.POST, instance=post) if blog_form.is_valid(): blog = blog_form.save(commit=False) blog.save() request.user.message_set.create(message=_("Successfully updated post '%s'") % blog.title) if notification: if blog.status == 2: # published if friends: # @@@ might be worth having a shortcut for sending to all friends notification.send((x['friend'] for x in Friendship.objects.friends_for_user(blog.author)), "blog_friend_post", {"post": blog}) return HttpResponseRedirect(reverse("blog_list_yours")) else: blog_form = form_class(instance=post) else: blog_form = form_class(instance=post) return render_to_response(template_name, { "blog_form": blog_form, "post": post, }, context_instance=RequestContext(request))
def notify_gasstock_product_enabled(sender, **kwargs): gasstock = sender extra_content = { 'gas' : gasstock.gas, 'product' : gasstock.product, 'action' : _("enabled"), } #Cannot resolve keyword 'gasmember_set' into field. Choices are: address, avatar, contact_set, delivery_for_order_set, des, display_name, gas, gasactivist, gasmember, historicaldelivery_for_order_set, historicalgasactivist, historicalgasmember, historicalorder_set, historicalsupplier_frontman_set, historicalsupplieragent, historicalwithdrawal_for_order_set, id, name, order_set, ssn, supplier, supplier_frontman_set, supplieragent, surname, user, website, withdrawal_for_order_set recipients = User.objects.filter( # person__gasmember_set__in=gasstock.gasmembers person__gasmember__in=gasstock.gasmembers ).distinct() log.debug("notify_gasstock_product_enabled recipients %s " % recipients) try: notification.send(recipients, "gasstock_update", extra_content ) except Exception as e: log.error("Send msg notify_gasstock_product_enabled: %s (%s)" % (e.message, type(e))) log.debug('EEEEEEEEEEEEEE notification notify_gasstock_product_enabled %s (%s)' % (e.message, type(e))) pass
def delete(request, message_id, success_url=None): """ Marks a message as deleted by sender or recipient. The message is not really removed from the database, because two users must delete a message before it's save to remove it completely. A cron-job should prune the database and remove old messages which are deleted by both users. As a side effect, this makes it easy to implement a trash with undelete. You can pass ?next=/foo/bar/ via the url to redirect the user to a different page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message. """ user = request.user now = datetime.datetime.now() message = get_object_or_404(Message, id=message_id) deleted = False if success_url is None: success_url = reverse('messages_inbox') if request.GET.has_key('next'): success_url = request.GET['next'] if message.sender == user: message.sender_deleted_at = now deleted = True if message.recipient == user: message.recipient_deleted_at = now deleted = True if deleted: message.save() messages.info(request, _(u"Message successfully deleted.")) if notification: notification.send([user], "messages_deleted", {'message': message,}) return HttpResponseRedirect(success_url) raise Http404
def watch(request, listing_id): ''' takes a POST and makes a watcher of the request.user ''' listing = get_object_or_404(Listing, id=listing_id) if request.method == 'POST': if request.POST["action"] == "watch": w, created = WatchRelation.objects.get_or_create( watcher=request.user, listing=listing ) notification.send([listing.owner], "listing_watch_start",{ "listing":listing, "watcher":w.watcher,} ) elif request.POST["action"] == "stop": w = WatchRelation.objects.get(listing=listing, watcher=request.user) w.delete() notification.send([listing.owner], "listing_watch_stop",{ "listing":listing, "watcher":w.watcher,} ) return HttpResponseRedirect(reverse('listings_all')) else: return HttpResponseRedirect(reverse('listings_all'))
def group(request, group_slug=None, form_class=BasicGroupUpdateForm, template_name="basic_groups/group.html"): group = get_object_or_404(BasicGroup, slug=group_slug) group_form = form_class(request.POST or None, instance=group) action = request.POST.get('action') if action == "update" and group_form.is_valid(): group = group_form.save() elif action == "join": group.members.add(request.user) request.user.message_set.create(message="You have joined the group %s" % group.name) if notification: notification.send([group.creator], "groups_created_new_member", {"user": request.user, "group": group}) notification.send(group.members.all(), "groups_new_member", {"user": request.user, "group": group}) elif action == "leave": group.members.remove(request.user) request.user.message_set.create(message="You have left the group %s" % group.name) if notification: pass # @@@ no notification on departure yet if not request.user.is_authenticated(): is_member = False else: is_member = group.user_is_member(request.user) return render_to_response(template_name, { "group_form": group_form, "group": group, "is_member": is_member, }, context_instance=RequestContext(request))
def rating_post_save(instance, sender, created, **kwargs): """ Send a notification when rating a layer, map or document """ notice_type_label = '%s_rated' % instance.content_object.class_name.lower() recipients = get_notification_recipients(notice_type_label, instance.user) notification.send(recipients, notice_type_label, {"instance": instance}) send_queued_notifications.delay()
def follow(request, username, public_profile_field=None, template_name='profiles/profile_list.html', extra_context=None): from_user= request.user to_user = User.objects.get(username=username) #follower friendship type friendship = Friendship.objects.filter(from_user=from_user, to_user=to_user) if friendship.count() >0: friendship[0].reactivate() else: friendship = Friendship(from_user=from_user, to_user=to_user, relation_mutual=False) friendship.save() if notification: notification.send([to_user], "new_follower", {"new_follower": from_user}) #stats from_user_stats = ProfileStats.objects.get(user=from_user) from_user_stats.following = int(from_user_stats.following) + 1 from_user_stats.save() to_user_stats = ProfileStats.objects.get(user=to_user) to_user_stats.followers = int(to_user_stats.followers) + 1 to_user_stats.save() response = {'success':True} if request.is_ajax(): json_response = simplejson.dumps(response) return HttpResponse(json_response, mimetype="application/json") return HttpResponseRedirect(reverse('profiles_profile_detail', kwargs={ 'username': username }))
def save(self, force_insert=False, force_update=False): self.slug = slugify(self.title) if self.pk: new=False else: new=True super(Listing, self).save(force_insert, force_update) #if new and notification: # notification.send(User.objects.all().exclude(id=self.owner.id), # "listing_new", # {'listing':self, }, # ) if notification and (self.state == 2 or self.state == 3): notification.send(User.objects.filter(watchrelation__listing=self).exclude(id=self.owner.id), "listing_done", {'listing':self, }, ) elif notification: notification.send(User.objects.filter(watchrelation__listing=self).exclude(id=self.owner.id), "listing_change", {'listing':self, }, )
def delete(self): if notification: notification.send(User.objects.filter(watchrelation__listing=self).exclude(id=self.owner.id), "listing_delete", {'listing':self, }, ) super(Listing, self).delete()
def tweet(sender, instance, created, **kwargs): #if tweet is None: # tweet = Tweet.objects.create(text=text, sender=user) recipients = set() # keep track of who's received it user = instance.sender # add the sender's followers user_content_type = ContentType.objects.get_for_model(user) followings = Following.objects.filter(followed_content_type=user_content_type, followed_object_id=user.id) for follower in (following.follower_content_object for following in followings): recipients.add(follower) # add sender recipients.add(user) # if starts with @user send it to them too even if not following match = reply_re.match(instance.text) if match: try: reply_recipient = User.objects.get(username=match.group(1)) recipients.add(reply_recipient) except User.DoesNotExist: pass # oh well else: if notification: notification.send([reply_recipient], "tweet_reply_received", {'tweet': instance,}) # now send to all the recipients for recipient in recipients: tweet_instance = TweetInstance.objects.create(text=instance.text, sender=user, recipient=recipient, sent=instance.sent)
def profile_pre_save(instance, sender, **kw): matching_profiles = Profile.objects.filter(id=instance.id) if matching_profiles.count() == 0: return if instance.is_active and not matching_profiles.get().is_active and \ 'notification' in settings.INSTALLED_APPS: notification.send([instance, ], "account_active")
def notify_about_event(instance, notice_type, employers): subscribers = Student.objects.filter(subscriptions__in=employers) to_users = list(set(map(lambda n: n.user, subscribers))) if not instance.is_public: to_users = filter(lambda u: Invitee.objects.filter(student = u.student, event=instance).exists(), to_users) # Batch the sending by unique groups of subscriptions. # This way someone subscribed to A, B, and C gets only one email. subscribers_by_user = {} employername_table = {} for employer in employers: employername_table[str(employer.id)] = employer.name for to_user in to_users: if to_user.student in employer.subscribers.all(): if to_user.id in subscribers_by_user: subscribers_by_user[to_user.id].append(employer.id) else: subscribers_by_user[to_user.id] = [employer.id] subscription_batches = {} for userid,employerids in subscribers_by_user.items(): key = ':'.join(map(lambda n: str(n), employerids)) subscription_batches[key] = userid for key,userids in subscription_batches.items(): employer_names = map(lambda n: employername_table[n], key.split(':')) has_word = "has" if len(employer_names)==1 else "have" employer_names = english_join(employer_names) for to_user in to_users: notification.send([to_user], notice_type, { 'name': to_user.first_name, 'employer_names': employer_names, 'has_word': has_word, 'event': instance, })
def topics(request, slug, form_class=TopicForm, template_name="projects/topics.html"): project = get_object_or_404(Project, slug=slug) if project.deleted: raise Http404 is_member = project.has_member(request.user) if request.method == "POST": if is_member: topic_form = form_class(request.POST) if topic_form.is_valid(): topic = topic_form.save(commit=False) topic.project = project topic.creator = request.user topic.save() request.user.message_set.create(message="You have started the topic %s" % topic.title) if notification: notification.send(project.member_users.all(), "projects_new_topic", {"creator": request.user, "topic": topic, "project": project}) topic_form = form_class() # @@@ is this the right way to reset it? else: request.user.message_set.create(message="You are not a member and so cannot start a new topic") topic_form = form_class() else: topic_form = form_class() return render_to_response(template_name, { "project": project, "is_member": is_member, "topic_form": topic_form, }, context_instance=RequestContext(request))
def save(self, commit=True): recipients = self.cleaned_data['recipients'] instance = super(MessageForm, self).save(commit=False) instance.sender = self.sender instance.owner = self.sender instance.recipient = recipients[0] instance.thread = self.get_thread(instance) instance.unread = False instance.sent_at = datetime.datetime.now() message_list = [] # clone messages in recipients inboxes for r in recipients: if r == self.sender: # skip duplicates continue msg = self.create_recipient_message(r, instance) message_list.append(msg) instance.to = ','.join([r.username for r in recipients]) if commit: instance.save() for msg in message_list: msg.save() if notification: notification.send([msg.recipient], "messages_received", {'message': msg,}) return instance, message_list
def create(request, form_class=TribeForm, template_name="tribes/create.html"): if request.user.is_authenticated() and request.method == "POST": if request.POST["action"] == "create": tribe_form = form_class(request.POST) if tribe_form.is_valid(): tribe = tribe_form.save(commit=False) tribe.creator = request.user tribe.save() tribe.members.add(request.user) tribe.save() # @@@ this is just temporary to give tribes a single calendar -- will revisit during whole # tribe/project merge effort calendar = Calendar(name = "%s Calendar" % tribe.name) calendar.save() CalendarRelation.objects.create_relation(calendar, tribe, distinction="default", inheritable=True) if notification: # @@@ might be worth having a shortcut for sending to all users notification.send(User.objects.all(), "tribes_new_tribe", {"tribe": tribe}, queue=True) if friends: # @@@ might be worth having a shortcut for sending to all friends notification.send((x['friend'] for x in Friendship.objects.friends_for_user(tribe.creator)), "tribes_friend_tribe", {"tribe": tribe}) #return render_to_response("base.html", { #}, context_instance=RequestContext(request)) return HttpResponseRedirect(tribe.get_absolute_url()) else: tribe_form = form_class() else: tribe_form = form_class() return render_to_response(template_name, { "tribe_form": tribe_form, }, context_instance=RequestContext(request))
def notify_topic_subscribers(post): topic = post.topic if post != topic.head: delete_url = reverse("pybb:delete_subscription", args=[post.topic.id]) current_site = Site.objects.get_current() if notification: notification.send( topic.subscribers.exclude(pk=post.user.pk), "forum_subscription_reply", {"site": current_site, "post": post, "delete_url": delete_url}, ) else: for user in topic.subscribers.all(): if user != post.user: try: email_validator.clean(user.email) except: # invalid email continue old_lang = translation.get_language() lang = user.get_profile().language or dict(settings.LANGUAGES)[settings.LANGUAGE_CODE.split("-")[0]] translation.activate(lang) subject = render_to_string( "pybb/mail_templates/subscription_email_subject.html", {"site": current_site, "post": post} ) # Email subject *must not* contain newlines subject = "".join(subject.splitlines()) message = render_to_string( "pybb/mail_templates/subscription_email_body.html", {"site": current_site, "post": post, "delete_url": delete_url}, ) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=True) translation.activate(old_lang)
def unhide_post(self): """Unhide post(s) and inform subscribers.""" self.hidden = False self.save() if self.topic.post_count == 1: # The topic is new send(User.objects.all(), 'forum_new_topic', { 'topic': self.topic, 'post': self, 'user': self.topic.user }) else: # Inform topic subscribers send(self.topic.subscribers.all(), 'forum_new_post', { 'post': self, 'topic': self.topic, 'user': self.user })
def handle_pledge_modified(sender, transaction=None, up_or_down=None, **kwargs): # we need to know if pledges were modified up or down because Amazon handles the # transactions in different ways, resulting in different user-visible behavior; # we need to set expectations appropriately # up_or_down is 'increased', 'decreased', or 'canceled' if transaction == None or up_or_down == None: return if up_or_down == 'canceled': transaction.user.profile.reset_pledge_badge() notification.send([transaction.user], "pledge_status_change", { 'transaction': transaction, 'up_or_down': up_or_down }, True) from regluit.core.tasks import emit_notifications emit_notifications.delay()
def conflict(self, conflicting_swap): self.state = 6 self.conflicted_by = conflicting_swap self.killed_time = datetime.now() self.revert_offers() if notification: notification.send([ self.proposing_offer.offerer, ], "swaps_conflict", { "losing_swap": self, "winning_swap": conflicting_swap }) notification.send([ self.responding_offer.offerer, ], "swaps_conflict", { "losing_swap": self, "winning_swap": conflicting_swap })
def bulk_upload(self, request): log.info("Bulk upload docs for user %s" % request.user.username) log.debug('request data=%s' % request.data) resp = [] try: for name, file in request.data.iteritems(): doc = UserDocument(user=request.user, file=file, name=name) doc.clean_fields() doc.save() resp.append(doc) except ValidationError: raise exceptions.ValidationError(_("Bad file extension or size!")) if not resp: raise exceptions.ValidationError(_("No documents uploaded!")) else: notification.send([self.request.user], 'checkdocument_issue') return Response(self.serializer_class(resp, many=True).data)
def notify(self, **kwargs): if not notification: return if not self.previous: all_recipients = set() if self.is_private: recipients = set(self.private.all()) if recipients: notification.send(recipients, 'private_post_received', {'post': self}) all_recipients = all_recipients.union(recipients) recipients = set( (wl.user for wl in WatchList.objects.filter(thread=self.thread) if wl.user not in all_recipients)) if recipients: notification.send(recipients, 'new_post_in_watched_thread', {'post': self}) all_recipients = all_recipients.union(recipients)
def save(self): """Will notify the recipient and also the sender.""" self.pasted_item = self.cleaned_data['uuid'] self.recipient_user = self.cleaned_data['recipient'] if notification: notification.send( [self.sender], "pasteditem_sent", { 'pasted_item': self.pasted_item, 'sender': self.sender, 'recipient': self.recipient_user, }) notification.send( [self.recipient_user], "pasteditem_received", # If the last argument is wrong it raises a NoticeType matching query does not exist. { 'pasted_item': self.pasted_item, 'sender': self.sender, })
def accept(self, new_user): # mark invitation accepted self.status = "5" self.save() # auto-create friendship friendship = Friendship(to_user=new_user, from_user=self.from_user) friendship.save() # notify if notification: notification.send([self.from_user], "join_accept", { "invitation": self, "new_user": new_user }) friends = [] for user in friend_set_for(new_user) | friend_set_for( self.from_user): if user != new_user and user != self.from_user: friends.append(user)
def attribute_edit(request, id, template_name="exploration/attributes/edit.html"): group, bridge = group_and_bridge(request) ctx = group_context(group, bridge) is_member = group.user_is_member(request.user) if not is_member: return HttpResponseForbidden("You must be a project member to do this") attr = get_object_or_404(FAttribute, pk=id) if request.method == 'POST': if 'delete' in request.POST: attr_name = attr.name # ExplorationWrapper.delete_attribute(attr.pk) attr.delete() ExplorationWrapper.touch(group) if notification: notification.send( group.member_users.all(), "context_remove_attribute", { "user": request.user, "attribute_name": attr_name, "project": group, }) return HttpResponseRedirect( bridge.reverse('edit_attributes', group)) else: form = AttributeForm(request.POST, instance=attr) if form.is_valid(): form.save() ExplorationWrapper.touch(group) return HttpResponseRedirect( bridge.reverse( 'edit_attributes', group, )) else: form = AttributeForm(instance=attr) data_dictionary = {"attribute": attr, "project": group, "form": form} return render_to_response(template_name, data_dictionary, context_instance=RequestContext(request, ctx))
def generate_report(context, template, decimal_separator, saved_report, language, user): translation.activate(language) if context.get('account'): if isinstance(context['account'], int): context['account'] = TradingAccount(mt4_id=context['account']) api = context['account'].get_api("db") else: api = DatabaseAPI() try: context['report'] = getattr(api, context['report_type'])(user=user, **context) except Exception: #Some error happened. We should at least notify user and admins and delete the report. e = sys.exc_info() notification.send([saved_report.for_user], 'report_generation_failed', extra_context={'name': saved_report.name}) mail_admins( u"Report generation FAILED", u"Generation of report %s for user \ ID=%d FAILED. Celery task id: %s\n%s: %s\nTraceback\n%s" % (saved_report.name, saved_report.for_user.pk, saved_report.celery_task_id, e[0], e[1], ''.join( traceback.format_list(traceback.extract_tb(e[2]))))) saved_report.delete() raise context['DECIMAL_SEPARATOR'] = decimal_separator context["STATIC_URL"] = "/static/" result_html = loader.render_to_string(template_name=template, dictionary=context) filename = str(uuid4()) + ".html" outfile = open(settings.SAVED_REPORTS_PATH + filename, 'w') outfile.write(result_html.encode('utf-8')) outfile.close() saved_report.filename = filename saved_report.save() notification.send([saved_report.for_user], 'report_has_been_generated', extra_context={ 'name': saved_report.name, 'report_id': saved_report.pk }) return {'result': saved_report}
def apply_to_join_group(self, request, group_id, extra_context=None): """Allow a user to apply to join group. Will return a JSON serialized dict if called with headers picked up by ``is_ajax()``. """ group = get_object_or_404(self.model, pk=group_id) if request.method != 'POST': return self.confirmation(request, 'apply_to_join', group, extra_context) already_member = request.user in group.members.all() if not already_member: ctype = ContentType.objects.get_for_model(self.model) (application, created) = \ UserGroupApplication.objects.get_or_create(user=request.user, content_type=ctype, object_id=group.pk) if created and notification: context = { 'application': application, 'group': group, } notification.send(group.admins.all(), 'usergroups_application', context) extra_context = extra_context or {} extra_context.update({ 'group': group, 'already_member': already_member, }) action = already_member and 'application_failed' or 'application_sent' if request.is_ajax(): data = { 'already_member': already_member } return self.json_done(request, action, data, group, extra_context) return http.HttpResponseRedirect(reverse('usergroups_%s' % action, args=(self.slug, group.pk)))
def group(request, group_slug=None, form_class=BasicGroupUpdateForm, template_name="basic_groups/group.html"): group = get_object_or_404(BasicGroup, slug=group_slug) group_form = form_class(request.POST or None, instance=group) action = request.POST.get('action') if action == "update" and group_form.is_valid(): group = group_form.save() elif action == "join": group.members.add(request.user) request.user.message_set.create( message="You have joined the group %s" % group.name) if notification: notification.send([group.creator], "groups_created_new_member", { "user": request.user, "group": group }) notification.send(group.members.all(), "groups_new_member", { "user": request.user, "group": group }) elif action == "leave": group.members.remove(request.user) request.user.message_set.create(message="You have left the group %s" % group.name) if notification: pass # @@@ no notification on departure yet if not request.user.is_authenticated(): is_member = False else: is_member = group.user_is_member(request.user) return render_to_response(template_name, { "group_form": group_form, "group": group, "is_member": is_member, }, context_instance=RequestContext(request))
def create(request, form_class=ProjectForm, template_name="projects/create.html"): project_form = form_class(request.POST or None) if project_form.is_valid(): project = project_form.save(commit=False) project.creator = request.user project.save() project_member = ProjectMember(project=project, user=request.user) project.members.add(project_member) project_member.save() if notification: # @@@ might be worth having a shortcut for sending to all users notification.send(User.objects.all(), "projects_new_project", {"project": project}, queue=True) return HttpResponseRedirect(project.get_absolute_url()) return render_to_response(template_name, { "project_form": project_form, }, context_instance=RequestContext(request))
def form_valid(self, *args, **kwargs): if self.home_team: # upon first submission, set date if not self.object.home_submission_date: self.object.home_submission_date = datetime.datetime.now() self.object.home_submitted = True else: # upon first submission, set date if not self.object.away_submission_date: self.object.away_submission_date = datetime.datetime.now() self.object.away_submitted = True self.object.save() if notification and self.object.home_submitted and self.object.away_submitted: notification.send(User.objects.exclude(username='******').filter(profile__teams__pk__in=(self.object.home_team_id, self.object.away_team_id)), "tournaments_lineup_ready", {'match': self.object, }) messages.success(self.request, 'Lineup submission successful.') return super(SubmitLineupView, self).form_valid(*args, **kwargs)
def send_notifications(self): """Send a notification to all users""" from datetime import datetime if notification: from django.contrib.auth.models import User context = { 'message': self, } notification.send(User.objects.filter(is_active=True), self.notification_type, context, on_site=False, queue=True) else: pass self.sent = datetime.now() self.save()
def send_notification(self, account, password): """Send account password recovery email to account user""" login = account._login if not login: if account.group_name in ['demoARM', 'ARM_MT4_Live']: login = account.mt4_id elif account.group_name in ['realstandard_ss']: login = account.user.email notification_data = { "user_name": account.user.first_name, "login": login, "account": account.mt4_id, "password": password } notification.send([account.user], self.notification_name, notification_data, no_django_message=True)
def send_otherconnect_notification(sender, instance, created, **kwargs): """ Sends new friend of friend notification. """ if notification and created: for user in Friendship.objects.friends_for_user(instance.to_user): if user != instance.from_user: notification.send( [user], "friends_otherconnect", { "your_friend": instance.to_user, "new_friend": instance.from_user }) for user in Friendship.objects.friends_for_user(instance.from_user): if user != instance.to_user: notification.send( [user], "friends_otherconnect", { "your_friend": instance.from_user, "new_friend": instance.to_user })
def team_join_withdraw(request, project_slug, language_code): team = get_object_or_404(Team, project__slug=project_slug, language__code=language_code) project = team.project access_request = get_object_or_404(TeamAccessRequest, team__pk=team.pk, user__pk=request.user.pk) if request.POST: try: access_request.delete() messages.success( request, _("You withdrew your request to join the '%s' team.") % team.language.name) # ActionLog & Notification # TODO: Use signals nt = 'project_team_join_withdrawn' context = { 'access_request': access_request, 'performer': request.user, 'sender': request.user } # Logging action action_logging(request.user, [project, team], nt, context=context) if settings.ENABLE_NOTICES: # Send notification for those that are observing this project txnotification.send_observation_notices_for( project, signal=nt, extra_context=context) # Send notification for maintainers, coordinators notification.send( set( itertools.chain(project.maintainers.all(), team.coordinators.all())), nt, context) except IntegrityError, e: transaction.rollback() logger.error("Something weird happened: %s" % str(e))
def team_request_deny(request, project_slug, language_code): team_request = get_object_or_404(TeamRequest, project__slug=project_slug, language__code=language_code) project = team_request.project if request.POST: try: team_request.delete() messages.success( request, _("You rejected the request by '%(user)s' for a '%(team)s' team." ) % { 'team': team_request.language.name, 'user': team_request.user }) # ActionLog & Notification # TODO: Use signals nt = 'project_team_request_denied' context = { 'team_request': team_request, 'performer': request.user, 'sender': request.user } # Logging action action_logging(request.user, [project], nt, context=context) if settings.ENABLE_NOTICES: # Send notification for those that are observing this project txnotification.send_observation_notices_for( project, signal=nt, extra_context=context) # Send notification for maintainers and the user notification.send( set( itertools.chain(project.maintainers.all(), [team_request.user])), nt, context) except IntegrityError, e: transaction.rollback() logger.error("Something weird happened: %s" % str(e))
def notify_gmo_product_erased(sender, **kwargs): gmo = sender extra_content = { 'order' : gmo.order, 'product' : gmo.product, 'action' : _("erased"), } recipients = [gmo.gasmember.person.user] try: notification.send(recipients, "ordered_product_update", extra_content ) except Exception as e: log.error("Send msg notify_gmo_product_erased: %s (%s)" % (e.message, type(e))) log.error('EEEEEEEEEEEEEE notification notify_gmo_product_erased %s (%s)' % (e.message, type(e))) pass
def user_follow_handler(user, target, instance, **kwargs): ''' user: the user who acted target: the user that has been followed instance: the follow object ''' from notification import models as notification notification.send_observation_notices_for(target, "followed", { "from_user": user, "owner": target }, [user]) if user != target: notification.send([target], "followed", {"from_user": user}, sender=user) notification.observe(target, user, "followed") notification.observe(target, user, "new") notification.observe(target, user, "favorited") notification.observe(target, user, "commented")
def save_model(self, request, obj, form, change): """ Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively resent to those users. """ obj.save() if notification: # Getting the appropriate notice labels for the sender and recipients. if obj.parent_msg is None: sender_label = 'messages_sent' recipients_label = 'messages_received' else: sender_label = 'messages_replied' recipients_label = 'messages_reply_received' # Notification for the sender. notification.send([obj.sender], sender_label, {'message': obj,}) if form.cleaned_data['group'] == 'all': # send to all users recipients = User.objects.exclude(pk=obj.recipient.pk) else: # send to a group of users recipients = [] group = form.cleaned_data['group'] if group: group = Group.objects.get(pk=group) recipients.extend( list(group.user_set.exclude(pk=obj.recipient.pk))) # create messages for all found recipients for user in recipients: obj.pk = None obj.recipient = user obj.save() if notification: # Notification for the recipient. notification.send([user], recipients_label, {'message' : obj,})
def save(self, profile=None): profile = profile or self.request.user.profile user = profile.user account = TradingAccount( platform_type='cfh', user=user, mt4_id=user.pk, group_name=GROUP_NAME_DEMO if self.account_type.is_demo else GROUP_NAME_REAL) if self.account_type.leverage_choices: account._leverage = self.cleaned_data.get('leverage', 50) password = account.api.account_create( account, initial_balance=self.cleaned_data.get('deposit', 0)) if password: account.save() Contact.objects.filter(user=user).exclude( tags__contains=['cfh']).update( tags=Func(F('tags'), Value('cfh'), function='array_append')) if self.account_type.is_demo: Contact.objects.filter(user=user).exclude( tags__contains=['demo']).update(tags=Func( F('tags'), Value('demo'), function='array_append')) notification.send( [user], 'demo_pro_account_created', { "password": password, 'type': self.account_type, "account": account.mt4_id, "login": account._login }) else: Contact.objects.filter(user=user).exclude( tags__contains=['real']).update(tags=Func( F('tags'), Value('real'), function='array_append')) notification.send( [user], 'real_pro_account_created', { "password": password, 'type': self.account_type, "account": account.mt4_id, "login": account._login }) return {"account": account, "password": password}
def batch_user_normalise_sq(): d = UserProfile.objects.aggregate(avg_sq=Avg('calculated_sq'), stddev_sq=StdDev('calculated_sq')) d['stddev_sq'] = max(1, d['stddev_sq']) # Prevent <1 sd mean # Store previous SQ value UserProfile.objects.all().update(previous_sq=F('sq')) #UPDATE {spenglr_users} SET nuSQ = 100 + ( ( ( uSQ - %d ) / %d ) * 16) WHERE questions_attempted>0 UserProfile.objects.all().update( sq=100 + (((F('calculated_sq') - d['avg_sq']) / d['stddev_sq']) * 16)) # Limit: this is horrible but using min() max() does not work on above query UserProfile.objects.filter(sq__gt=200).update(sq=200) UserProfile.objects.filter(sq__lt=0).update(sq=0) users_sq_changed = UserProfile.objects.exclude(sq=F('previous_sq')) for userp in users_sq_changed: notification.send([userp.user], "user_sq_updated", {"user": userp.user})
def notify_add_blog_post(sender, **kwargs): """ Notify to Action referrers and followers that a new post has been added to the Action blog #1 set the recipients (the receivers) #2 send notification(notification.send) Possible options: * 'now=True and queue=True': error * 'now=True and queue=False': send notice immediately by passing 'now=True' to send function * 'queue=True and now=False': queue the notice in order to send it later * 'now=False and queue=False'(default): let the default notification configuration decide QUESTION: should we pass the referrer who created the blog post as the sender of the notice (in sender=)? ANSWER: no, the sender is always "the system" """ if kwargs['created']: post = kwargs['instance'] # This is a generic Post post_save handler, # so we have to check if it is an answer if post.is_answer(): action = post.action referrers = action.referrers #WAS: followers = action.thread.followed_by.all() followers = action.followers # recipients users = referrers | followers extra_context = ({"blog_post": post, "action": action}) notification.send(users=users, label=notification_consts.ACTION_MAKE_BLOGPOST, extra_context=extra_context, on_site=True, sender=None, now=True)
def add(request, extra_context=None, next_override=None, upload_form=UploadAvatarForm, *args, **kwargs): if extra_context is None: extra_context = {} avatar, avatars = _get_avatars(request.user) upload_avatar_form = upload_form(request.POST or None, request.FILES or None, user=request.user) if request.method == "POST" and 'avatar' in request.FILES: if upload_avatar_form.is_valid(): avatar = Avatar( user=request.user, primary=True, ) image_file = request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() request.user.message_set.create( message=_("Successfully uploaded a new avatar.")) avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar) if notification: notification.send( [request.user], "Picture_added", { 'message': "You have successfully added new profile picture.", }) return HttpResponseRedirect(next_override or _get_next(request)) return render_to_response( 'avatar/add.html', extra_context, context_instance=RequestContext( request, { 'avatar': avatar, 'avatars': avatars, 'upload_avatar_form': upload_avatar_form, 'next': next_override or _get_next(request), }))
def reapply(self, editor): """Return the Article to this revision.""" # XXX Would be better to exclude reverted revisions # and revisions previous/next to reverted ones next_changes = self.article.changeset_set.filter( revision__gt=self.revision).order_by('-revision') article = self.article content = None for changeset in next_changes: if content is None: content = article.content patch = dmp.patch_fromText(changeset.content_diff) content = dmp.patch_apply(patch, content)[0] changeset.reverted = True changeset.save() old_content = article.content old_title = article.title old_markup = article.markup article.content = content article.title = changeset.old_title article.markup = changeset.old_markup article.save() article.new_revision(old_content=old_content, old_title=old_title, old_markup=old_markup, comment='Reverted to revision #%s' % self.revision, editor=editor) self.save() if None not in (notification, self.editor): notification.send([self.editor], 'wiki_revision_reverted', { 'revision': self, 'article': self.article })
def reply_to_thread(thread, sender, body): from .models import Message, Participant new_message = Message.objects.create(body=body, sender=sender) new_message.parent_msg = thread.latest_msg thread.latest_msg = new_message thread.all_msgs.add(new_message) thread.replied = True thread.save() new_message.save() recipients = [] for participant in thread.participants.all(): participant.deleted_at = None participant.save() if sender != participant.user: # dont send emails to the sender! recipients.append(participant.user) sender_part = Participant.objects.get(thread=thread, user=sender) sender_part.replied_at = sender_part.read_at = now() sender_part.save() invalidate_count_cache(Message, new_message) if notification: for r in recipients: if tm_settings.THREADED_MESSAGES_USE_SENDGRID: reply_email = sendgrid_parse_api.utils.create_reply_email( tm_settings.THREADED_MESSAGES_ID, r, thread) notification.send( recipients, "received_email", { "thread": thread, "message": new_message }, from_email=reply_email.get_reply_email(), headers={'Reply-To': reply_email.get_reply_to_email()}) else: notification.send([r], "received_email", { "thread": thread, "message": new_message }) return (thread, new_message)
def project_hub_join_deny(request, project_slug, outsourced_project_slug): hub_request = get_object_or_404(HubRequest, project__slug=outsourced_project_slug, project_hub__slug=project_slug) outsourced_project = hub_request.project if request.POST: try: _hub_request = copy.copy(hub_request) hub_request.delete() messages.info( request, _("You rejected the request of " "'%(project)s' to join the '%(project_hub)s' project hub") % { 'project': outsourced_project, 'project_hub': _hub_request.project_hub }) # ActionLog & Notification # TODO: Use signals nt = 'project_hub_join_denied' context = {'hub_request': hub_request, 'sender': request.user} # Logging action action_logging(request.user, [outsourced_project, _hub_request.project_hub], nt, context=context) if settings.ENABLE_NOTICES: # Send notification for maintainers, coordinators and the user notification.send(outsourced_project.maintainers.all(), nt, context) except IntegrityError, e: transaction.rollback() logger.error("Something weird happened: %s" % e.message) project_outsourced_changed.send(sender=hub_request.project_hub)
def team_delete(request, project_slug, language_code): project = get_object_or_404(Project, slug=project_slug) team = get_object_or_404(Team, project__pk=project.pk, language__code=language_code) if request.method == "POST": _team = copy.copy(team) team.delete() messages.success(request, _("The team '%s' was deleted.") % _team.language.name) # ActionLog & Notification # TODO: Use signals nt = 'project_team_deleted' context = {'team': _team, 'sender': request.user} #Delete rlstats for this team in outsourced projects for p in project.outsourcing.all(): RLStats.objects.select_related('resource').by_project_and_language( p, _team.language).filter(translated=0).delete() # Logging action action_logging(request.user, [project, _team], nt, context=context) if settings.ENABLE_NOTICES: # Send notification for those that are observing this project txnotification.send_observation_notices_for(project, signal=nt, extra_context=context) # Send notification for maintainers notification.send(project.maintainers.all(), nt, context) return HttpResponseRedirect( reverse("project_detail", args=(project_slug, ))) else: return render_to_response("teams/team_confirm_delete.html", { "team": team, "project": team.project }, context_instance=RequestContext(request))
def change_user_manager(request, user_id): if not (request.user.is_superuser or PersonalManager.objects.filter(user=request.user).exists()): raise Http404() user = get_object_or_404(User, pk=user_id) profile = user.profile req = ManagerReassignRequest(author=request.user, user=user, previous=profile.manager) form = ManagerReassignForm(request.POST or None, instance=req, request=request) if request.method == "POST" and form.is_valid(): req = form.save() # instant change is possible only in the cases: # it is superuser # it is head manager(like S.Solovyov) # it is local reassignment(X office -> X office manager) # and current user is supermanager in X office if (request.user.pk != 140743 and # T. Volchetckiy. Sorry, I do not want to add yet another checkbox to admin (req.assign_to and (request.user.crm_manager.is_head_supermanager or request.user.is_superuser)) or (request.user.crm_manager.is_office_supermanager and req.is_local and req.assign_to and req.assign_to.crm_manager.office == request.user.crm_manager.office) or not req.assign_to): req.accept(request.user, notify=True, completed_by_ip=request.META["REMOTE_ADDR"]) # if this request wasn't instant, we should send notification about it to heads if not req.is_completed: supers = User.objects.filter( crm_manager__is_office_supermanager=True, crm_manager__office=None) notification.send( list(supers) + [req.author], 'crm_reassignrequest_new', {'obj': req}) return {'profile': profile, 'form': form, 'obj': req}