def user_like_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.user, notification_type=1) notify.save()
def post(self, request, token=None): user = check_token(token) password = request.data.get('new_password', '') if not password: return Response( dict(status="error", error_code="new_password_required", message="You haven't provided a new password.")) # if we have a valid user if user: # check if the submitted password complies with the password_enforce_format pass_check = password_enforce_format(password) if pass_check: user.set_password(password) user.save() return Response( dict(status="error", error_code="invalid_password_format", message=pass_check)) else: package = dict( caller='jwt_auth', notification_type='RESET_PASSWORD_CONFIRMATION', recipients=[user.email, ], context=dict( username=user.username, password=password ) ) notify = Notification(**package) notify.send() return Response(dict(status="success", message="Password has been successfully reset")) else: return Response( dict(status="error", error_code="invalid_token", message="The token you provided is invalid or has expired."))
def put(self, request, *args, **kwargs): """ Update recipe """ if 'pk' not in kwargs: raise Http404() obj = get_object_or_404(Recipes, pk=kwargs['pk']) if obj.chef != request.user: self.raise_invalid_credentials() # Check if we have a new publication if obj.draft and request.DATA['draft'] == '0' and request.DATA[ 'private'] == '0': notify_new = True else: notify_new = False serializer = ApiRecipeSerializer(obj, data=request.DATA, files=request.FILES, partial=True) serializer.user = request.user if serializer.is_valid(): recipe = serializer.save() if notify_new: Notification.create_new_recipe(recipe) data = self.remove_unwanted_data(serializer.data) return Response({'recipe': data}) return self.invalid_serializer_response(serializer)
def post(self, request, *args, **kwargs): """ Add comment to recipe """ recipe = get_object_or_404(Recipes, pk=kwargs['recipe_pk']) if recipe.private and recipe.chef != request.user: return self.invalid_request( 'The recipe is private and the requestor is not the owner') book = recipe.book_for_sale() if book and not book.user_has_bought_it(request.user): return self.invalid_request( 'Recipe in book for sale and the user has not bought it') serializer = ApiCommentSerializer(data=request.DATA, files=request.FILES) serializer.user = request.user serializer.recipe = recipe if serializer.is_valid(): comment = serializer.save() recipe.update_comments() if request.user != recipe.chef: Notification.create_new_comment(comment) Notification.send_new_comment_to_thread(comment) return Response({'comment': serializer.data}) return self.invalid_serializer_response(serializer)
def user_comment_post(sender, instance, *args, **kwargs): comment = instance post = comment.post text_preview = comment.body[:90] sender = comment.user notify = Notification(post=post, sender=sender, user=post.user, text_preview=text_preview, notification_type=2) notify.save()
def buddy_click(request): buddy_subject_id = request.POST.get('buddy_subject_id', None) buddy_object_id = request.POST.get('buddy_object_id', None) buddy_action = request.POST.get('buddy_action', None) if buddy_action == 'buddy': Buddies.objects.create( buddy_subject_id=buddy_subject_id, buddy_object_id=buddy_object_id, status=Buddies.PENDING) buddying = 'buddy' elif buddy_action == 'accept': b = Buddies.objects.get( buddy_subject_id=buddy_subject_id, buddy_object_id=buddy_object_id) b.status = Buddies.BUDDYING b.save() buddying = 'accept' Notification.notify_accepted_request(b.buddy_object.user, b.buddy_subject.user) elif buddy_action == 'unbuddy' or buddy_action == 'cancel': Buddies.objects.get( Q(buddy_subject_id=buddy_subject_id, buddy_object_id=buddy_object_id) | Q(buddy_subject_id=buddy_object_id, buddy_object_id=buddy_subject_id) ).delete() buddying = 'delete' else: return HttpResponseBadRequest('Unknown action: {}'.format(buddy_action)) return HttpResponse(buddying)
def user_follow(sender, instance, *args, **kwargs): follow = instance sender = follow.follower following = follow.following notify = Notification(sender=sender, user=following, notification_type=3) notify.save()
def notify_people(request, key, species, obj, users, metadata=None): for user in users: if request and user == request.user: continue n = Notification(key=key, species=species, linked_object=obj, user=user) n.save() if metadata: n.set_metadata(metadata) n.save() try: notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key) except NotificationRestriction.MultipleObjectsReturned: NotificationRestriction.objects.filter(user=user, key=key).delete() notification_restriction, __ = NotificationRestriction.objects.get_or_create(user=user, key=key) notification_restriction_all, __ = NotificationRestriction.objects.get_or_create(user=user, key='') if notification_restriction.autoread or notification_restriction_all.autoread: n.seen = True n.save() if not notification_restriction.no_email and not notification_restriction_all.no_email and Notification.objects.filter(key=key, species=species, object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), user=user, seen=False).count() == 1: NotificationEmail(user=user, notification=n).save()
def like(request): post_id = request.POST.get('post_id', False) customer_id = request.POST.get('customer_id', False) post = Post.objects.get(id=post_id) customer = Customer.objects.get(id=customer_id) like = Like.objects.filter(post=post, customer=customer_id) if like.exists(): like.delete() nlikes = len(Like.objects.filter(post_id=post_id)) data = nlikes notifi2 = Notification.objects.filter(customer_id=customer_id, post_id=post_id, status=2) notifi2.delete() else: like2 = Like() like2.customer = customer like2.post = post like2.save() nlikes = len(Like.objects.filter(post_id=post_id)) data = nlikes notifi = Notification() notifi.customer_id = post.customer.id notifi.createtime = timezone.now() notifi.customer_user = customer notifi.description = customer.fullname + " đã yêu thích bài viết của bạn..." notifi.post = post notifi.status = 2 notifi.save() return HttpResponse(data)
def handle(self, *args, **options): now = timezone.now() pjs = ProfileJob.objects.all() for pj in pjs: date_next = pj.assign_at + timedelta(days=1) exist_history = JobHistory.objects.filter(profilejob=pj).exists() print "FECHA ACTUAL: %s >= F24H:%s, %s, %s " % (now, date_next, (now >= date_next), exist_history) if (date_next <= now) and not exist_history: print "Creando notificacion" if not Notification.objects.filter( obj='ProfileJob', obj_id=pj.id, profile=pj.profile).exists(): notification = Notification( profile=pj.profile, level=u'HIG', type=u'MES', title=u'Trabajo no cumplido por: %s' % (pj.profile), content=u'No se ha realizado el trabajo con estado %s' % (pj.job.state), obj=u'ProfileJob', obj_id=(u'%s' % pj.id), ) notification.save()
def send_notification(self, notification_subscription, type): if Notification.objects.filter( notification_subscription=notification_subscription, type=type).exists(): return None if type == NOTIFICATION_TYPE.ONE_HOUR: msg = f'Raffle {notification_subscription.raffle.name} will start in 1 hour' elif type == NOTIFICATION_TYPE.ONE_MINUTE: msg = f'Raffle {notification_subscription.raffle.name} will start in 1 minute' elif type == NOTIFICATION_TYPE.HAS_STARTED: msg = f'Raffle {notification_subscription.raffle.name} has started' elif type == NOTIFICATION_TYPE.HAS_ENDED: msg = f'Raffle {notification_subscription.raffle.name} has ended' else: return None url = f'https://poap.fun/{notification_subscription.raffle.id}' response = self.send_fcm(notification_subscription.token, msg, url) notification = Notification( notification_subscription=notification_subscription, type=type, response=response) notification.save()
def register_view(request): form = UserRegistrationForm(request.POST or None, request.FILES or None) if request.user.is_authenticated(): return redirect('login_view') if request.method == 'POST': if form.is_valid(): form.save() email = form.cleaned_data['email'] password = form.cleaned_data['password1'] activation_key = signing.dumps({'email': email}) user = User.objects.get(email=email) UserActivation.objects.filter(user=user).delete() new_activation = UserActivation(user=user, activation_key=activation_key, request_time=timezone.now()) new_activation.save() mailing.confirm_email(email, activation_key) notification = Notification(user=user, text='Пожалуйста, активируйте ваш профиль, перейдя по ссылке в письме на вашем почтовом ящике') notification.save() user = auth.authenticate(username=email, password=password) auth.login(request, user) return redirect('index_view') else: messages.warning(request, "Здесь есть неверно заполненные поля!") return render(request, 'reg.html', {'form': form}) return render(request, 'reg.html', {'form': form})
def create(recipients, subject=None, message=None, action=None, notification_type=None, context={}): """Instantiates notifications. Generates a notification subject and message, depending on the notification_type. """ # Pass the action as context to the email templates. context["action"] = action context["coordinator_email"] = coordinator_email # Generate a subject and message based on the notification_type. gen_subject, gen_message = gen_subject_and_message(site_url, notification_type, action, context) # Create the notification. notification = Notification(action=action, type=notification_type, delivered=False, created_date_time=timezone.now(), subject=subject or gen_subject, message=message or gen_message, recipients=recipients) notification.save()
def notify_handler(verb, **kwargs): """ Handler function to create Notification instance upon action signal call. """ kwargs.pop('signal', None) recipient = kwargs.pop('recipient') actor = kwargs.pop('sender') newnotify = Notification( recipient = recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=unicode(verb), public=bool(kwargs.pop('public', True)), description=kwargs.pop('description', None), timestamp=kwargs.pop('timestamp', now()) ) for opt in ('target', 'action_object'): obj = kwargs.pop(opt, None) if not obj is None: setattr(newnotify, '%s_object_id' % opt, obj.pk) setattr(newnotify, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if len(kwargs) and EXTRA_DATA: newnotify.data = kwargs newnotify.save()
def create(self, validated_data): note = Note.objects.create(**validated_data) action_type = 'NOTE ADDED' # contentType = ContentType.objects.get(pk=note.content_type.id) if note.object_type == 'Document': document = Document.objects.get(pk = note.object_id) noteFor = note.object_type + ' ' + document.name slug = slugify(document.subProcess.name) link = slug message = 'Added note for ' + noteFor contentType = ContentType.objects.get(model='document') notification = Notification(message=message,content_type=contentType,object_id=note.object_id,link=link,committee=note.committee,action_type=action_type) notification.save() return note
def notify_user(recipient, actor, verb, **kwargs): """ Handler function to create Notification instance upon action signal call. """ new_notification = Notification( recipient = recipient, actor_content_type=ContentType.objects.get_for_model(actor), actor_object_id=actor.pk, verb=text_type(verb), public=bool(kwargs.pop('public', False)), description=kwargs.pop('description', None), timestamp=kwargs.pop('timestamp', utc_now()), level=kwargs.pop('level', Notification.LEVELS.info), ) for opt in ('target', 'action_object'): obj = kwargs.pop(opt, None) if not obj is None: setattr(new_notification, '%s_object_id' % opt, obj.pk) setattr(new_notification, '%s_content_type' % opt, ContentType.objects.get_for_model(obj)) if len(kwargs) and EXTRA_DATA: new_notification.data = kwargs new_notification.save() return new_notification
def reactionLove(request, id): if not request.user.is_authenticated(): raise Http404 print("this should work !") product = get_object_or_404(Product, id=id) oldReaction = Reaction.objects.filter(user=request.user, product=product) for old in oldReaction: old.delete() reaction = Reaction(user=request.user, product=product, reaction_type='love') reaction.save() if request.user.id != product.table.user.id: notif = Notification(from_user=request.user, to_user=product.table.user, notification_type='love', product=product) notif.save() ret = Reaction.objects.filter(product=product).count() print( "reaction --Love-- added successfully from reactions application...") return HttpResponse(ret)
def likePost(request, post_key): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id post = Posts.objects.get(pk=post_key) if post.likes: if person_id in post.likes['persons']: post.likes['persons'].remove(person_id) isLiked = False else: post.likes['persons'].append(person_id) isLiked = True else: post.likes = dict(persons=[(person_id)]) isLiked = True post.save() # make a notification to send if post.person_id != person_id and isLiked: notification = Notification( noti=0, person_for=post.person_id, person_from=person_id, about=post.id, created=datetime.now().timestamp() ) notification.save() return Response(json.loads('{"action":"success"}'),status=status.HTTP_200_OK)
def notifications(request): if request.method == 'POST': sender_user = request.user traveller_id = request.POST['traveller_id'] receiver = get_object_or_404(Traveller, pk=traveller_id) sender_name = sender_user.first_name + " " + sender_user.last_name receiver_user = get_object_or_404(User, email=receiver.email) reg_date = datetime.datetime.utcnow().replace(tzinfo=utc) #Check if user has made request already if request.user.is_authenticated: current_user = request.user has_requested = Notification.objects.all().filter( receiver_email=receiver_user, sender_email=sender_user, completed=False) if has_requested: messages.error(request, 'You have already made a request to this guide') return redirect('/view_profile/' + traveller_id) else: notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name=sender_name, reg_date=reg_date) notification.save() return redirect('/view_profile/' + traveller_id) return redirect('/view_profile/' + traveller_id)
def reactionWow(request, id): if not request.user.is_authenticated(): raise Http404 product = get_object_or_404(Product, id=id) if (request.user in product.likes.all()): product.likes.remove(request.user) if (request.user in product.smiles.all()): product.smiles.remove(request.user) if (request.user in product.wishes.all()): product.wishes.remove(request.user) if request.user.id != product.store.user.id: notif = Notification(from_user=request.user, to_user=product.store.user, notification_type='W', product=product) notif.save() product.wishes.add(request.user) product.save() print("reaction --Wow-- added successfully from reactions application...") return HttpResponse(product.likes.count() + product.smiles.count() + product.wishes.count())
def notifications_index(request): # get the page page = int(request.GET.get('page', 1)) # Get the total pages (rounding up, ex: 1.2 pages means 2 pages) total_pages = int(math.ceil(float(Notification.count(request.user)) / NOTIFICATIONS_PER_PAGE)) # If the page doesn't exists then 404 if page > total_pages and total_pages > 0: raise Http404 # Get the notifications offset = NOTIFICATIONS_PER_PAGE * (page - 1) limit = offset + NOTIFICATIONS_PER_PAGE notifications = Notification.find(request.user, offset, limit-1) context = { "total_pages": total_pages, "actual_page": page, "notifications": notifications } return render_to_response('notifications/notifications-index.html', context, context_instance=RequestContext(request))
def download_pdf(request): """ request download of PDF file - notify student of download """ results = {'success':False} if(request.method == u'POST'): try: POST = request.POST application = Application.objects.get(id=POST['application_id']) documents = application.documents.all() results['pdfs'] = [doc.url for doc in documents] results['success'] = True # notify user that application has been downloaded by company try: new_notification = Notification(user=application.user, company=application.company, receiver=1, notification=2) new_notification.save() except Exception, e: print e raise e except: pass json_results = simplejson.dumps(results) return HttpResponse(json_results, mimetype='application/json')
def comment_notify(self, comment_id, type, parent_id): try: c = Comment.objects.get(pk=comment_id) if type == 1: p = Answer.objects.get(pk=parent_id) owner_id = p.writer.user.id uf = UserFigures.objects.get(user_id=c.writer.id) uf.comments += 1 uf.save() else: p = Comment.objects.get(pk=parent_id) owner_id = p.writer.id uf = UserFigures.objects.get(user_id=c.writer.id) uf.comments += 1 uf.save() n = Notification(actor_id=c.writer.id, owner_id=owner_id, note_type=8, notification_id=parent_id) n.save() return NotificationSerializer(n).data except Exception as e: self.retry(exc=e, countdown=60)
class NotificationTests(TestCase): def setUp(self): settings.NOTIFICATION_OPTIONS = dict( TEST_NOTIFICATION=dict( caller='notification', template='notification_test_template.html', subject='Notification test template' ) ) self.package = dict( caller='notifications', notification_type='TEST_NOTIFICATION', recipients=['dummy_mail@dummy_host.com', ], context=dict( dummy_data='dummy_data' ) ) # noinspection PyUnresolvedReferences def tearDown(self): del settings.NOTIFICATION_OPTIONS # noinspection PyUnresolvedReferences def test_notification_options(self): self.notification = Notification(**self.package) self.notification.send() self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Notification test template') self.assertTrue('dummy_data' in mail.outbox[0].body)
def congratz_after_30days(pk): # user = User.objects.get(pk=pk) notification_text = 'Congratulations being 30 days in this shitty site...Stay on!' notification = Notification(user_notified_id=pk, notification_date=timezone.now(), text=notification_text) notification.save() return notification_text
def create_media_promotion_notification(media_account, _type, child_media_name=""): content_tmpl = MEDIA_PROMOTION_BANNED_NOTIFICATION_MAPPING[_type] content = content_tmpl.format(account_name=media_account.title, child_account_name=child_media_name) Notification.create_notification(str(media_account.id), TYPE_MEDIA_PROMOTION, content)
def slava_ukr_notification(): users = User.objects.all() for user in users: notification = Notification(user_notified=user, notification_date=timezone.now(), text='СЛАВА УКРАЇНІ!!!') notification.save() return 'PERIODIC TASK!'
def follow(self, user): self.followed_users.add(user) self.add_redis_set.delay('followed_users', user.id) self.add_feeds_from_user.delay(user) user.add_redis_set.delay('followers', self.id) if user.notify_new_friend: note = Notification(sender=self, recipient=user, note_type=0, subject_id=self.id) note.save()
def notify_comment(sender, instance, **kwargs): comment_notification = Notification(level=Notification.INFO, recipient=instance.project.author, verb="commented on", actor=instance.commenter, target=instance.project) comment_notification.save() pass
def save(self, *args, **kwargs): super(PostLike, self).save(*args, **kwargs) self.post.increment_social_interaction('likes_count', to_save=True) tokens_for_parent_post_creator_qs = PushToken.objects.filter( user=self.post.created_by, push_group=IONIC_PUSH_GROUP, is_active=True).values_list('token').exclude( user=self.created_by_id) tokens_for_parent_post_creator = list() for token in tokens_for_parent_post_creator_qs: tokens_for_parent_post_creator.append(token[0]) if self.post.parent_post_id: payload = { "post_id": str(self.post.parent_post_id), "comment_id": str(self.post.id), "image": self.created_by.get_profile_image_cache_url(), "created_by_id": str(self.created_by_id), "type": NOTIFICATION_TYPES.NEW_LIKE } else: payload = { "post_id": str(self.post_id), "image": self.created_by.get_profile_image_cache_url(), "created_by_id": str(self.created_by_id), "type": NOTIFICATION_TYPES.NEW_LIKE } title = "%s likes your post" % self.created_by message = "Click here to view it" notif = Notification(to_user=self.post.created_by, from_user=self.created_by, created_on=timezone.datetime.now(), title=title, message=message, payload=payload) notif.save() if len(tokens_for_parent_post_creator) > 0: r = PushNotificationRequest() r.create({ "tokens": tokens_for_parent_post_creator, "notification": { "message": message, "title": title, "payload": payload, "ios": { "badge": "1", "sound": "default", "priority": 10 }, "android": { "sound": "default", "priority": "high" } }, "profile": IONIC_PUSH_GROUP })
def launch(request, id): e = get_equipment(request, id) if e is None: raise ValueError('not found') e.launched = True e.requesting = False e.save() Notification.create(e.provider, request.params.get('notification')) return JsonResponse({})
def render(self, context): try: n = Notification() context[self.var_name] = n.is_notified(self.notification_name, context['user']) except: pass return ""
def form_valid(self, form): user = form.save() login(self.request, user) admin = User.objects.filter(user_type="ADMIN")[0] notification = Notification(content='New Company: ' + user.name, url=f'/profile/{user.id}') notification.save() notification.users.add(admin) return redirect('my_profile')
def user_subscribed(sender, instance, *args, **kwargs): subscription = instance sender = subscription.subscriber subscribing = subscription.subscribed notify = Notification(sender=sender, user=subscribing, notification_type=3) notify.save()
def notify_of_new_follower(self, user_following_id): try: uf = UserFollowings.objects.get(pk=user_following_id) n = Notification(actor_id=uf.user_id, owner_id=uf.is_following_id, note_type=13, notification_id=user_following_id) n.save() except Exception as e: self.retry(exc=e, countdown=60)
def create(self, validated_data): try: user = self.perform_create(validated_data) except IntegrityError: self.fail('cannot_create_user') Notification().greeting(user) Notification().new_user(user, validated_data['password']) return user
def amo_notification(instance, **kw): """ Given an error see if we need to send a notification """ log('Firing signal: default_notification') user = User.objects.get(email__in=amo_users) if instance.domain in amo_domains: notification = Notification() notification.notifier = instance notification.save() notification.user.add(user)
def testBasic(self): c = Client() assert not Error.all().count() c.post(reverse("error-post"), test_data) assert test_data["priority"] < 5, test_data["priority"] assert Error.all().count() == 1 assert Notification.all().count() == 1 c.post(reverse("error-post"), test_data) assert test_data["priority"] < 5, test_data["priority"] assert Error.all().count() == 2 assert Notification.all().count() == 2
def custom_notification(by,body,subject,superusers = True): if superusers: users = User.objects.filter(is_superuser=True) for user in users: context = {'user': user.name, 'body': body, 'subject': subject} emailit.api.send_mail(user.email, context, 'notification/emails/notification_email', from_email=user.email) notif = Notification(actor=by, recipient=user, verb=subject, description=body, emailed=True) notif.save() return True
def post(self, request): email = request.POST['email'] password = request.POST['password'] if not validate_email_format(email): context = { 'signup_failed': True, 'message': 'Please, enter a valid email!' } return render(request, self.template_name, context=context) if not check_password_strength(password): context = { 'signup_failed': True, 'message': 'Password length must be at least 6!' } return render(request, self.template_name, context=context) try: with transaction.atomic(): user = User.objects.create_user(email, email, password) auth.login(request, user) notification = Notification(message='Account created', icon=Notification.PLUS, click_view='frontend:profile', user=user) notification.save() return redirect('frontend:dashboard') except IntegrityError as e: user = auth.authenticate(request, username=email, password=password) if user is not None: auth.login(request, user) return redirect('frontend:dashboard') context = { 'signup_failed': True, 'message': 'Do you have an account with the same email? Login instead!' } return render(request, self.template_name, context=context) except Exception as e: context = { 'signup_failed': True, 'message': 'Ops! Our server couldn\'nt create a new account. Try again later!' } return render(request, self.template_name, context=context)
def user_comment_post(sender, instance, *args, **kwargs): comment = instance post = comment.post text_preview = strip_tags(comment.body[:90]) sender = comment.name notify = Notification(post=post, sender=sender, user=post.author, text_preview=text_preview, notification_type=2) notify.save()
def default_notification(instance, **kw): """ Given an error see if we need to send a notification """ log("Firing signal: default_notification") # todo, this will be changed to lookup a user profile as per # http://github.com/andymckay/arecibo/issues/issue/4 if instance.priority >= 5: return notification = Notification() notification.error = instance notification.user = [ str(u.key()) for u in approved_users() ] notification.save()
def create(cls, *args, **kwargs): task = cls(*args, **kwargs) task.save() from misc.models import Search # bidirectional import Notification.create( users=task.course.students, heading='New task created', text='{} created in {}'.format(task.name, task.course.name), url=reverse('viewtask', args=(task.id,)) ) Search.add_words(kwargs['name'], task.id, Task) return task
def page(request): if request.POST: if "cancel" in request.POST: return HttpResponseRedirect(reverse_lazy('index')) else: form = NewUserModel(request.POST) if form.is_valid(): name = form.cleaned_data['name'] surname = form.cleaned_data['surname'] email = form.cleaned_email() # TODO: all email on lower pas2 = form.cleaned_data['password2'] tel = form.cleaned_data['phone'] new_user = UserModel( email=email.lower(), is_active=True, name=name, surname=surname, phone=tel, messages=1) new_user.set_password(pas2) # TODO: play with commit False. # If captcha fails creates user anyways. try: taken = UserModel.objects.get(email=email.lower()) except UserModel.DoesNotExist: new_user.save() new_notification = Notification( user=new_user, notified=False, text=u"""Welcome to the website! You have an available account.""") new_notification.save() messages.success(request, 'New user created correctly.') # TODO: authenticate user otherwise next will always go to index if request.user.is_anonymous: return HttpResponseRedirect(reverse_lazy('index')) else: if request.user.is_admin: return HttpResponseRedirect(reverse_lazy('users_list')) else: return HttpResponseRedirect(reverse_lazy('panel')) else: return render( request, 'clients/user_create.html', {'form': form} ) else: form = NewUserModel() return render(request, 'clients/user_create.html', {'form': form})
def create(cls, task, user, bonus): sub = cls.objects.filter(user=user, task=task).first() if sub is None: sub = AssignSubmission(user=user, task=task, criteria=None, data=bonus['data'], mark=0) else: sub.data = bonus['data'] sub.save() Notification.create( users=[task.course.teacher], heading='Task handed in', text='{} handed in for {}'.format(user.get_full_name(), task.name), url=reverse('viewtask', args=(task.id,)) ) return sub.on_submit(bonus)
def approve_user(request, approve_key): key = str(base64.b64decode(approve_key)) user = get_object_or_404(User, pk = int(key.split("_")[0])) group = get_object_or_404(GroupProfile, pk = int(key.split("_")[1])) try: user.groups.add(group.group) GroupPermission(group=group.group, user=user, permission_type=2).save() messages.add_message(request, messages.INFO, "Your approval is successful!") notification = Notification(text = \ "Manager of the group %s has just approved you to join.\n Click on the following link to go to that group: http://%s/group/%s/ \n \ Have fun!" % (group.group.name, get_domain(), group.slug), entity=group, recipient = user) notification.save() except: pass return HttpResponseRedirect('/')
def handle(self, *args, **options): today = date.today() to_notify = EmptyQuerySet() # Iterate over sales that are in effect for sale in Sale.objects.filter(start__lte=today, end__gte=today): # Find subscriptions that require the products on sale subscriptions = Subscription.objects.filter(product__in=sale.products.all()) # Remove subscriptions that have been notified subscriptions = subscriptions.exclude(notifications__sale=sale) to_notify |= subscriptions # Collect the subscriptions by user user_subs = defaultdict(list) for sub in to_notify: user_subs[sub.user].append(sub) from_email = getattr(settings, 'DEFAULT_FROM_EMAIL', '*****@*****.**') # Build the emails for user, subs in user_subs.iteritems(): to_email = user.email context = {'user': user, 'subscriptions': subs} subject = render_to_string('notifications/sale_subject.txt', context).replace('\n', '').strip() context['subject'] = subject text_content = render_to_string('notifications/sale_body.txt', context) html_content = render_to_string('notifications/sale_body.html', context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, 'text/html') msg.send() # Will raise exceptions on failure # Mark all active sales for this product as notified for sub in subs: for sale in sub.product.active_sales.all(): notified = Notification() notified.sale = sale notified.subscription = sub notified.save()
def test_achievement_notification_get_all_asc(self): #with three we have enought to test achieves = Achievement.objects.all() user = User.objects.get(id=1) r = get_redis_connection() a_len = len(achieves) for i in achieves: notif = AchievementNotification(achievement=i, user=user) time.sleep(1) if random.randrange(100) % 2: key = Notification.STORE_KEY_UNREAD_FORMAT.format(user.id) else: key = Notification.STORE_KEY_READ_FORMAT.format(user.id) r.zadd(key, notif.date, notif.to_json()) # Get notifications res = Notification.all(user, desc=False) self.assertEquals(a_len, len(res)) for i in range(len(res)): before = achieves[i] after = res[i] self.assertEquals(before.id, after.achievement_id)
def test_achievement_notification_get_range(self): achieves = Achievement.objects.all()[:5] notifs = [] user = User.objects.get(id=1) r = get_redis_connection() for i in achieves: notif = AchievementNotification(achievement=i, user=user) time.sleep(1) if random.randrange(100) % 2: key = Notification.STORE_KEY_UNREAD_FORMAT.format(user.id) else: key = Notification.STORE_KEY_READ_FORMAT.format(user.id) r.zadd(key, notif.date, notif.to_json()) notifs.append(notif) achieves = achieves[2:5] # 2, 3 and 4 only a_len = len(achieves) # Get notifications res = Notification.time_range(user, lowerbound=notifs[2].date, upperbound=notifs[4].date, desc=False, mode=2) self.assertEquals(a_len, len(res)) for i in range(len(res)): before = achieves[i] after = res[i] self.assertEquals(before.id, after.achievement_id)
def notifications_send(request): log("Firing cron: notifications_send") notifications = Notification.all().filter("type = ", "Error").filter("tried = ", False) # batch up the notifications for the user holders = {} for notif in notifications: for user in notif.user_list(): key = str(user.key()) if key not in holders: holder = Holder() holder.user = user holders[key] = holder holders[key].objs.append(notif.notifier()) holders[key].notifs.append(notif) for user_id, holder in holders.items(): try: send_error_email(holder) for notification in holder.notifs: notification.tried = True notification.completed = True notification.save() except: info = sys.exc_info() data = "%s, %s" % (info[0], info[1]) for notification in holder.notifs: notification.tried = True notification.completed = True notification.error_msg = data notification.save() return render_plain("Cron job completed")
def test_achievement_notification_find_all_with_limits(self): achieves = Achievement.objects.all()[:5] user = User.objects.get(id=1) r = get_redis_connection() for i in achieves: notif = AchievementNotification(achievement=i, user=user) time.sleep(1) if random.randrange(100) % 2: key = Notification.STORE_KEY_UNREAD_FORMAT.format(user.id) else: key = Notification.STORE_KEY_READ_FORMAT.format(user.id) r.zadd(key, notif.date, notif.to_json()) # Get notifications res = Notification.find(user, offset=2, limit=3, desc=False, mode=2) achieves = achieves[2:4] # 2 and 3 only a_len = len(achieves) self.assertEquals(a_len, len(res)) for i in range(len(res)): before = achieves[i] after = res[i] self.assertEquals(before.id, after.achievement_id)
def default_notification(instance, **kw): """ Given an error see if we need to send a notification """ log("Firing signal: default_notification") if instance.priority >= 5: return users = approved_users() if not users.count(): return notification = Notification() notification.notifier = instance notification.save() for user in users: notification.user.add(user)
def user_dashboard(request): # Notifications # Rest one beacause is the upper limit inclusive notifs = Notification.find(user=request.user, limit=NOTIFS_IN_DASHBOARD-1) # Stats total_links = UserLink.objects.filter(user=request.user).count() total_achieves = UserAchievement.objects.filter(user=request.user).count() # Latest links links_aux = UserLink.objects.filter( user=request.user).order_by('-id')[:LINKS_IN_DASHBOARD] links = [ShortLink.find(token=i.token) for i in links_aux] # Latest achievements achievements = UserAchievement.objects.filter( user=request.user).order_by('-id')[:ACHIEV_IN_DASHBOARD] context = { "notifications": notifs, "links": links, "stats": { "Total Links": total_links, "Achievements": total_achieves, "Level": request.user.profile.level.level_number, "Points": request.user.profile.points, }, "achievements": achievements } return render_to_response('userprofile/dashboard.html', context, context_instance=RequestContext(request))
def get_notifications(user, type): notifications = Notification.unread_notifications(user, type) my_notifications = [] for notification in notifications: plain_notification = notification.plain() my_notifications.append(plain_notification) return PlainNotificationSerializer(my_notifications, many=True)
def notifications_cleanup(request): log("Firing cron: notifications_cleanup") expired = datetime.today() - timedelta(days=7) queryset = Notification.all().filter("tried = ", True).filter("timestamp < ", expired) for notification in queryset: notification.delete() return render_plain("Cron job completed")
def create_notification(type, source_id, from_user, for_user, message=None): notification = Notification(type=type, source_id=source_id, from_user=from_user, for_user=for_user, message=message, seen=False, action_taken=False) notification.save() extra = { "id": notification.id, "type": notification.type } app_key = settings.UA['app_key'] master_secret = settings.UA['master_secret'] logger.debug("app_key") logger.debug(app_key) logger.debug("master_secret") logger.debug(master_secret) airship = ua.Airship(app_key, master_secret) devices = for_user.user_devices.all() for device in devices: logger.debug("push_token") logger.debug(device.push_token) if device.push_token: push = airship.create_push() if device.device_type == 'iOS': push.audience = ua.device_token(device.push_token) elif device.device_type == 'Android': push.audience = ua.apid(device.push_token) push.notification = ua.notification(ios=ua.ios(alert=message, badge="+1", extra=extra), android=ua.android(alert=message, extra=extra)) push.device_types = ua.device_types('ios', 'android', ) logger.debug("push response") logger.debug(push.send()) return notification
def testNoNotification(self): c = Client() assert not Error.all().count() data = test_data.copy() data["priority"] = 6 c.post(reverse("error-post"), data) assert data["priority"] > 5, data["priority"] assert Error.all().count() == 1 assert Notification.all().count() == 0
def update_comment_list(sender, instance, created, **kwargs): if created: if instance.beat.creator.notify_comment: note = Notification() note.sender = instance.creator note.recipient = instance.beat.creator note.note_type = 1 note.content = instance.text[:20] note.subject_id = instance.beat_id note.save() redis_push_list('Beat', instance.beat_id, 'comments', instance.id)