def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent = 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads(str(queued_batch.pickled_data).decode("base64")) batch_sent = 0 for user, label, extra_context, on_site, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice to %s" % user) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site, sender) sent += 1 batch_sent += 1 except: # get the exception _, e, _ = sys.exc_info() # log it as critical logging.critical("an exception occurred: %r" % e) # update the queued_batch, removing notices that had been sucessfully sent queued_batch.pickled_data = pickle.dumps(notices[batch_sent:]).encode("base64") queued_batch.save() queued_batch.delete() batches += 1 except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[%s emit_notices] %r" % (current_site.name, e) message = "%s" % ("\n".join(traceback.format_exception(*sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent,)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def image_detail(request, id, template_name="loupe/image_detail.html"): """ Displays the image to be discussed by the project members expects an id for the image and the user has access to the parent project """ if not request.user.is_staff: image = get_object_or_404(Image, pk=id, corkboard__project__members=request.user) else: image = get_object_or_404(Image, pk=id) notes = Note.objects.filter(image=image) notes_count = notes.count() form = NoteForm() if request.method == "POST": form = NoteForm(request.user, request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.image = image note.save() if notification: notification.send_now( image.corkboard.project.members.all(), "corkboard_new_image_note", {"user": request.user, "image_url": image.get_absolute_url, "image": image}, ) request.user.message_set.create(message=_("Successfully attached note to image '%s'") % image.title) return render_to_response( template_name, {"image": image, "notes": notes, "notes_count": notes_count, "form": form}, context_instance=RequestContext(request), )
def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(NOTIFICATION_LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent = 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads( str(queued_batch.pickled_data).decode("base64")) for user, label, extra_context, on_site in notices: user = User.objects.get(pk=user) logging.info("emitting notice to %s" % user) # call this once per user to be atomic and allow for # logging to accurately show how long each takes. notification.send_now([user], label, extra_context, on_site) sent += 1 queued_batch.delete() batches += 1 except: # get the exception exc_class, e, t = sys.exc_info() # email people if NOTIFICATION_USE_SITE: name = Site.objects.get_current().name elif NOTIFICATION_DEFAULT_SITE_NAME: name = NOTIFICATION_DEFAULT_SITE_NAME else: # don't display None, display just a space name = "" subject = "[%s emit_notices] %r" % (name, e) message = "%s" % ("\n".join( traceback.format_exception(*sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent,)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def expiration_notification(sender, **kwargs): """ FIXME: Migrate it (txcron) to work with the String Level. """ logger.debug("lock-addon: Sending expiration notifications...") if not settings.ENABLE_NOTICES: logger.debug("lock-addon: ENABLE_NOTICES is not enabled") return current_site = Site.objects.get_current() locks = Lock.objects.expiring() nt = 'project_resource_language_lock_expiring' for lock in locks: context = { 'resource': lock.rlstats.resource, 'language': lock.rlstats.language, 'project': lock.rlstats.resource.project, 'user': lock.owner, 'expires': lock.expires, 'current_site': current_site } logger.debug("lock-addon: Sending notification about lock: %s" % lock) notification.send_now([ lock.owner, ], nt, context) lock.notified = True lock.save()
def register(request): invite = request.session['profile-invite'] if request.method == 'POST': userForm = forms.UserForm(request.POST, prefix='user') profileForm = ProfileForm(request.POST, prefix='profile') else: userForm = forms.UserForm(prefix='user') profileForm = ProfileForm(prefix='profile') if userForm.is_valid() and profileForm.is_valid(): oldUser = None try: oldUser = User.objects.get(username__exact=userForm.cleaned_data['username']) except ObjectDoesNotExist, e: pass if not oldUser: user = User.objects.create_user(userForm.cleaned_data['username'], userForm.cleaned_data['email'], userForm.cleaned_data['password']) user.save() invite.claimer = user invite.save() profile = user.minecraftprofile profile.mc_username = profileForm.cleaned_data['mc_username'] profile.save() user = authenticate(username=userForm.cleaned_data['username'], password=userForm.cleaned_data['password']) notification.send_now([invite.creator], "invite_accepted", {"new_user": user}) login(request, user) del request.session['profile-invite'] return HttpResponseRedirect("/")
def notify_expired_accounts(): expired_accounts = Account.objects.filter(status='EXPIRED') for account in expired_accounts: notification.send_now([account.user], "account_expired", { 'user': account.user, 'site': Site.objects.get_current() }, True)
def emit_batch(queued_batch): sent = 0 try: notices = pickle.loads(str(queued_batch.pickled_data).decode("base64")) for user, label, extra_context, on_site, sender, kwargs in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice %s to %s" % (label, user)) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site, sender, **kwargs) except User.DoesNotExist: # Ignore deleted users, just warn about them logging.warning("not emitting notice %s to user %s since it " "does not exist" % (label, user)) sent += 1 queued_batch.delete() except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[%s emit_notices] %r" % (current_site.name, e) message = "%s" % ("\n".join(traceback.format_exception( *sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) return sent
def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent = 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): data = str(queued_batch.pickled_data).decode("base64") notices = pickle.loads(data) for user, label, extra_context, on_site, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice %s to %s" % (label, user)) # call this once per user to be atomic and allow for # logging to accurately show how long each takes. notification.send_now([user], label, extra_context, on_site, sender) except User.DoesNotExist: # Ignore deleted users, just warn about them logging.warning("not emitting notice %s to user %s" " since it does not exist" % (label, user)) sent += 1 queued_batch.delete() batches += 1 except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[%s emit_notices] %r" % (current_site.name, e) message = "%s" % ("\n".join( traceback.format_exception(*sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent,)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent = 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads(str(queued_batch.pickled_data).decode("base64")) try: for user, label, extra_context, on_site, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice %s to %s" % (label, user)) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site, sender) except User.DoesNotExist: # Ignore deleted users, just warn about them logging.warning("not emitting notice %s to user %s since it does not exist" % (label, user)) sent += 1 except : #if we sent half the batch, we don't want to resend notices to the first half next #time we run it, so just throw away this (apparantly faulty) queued_batch queued_batch.delete() raise queued_batch.delete() batches += 1 except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[%s emit_notices] %r" % (current_site.name, e) message = "%s" % ("\n".join(traceback.format_exception(*sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent,)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def notify_expiring_accounts(): expiring_accounts = Account.objects.filter(status='EXPIRING', user__isnull=False) for account in expiring_accounts: notification.send_now([account.user], "account_expiring", { 'user': account.user, 'site': Site.objects.get_current() }, True)
def send_all(): lock = FileLock('send_notices') logging.debug('acquiring lock...') try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug('lock already in place. quitting.') return except LockTimeout: logging.debug('waiting for the lock timed out. quitting.') return logging.debug('acquired.') batches, sent = 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads( base64.b64decode(queued_batch.pickled_data)) for user, label, extra_context, on_site in notices: user = User.objects.get(pk=user) # FrankU: commented, because not all users get e-mailed # and to supress useless logging # logging.info('emitting notice to %s' % user) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site) sent += 1 queued_batch.delete() batches += 1 except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = '[%s emit_notices] %r' % (current_site.name, e) message = '%s' % ('\n'.join( traceback.format_exception(*sys.exc_info())), ) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical('an exception occurred: %r' % e) finally: logging.debug('releasing lock...') lock.release() logging.debug('released.') logging.info('') logging.info('%s batches, %s sent' % ( batches, sent, )) logging.info('done in %.2f seconds' % (time.time() - start_time))
def index(request): if request.method == 'POST': form = forms.DonationForm(request.POST, prefix='base') stripeForm = forms.StripeForm(request.POST, prefix='stripe') else: form = forms.DonationForm(prefix='base') stripeForm = forms.StripeForm(prefix='stripe') if form.is_valid(): if int(form.cleaned_data['method']) == forms.DonationForm.METHOD_DWOLLA: data = {} order = {} item = {} item['Description'] = "Caminus Donation" item['Name'] = "Caminus Donation" item['Price'] = str(form.cleaned_data['quantity']) item['Quantity'] = 1 order['OrderItems'] = [item,] order['Test'] = True order['Tax'] = 0.00 order['Total'] = str(form.cleaned_data['quantity']) order['DestinationId'] = settings.DWOLLA_API_ID data['PurchaseOrder'] = order data['Key'] = settings.DWOLLA_API_KEY data['Secret'] = settings.DWOLLA_API_SECRET data['Callback'] = 'http://camin.us%s'%reverse('donate.views.dwollaCallback') donation = models.Donation.objects.create(quantity=form.cleaned_data['quantity'], user=request.user) order['OrderId'] = donation.id data['Redirect'] = 'http://camin.us%s'%reverse('donate.views.thanks', kwargs={'donation':donation.id}) req = urllib2.Request("https://www.dwolla.com/payment/request", data=json.dumps(data), headers={'Content-Type': 'application/json'}) response = json.load(urllib2.urlopen(req)) return HttpResponseRedirect("https://www.dwolla.com/payment/checkout/%s"%(response['CheckoutId'])) elif stripeForm.is_valid(): stripe.api_key = settings.STRIPE_KEY cardData = {} cardData['number'] = stripeForm.cleaned_data['card'] cardData['exp_month'] = stripeForm.cleaned_data['month'] cardData['exp_year'] = stripeForm.cleaned_data['year'] cardData['cvc'] = stripeForm.cleaned_data['cvc'] try: charge = stripe.Charge.create( amount = str(form.cleaned_data['quantity']*100), currency = 'usd', card = cardData, description = 'Caminus Donation from %s'%(request.user.email) ) except stripe.CardError, e: messages.error(request, "There was an error while processing your card: %s"%(e.message)) return render_to_response('donate/index.html', {'form': form, 'stripeForm': stripeForm}, context_instance = RequestContext(request)) donation = models.Donation.objects.create(quantity=form.cleaned_data['quantity'], user=request.user) donation.status = models.Donation.STATUS_PAID donation.transactionId = charge.id donation.save() acct = donation.user.minecraftprofile.currencyaccount acct.balance = F('balance')+(donation.quantity*2000) acct.save() notification.send_now([donation.user], "donation_paid", {"donation":donation, "credit":donation.quantity*2000}) return HttpResponseRedirect('http://camin.us%s'%reverse('donate.views.thanks', kwargs={'donation':donation.id}))
def notify_new_letter(sender, instance, created, **kw): if notification and isinstance(instance, Letter) and created: user = [instance.recipient,] game = instance.recipient_player.game extra_context = {'game': game, 'letter': instance, 'STATIC_URL': settings.STATIC_URL,} if game.fast: notification.send_now(user, "condottieri_messages_received", extra_context) else: notification.send(user, "condottieri_messages_received", extra_context)
def dwollaCallback(request): if request.method =='POST': data = json.loads(request.raw_post_data) donation = models.Donation.objects.get(id=data['OrderId']) donation.status = models.Donation.STATUS_PAID donation.transactionId = data['TransactionId'] donation.save() acct = donation.user.minecraftprofile.currencyaccount acct.balance = F('balance')+(donation.quantity*2000) acct.save() notification.send_now([donation.user], "donation_paid", {"donation":donation, "credit":donation.quantity*2000}) return HttpResponse(status=204)
def notify_unclaimed_gifts(): unclaimed = Gift.objects.filter(used=None) for gift in unclaimed: """ send notice every 7 days """ unclaimed_duration = (now() - gift.acq.created).days if unclaimed_duration > 0 and unclaimed_duration % 7 == 0: # first notice in 7 days notification.send_now([gift.acq.user], "purchase_gift_waiting", {'gift': gift}, True) notification.send_now([gift.giver], "purchase_notgot_gift", {'gift': gift}, True)
def report_new_ebooks(created=None): #created= creation date if created: period = (created, created + timedelta(days=1)) else: period = (date_today() - timedelta(days=1), date_today()) works = models.Work.objects.filter( editions__ebooks__created__range=period).distinct() for work in works: # only notify if a new ebooks are active, don't notify person if the book was just wished # ebooks() only returns active ebooks for ebook in work.ebooks().filter(created__range=period): notification.send_now(work.wished_by(excluding=period), "wishlist_unglued_book_released", {'work': work}, True) break
def main(*args, **options): help_msg = """Send a test notification to a specified user.\nUsage: python manage.py test_notification <username>""" if len(args) == 1: username = args[0] else: username = '******' print "Using default recipient, %s" % username try: u = User.objects.get(username=username) except User.DoesNotExist: sys.exit("User, %s, does not exist" % username) print "Sending test notification to %s ..." % username a = Article.objects.get(doi='pone.0012345') n.send_now([u], 'new_urgent_web_correction', {"article": a})
def _send_batch_part(users, label, extra_context, on_site, sender): """Sends part of queued batch""" sent = {} for user in users: # The instance of QuerySet also can be pickled, # so, ckecks the instance of user. if not isinstance(user, User): try: logger.info("loading user {0}".format(user)) user = User.objects.get(pk=user) except User.DoesNotExist: # Ignore deleted users, just warn about them logger.warning("not emitting notice {0} to user {1} since it does not exist".format(label, user)) continue logger.info("emitting notice {0} to {1}".format(label, user)) # call this once per user to be atomic and allow for logger to # accurately show how long each takes. try: result = notification.send_now([user], label, extra_context, on_site, sender) except ObjectDoesNotExist as e: logger.warning("Can't to emit notice {0} to user {1} since {2}".format(label, user, e)) else: for k, v in result.items(): sent.setdefault(k, 0) sent[k] += v return sent
def send_all(*args): lock = acquire_lock(*args) batches, sent, sent_actual = 0, 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads( base64.b64decode(queued_batch.pickled_data)) for user, label, extra_context, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice {} to {}".format( label, user)) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. if notification.send_now([user], label, extra_context, sender): sent_actual += 1 except User.DoesNotExist: # Ignore deleted users, just warn about them logging.warning( "not emitting notice {} to user {} since it does not exist" .format(label, user)) sent += 1 queued_batch.delete() batches += 1 emitted_notices.send(sender=NoticeQueueBatch, batches=batches, sent=sent, sent_actual=sent_actual, run_time="%.2f seconds" % (time.time() - start_time)) except Exception: # pylint: disable-msg=W0703 # get the exception _, e, _ = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[{} emit_notices] {}".format(current_site.name, e) message = "\n".join( traceback.format_exception( *sys.exc_info()) # pylint: disable-msg=W0142 ) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: {}".format(e)) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("{} batches, {} sent".format( batches, sent, )) logging.info("done in {:.2f} seconds".format(time.time() - start_time))
def corkboard_detail(request, slug, template_name="loupe/corkboard_detail.html"): """ Displays the corkboard and all it's associated images to the user expects a slug and expects the user has access to the parent project """ if not request.user.is_staff: corkboard = get_object_or_404(Corkboard, slug=slug, project__members=request.user) else: corkboard = get_object_or_404(Corkboard, slug=slug) images = Image.objects.filter(corkboard=corkboard) form = ImageForm() if request.method == "POST": form = ImageForm(request.user, request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) image.user = request.user image.corkboard = corkboard image.save() if notification: notification.send_now( corkboard.project.members.all(), "corkboard_new_image", { "user": request.user, "corkboard": corkboard, "image_url": image.get_absolute_url, "corkboard_url": corkboard.get_absolute_url }) request.user.message_set.create( message=_("Successfully uploaded image '%s'") % image.title) return render_to_response(template_name, { "corkboard": corkboard, "form": form, "images": images, }, context_instance=RequestContext(request))
def generate(): print "Sending 10% of the stored notifications" num = NoticeQueueBatch.objects.count() users = dict([(str(u.id), u) for u in User.objects.all()]) print "Unpickling batch data" batches = map( lambda data: pickle.loads(data.decode("base64"))[0], NoticeQueueBatch.objects.order_by('?').values_list('pickled_data', flat=True)[:num / 10] ) print "Unpickled batch data" NoticeQueueBatch.objects.all().delete() i = 0 for i, args in enumerate(batches): arg_list = list(args) arg_list[0] = [users[str(arg_list[0])]] send_now(*arg_list) print "%d notifications sent" % (i,)
def generate(): print "Sending 10% of the stored notifications" num = NoticeQueueBatch.objects.count() users = dict([(str(u.id), u) for u in User.objects.all()]) print "Unpickling batch data" batches = map( lambda data: pickle.loads(data.decode("base64"))[0], NoticeQueueBatch.objects.order_by('?').values_list('pickled_data', flat=True)[:num / 10]) print "Unpickled batch data" NoticeQueueBatch.objects.all().delete() i = 0 for i, args in enumerate(batches): arg_list = list(args) arg_list[0] = [users[str(arg_list[0])]] send_now(*arg_list) print "%d notifications sent" % (i, )
def project_detail(request, slug, template_name="loupe/project_detail.html"): """ Displays the corkboards for the given porject 'slug' to the user expects a slug and expects the user has access to the parent project """ if not request.user.is_staff: project = get_object_or_404(Project, slug=slug, members=request.user) else: project = get_object_or_404(Project, slug=slug) corkboards = Corkboard.objects.filter(project=project) form = CorkboardForm() if request.method == "POST": form = CorkboardForm(request.user, request.POST) if form.is_valid(): corkboard = form.save(commit=False) corkboard.user = request.user corkboard.project = project corkboard.save() request.user.message_set.create( message=_("Successfully created corkboard '%s'") % corkboard.title) if notification: notification.send_now( project.members.all(), "corkboard_new_corkboard", { "user": request.user, "corkboard": corkboard, "corkboard_url": corkboard.get_absolute_url }) return HttpResponseRedirect( reverse('corkboard_detail', args=(corkboard.slug, ))) return render_to_response(template_name, { "project": project, "form": form, "corkboards": corkboards, }, context_instance=RequestContext(request))
def corkboard_detail(request, slug, template_name="loupe/corkboard_detail.html"): """ Displays the corkboard and all it's associated images to the user expects a slug and expects the user has access to the parent project """ if not request.user.is_staff: corkboard = get_object_or_404(Corkboard, slug=slug, project__members=request.user) else: corkboard = get_object_or_404(Corkboard, slug=slug) images = Image.objects.filter(corkboard=corkboard) form = ImageForm() if request.method == "POST": form = ImageForm(request.user, request.POST, request.FILES) if form.is_valid(): image = form.save(commit=False) image.user = request.user image.corkboard = corkboard image.save() if notification: notification.send_now( corkboard.project.members.all(), "corkboard_new_image", { "user": request.user, "corkboard": corkboard, "image_url": image.get_absolute_url, "corkboard_url": corkboard.get_absolute_url, }, ) request.user.message_set.create(message=_("Successfully uploaded image '%s'") % image.title) return render_to_response( template_name, {"corkboard": corkboard, "form": form, "images": images}, context_instance=RequestContext(request), )
def image_detail(request, id, template_name="loupe/image_detail.html"): """ Displays the image to be discussed by the project members expects an id for the image and the user has access to the parent project """ if not request.user.is_staff: image = get_object_or_404(Image, pk=id, corkboard__project__members=request.user) else: image = get_object_or_404(Image, pk=id) notes = Note.objects.filter(image=image) notes_count = notes.count() form = NoteForm() if request.method == "POST": form = NoteForm(request.user, request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.image = image note.save() if notification: notification.send_now( image.corkboard.project.members.all(), "corkboard_new_image_note", { "user": request.user, "image_url": image.get_absolute_url, "image": image }) request.user.message_set.create( message=_("Successfully attached note to image '%s'") % image.title) return render_to_response(template_name, { "image": image, "notes": notes, "notes_count": notes_count, "form": form, }, context_instance=RequestContext(request))
def send_all(*args): lock = acquire_lock(*args) batches, sent, sent_actual = 0, 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads(base64.b64decode(queued_batch.pickled_data)) for user, label, extra_context, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice {} to {}".format(label, user)) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. if notification.send_now([user], label, extra_context, sender): sent_actual += 1 except User.DoesNotExist: # Ignore deleted users, just warn about them logging.warning( "not emitting notice {} to user {} since it does not exist".format( label, user) ) sent += 1 queued_batch.delete() batches += 1 emitted_notices.send( sender=NoticeQueueBatch, batches=batches, sent=sent, sent_actual=sent_actual, run_time="%.2f seconds" % (time.time() - start_time) ) except Exception: # pylint: disable-msg=W0703 # get the exception _, e, _ = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[{} emit_notices] {}".format(current_site.name, e) message = "\n".join( traceback.format_exception(*sys.exc_info()) # pylint: disable-msg=W0142 ) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: {}".format(e)) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("{} batches, {} sent".format(batches, sent,)) logging.info("done in {:.2f} seconds".format(time.time() - start_time))
def give_money(request, slug, player_id): game = get_object_or_404(Game, slug=slug) if game.phase == 0 or not game.configuration.finances: messages.error(request, _("You cannot give money in this game.")) return redirect(game) borrower = get_object_or_404(Player, id=player_id, game=game) lender = get_object_or_404(Player, user=request.user, game=game) context = base_context(request, game, lender) if request.method == 'POST': form = forms.LendForm(request.POST) if form.is_valid(): ducats = form.cleaned_data['ducats'] if ducats > lender.ducats: ##TODO Move this to form validation messages.error(request, _("You cannot give more money than you have")) return redirect(game) lender.ducats = F('ducats') - ducats borrower.ducats = F('ducats') + ducats lender.save() borrower.save() messages.success(request, _("The money has been successfully sent.")) if notification: extra_context = {'game': lender.game, 'ducats': ducats, 'country': lender.country, 'STATIC_URL': settings.STATIC_URL} if lender.game.fast: notification.send_now([borrower.user,], "received_ducats", extra_context) else: notification.send([borrower.user,], "received_ducats", extra_context) return redirect(game) else: form = forms.LendForm() context['form'] = form context['borrower'] = borrower return render_to_response('machiavelli/give_money.html', context, context_instance=RequestContext(request))
def expiration_notification(sender, **kwargs): """ FIXME: Migrate it (txcron) to work with the String Level. """ logger.debug("lock-addon: Sending expiration notifications...") if not settings.ENABLE_NOTICES: logger.debug("lock-addon: ENABLE_NOTICES is not enabled") return current_site = Site.objects.get_current() locks = Lock.objects.expiring() nt = 'project_resource_language_lock_expiring' for lock in locks: context = { 'resource': lock.rlstats.resource, 'language': lock.rlstats.language, 'project' : lock.rlstats.resource.project, 'user': lock.owner, 'expires': lock.expires, 'current_site' : current_site } logger.debug("lock-addon: Sending notification about lock: %s" % lock) notification.send_now([lock.owner,], nt, context) lock.notified = True lock.save()
def project_detail(request, slug, template_name="loupe/project_detail.html"): """ Displays the corkboards for the given porject 'slug' to the user expects a slug and expects the user has access to the parent project """ if not request.user.is_staff: project = get_object_or_404(Project, slug=slug, members=request.user) else: project = get_object_or_404(Project, slug=slug) corkboards = Corkboard.objects.filter(project=project) form = CorkboardForm() if request.method == "POST": form = CorkboardForm(request.user, request.POST) if form.is_valid(): corkboard = form.save(commit=False) corkboard.user = request.user corkboard.project = project corkboard.save() request.user.message_set.create(message=_("Successfully created corkboard '%s'") % corkboard.title) if notification: notification.send_now( project.members.all(), "corkboard_new_corkboard", {"user": request.user, "corkboard": corkboard, "corkboard_url": corkboard.get_absolute_url}, ) return HttpResponseRedirect(reverse("corkboard_detail", args=(corkboard.slug,))) return render_to_response( template_name, {"project": project, "form": form, "corkboards": corkboards}, context_instance=RequestContext(request), )
def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent = 0, 0 start_time = time.time() try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads(str(queued_batch.pickled_data).decode("base64")) for user, label, extra_context, on_site in notices: user = User.objects.get(pk=user) logging.info("emitting notice to %s" % user) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site) sent += 1 queued_batch.delete() batches += 1 finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent)) logging.info("done in %.2f seconds" % (time.time() - start_time))
def refresh_acqs(): in_10_min = now() + timedelta(minutes=10) acqs = Acq.objects.filter(refreshed=False, refreshes__lt=in_10_min) logger.info('refreshing %s acqs' % acqs.count()) for acq in acqs: for hold in acq.holds: # create a 1 day reserve on the acq reserve_acq = Acq.objects.create( user=hold.user, work=hold.work, license=RESERVE, lib_acq=acq, ) # the post_save handler takes care of pushing expires vis acq.expires_in # notify the user with the hold if 'example.org' not in reserve_acq.user.email: notification.send_now([reserve_acq.user], "library_reserve", {'acq': reserve_acq}) # delete the hold hold.delete() break else: acq.refreshed = True
def test_announce(): from notification import models as notification a = Announcement.objects.all()[0] data = {'content' :a.content, 'get_absolute_url' : a.get_absolute_url()} users = [User.objects.get(username = '******'), User.objects.get(username = '******')] notification.send_now(users, "announcement", {'announcement' : data})
def notify(self, from_user, q): editors = Permission.objects.get(codename='change_question').user_set.all() | User.objects.filter(is_superuser=True) notification.send_now(editors, 'question_reported', {"from":from_user, "q":q, "description": self.cleaned_data['description']})
def send_all(): lock = FileLock("send_notices") logging.debug("acquiring lock...") try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logging.debug("lock already in place. quitting.") return except LockTimeout: logging.debug("waiting for the lock timed out. quitting.") return logging.debug("acquired.") batches, sent, tried = 0, 0, 0 start_time = time.time() try: # nesting the try statement to be Python 2.4 try: for queued_batch in NoticeQueueBatch.objects.all(): notices = pickle.loads(str(queued_batch.pickled_data).decode("base64")) for user, label, extra_context, on_site, sender in notices: try: user = User.objects.get(pk=user) logging.info("emitting notice %s to %s" % (label, user)) # call this once per user to be atomic and allow for logging to # accurately show how long each takes. notification.send_now([user], label, extra_context, on_site, sender) tried = tried + 1 except User.DoesNotExist: tried = tried + 1 # Ignore deleted users, just warn about them logging.warning("not emitting notice %s to user %s since it does not exist" % (label, user)) except Exception as e: logging.critical("Error while sending email to user: %s. Notification: %s" % (user, label)) logging.critical("Exception: %s" % e.value) logging.critical("Updating NoticeQueueBatch object to avoid re-sending to same users...") queued_batch.pickled_data = pickle.dumps(notices[tried:]).encode("base64") queued_batch.save() raise e sent += 1 queued_batch.delete() batches += 1 tried = 0 except: # get the exception exc_class, e, t = sys.exc_info() # email people current_site = Site.objects.get_current() subject = "[%s emit_notices] %r" % (current_site.name, e) message = "%s" % ("\n".join(traceback.format_exception(*sys.exc_info())),) mail_admins(subject, message, fail_silently=True) # log it as critical logging.critical("an exception occurred: %r" % e) finally: logging.debug("releasing lock...") lock.release() logging.debug("released.") logging.info("") logging.info("%s batches, %s sent" % (batches, sent,)) logging.info("done in %.2f seconds" % (time.time() - start_time))