Exemplo n.º 1
0
 def test_send_now(self):
     Site.objects.create(domain="localhost", name="localhost")
     users = [self.user, self.user2]
     send_now(users, "label")
     self.assertEqual(len(mail.outbox), 2)
     self.assertIn(self.user.email, mail.outbox[0].to)
     self.assertIn(self.user2.email, mail.outbox[1].to)
     self.assertEqual(len(NoticeHistory.objects.all()), 1)
     not_his = NoticeHistory.objects.get(pk=1)
     self.assertEqual(len(not_his.recipient.all()), 2)
Exemplo n.º 2
0
def check_message_mention(sender_user, url, message, label):
    users = re.findall(r"(?<=@)\w+", message)
    for user in list(set(users)):
        notice = NoticeType.objects.get(label=label)
        u = User.objects.filter(username=user)
        if u.count() > 0:
            Notification.objects.create(recipient=u[0], notice_type=notice, sender=sender_user, url=url, message=message)
            send_now([u[0]], label, sender=sender_user, extra={'url': url,
                                                               'message': message,
                                                               'date': datetime.datetime.now()})
Exemplo n.º 3
0
def check_message_mention(sender_user, url, message, label):
    users = re.findall(r"(?<=@)\w+", message)
    for user in list(set(users)):
        notice = NoticeType.objects.get(label=label)
        u = User.objects.filter(username=user)
        if u.count() > 0:
            Notification.objects.create(recipient=u[0], notice_type=notice, sender=sender_user, url=url, message=message)
            send_now([u[0]], label, sender=sender_user, extra={'url': url,
                                                               'message': message,
                                                               'date': datetime.datetime.now()})
Exemplo n.º 4
0
def connect(request):

    success = False
    errors = {}
    data = None
    req_prof = request.user.profile

    if request.POST and request.is_ajax():

        type = request.POST.get('type', None)
        username = request.POST.get('user', None)

        if type and username:
            user = User.objects.filter(username=username)
            if user.exists():
                user = user[0]
            else:
                user = None

            if not user:
                errors['user'] = "******" % username

            elif user.profile == req_prof:
                errors['user'] = "******"

            else:
                if type == 'add-follow':
                    req_prof.follows.add(user.profile)

                    try:
                        c = Command()
                        c.user_populate_history(request.user, user)
                    except Exception, e:
                        print e

                    notice = NoticeType.objects.get(label="new_follower")
                    Notification.objects.create(recipient=user,
                                                sender=request.user,
                                                notice_type=notice)
                    send_now([user], "new_follower", sender=request.user)

                elif type == 'rm-follow' and req_prof.follows.filter(
                        user=user).exists():
                    req_prof.follows.remove(user)

                    try:
                        c = Command()
                        c.remove_user_populate_history(request.user, user)
                    except Exception, e:
                        print e
Exemplo n.º 5
0
def connect(request):

    success = False
    errors = {}
    data = None
    req_prof = request.user.profile

    if request.POST and request.is_ajax():

        type = request.POST.get('type', None)
        username = request.POST.get('user', None)

        if type and username:
            user = User.objects.filter(username=username)
            if user.exists():
                user = user[0]
            else:
                user = None

            if not user:
                errors['user'] = "******" % username

            elif user.profile == req_prof:
                errors['user'] = "******"

            else:
                if type == 'add-follow':
                    req_prof.follows.add(user.profile)
                    
                    try:
                        c = Command()
                        c.user_populate_history(request.user, user)
                    except Exception, e:
                        print e
                        
                    notice = NoticeType.objects.get(label="new_follower")
                    Notification.objects.create(recipient=user, sender=request.user, notice_type=notice)
                    send_now([user], "new_follower", sender=request.user)

                elif type == 'rm-follow' and req_prof.follows.filter(
                        user=user).exists():
                    req_prof.follows.remove(user)
                    
                    try:
                        c = Command()
                        c.remove_user_populate_history(request.user, user)
                    except Exception, e:
                        print e
Exemplo n.º 6
0
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 = get_user_model().objects.get(pk=user)
                        logging.info("emitting notice {0} to {1}".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 get_user_model().DoesNotExist:
                        # Ignore deleted users, just warn about them
                        logging.warning(
                            "not emitting notice {0} to user {1} 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 = "[{0} emit_notices] {1}".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: {0}".format(e))
    finally:
        logging.debug("releasing lock...")
        lock.release()
        logging.debug("released.")

    logging.info("")
    logging.info("{0} batches, {1} sent".format(
        batches,
        sent,
    ))
    logging.info("done in {0:.2f} seconds".format(time.time() - start_time))
Exemplo n.º 7
0
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 = get_user_model().objects.get(pk=user)
                        logging.info(
                            "emitting notice {0} to {1}".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 get_user_model().DoesNotExist:
                        # Ignore deleted users, just warn about them
                        logging.warning(
                            "not emitting notice {0} to user {1} 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 = "[{0} emit_notices] {1}".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: {0}".format(e))
    finally:
        logging.debug("releasing lock...")
        lock.release()
        logging.debug("released.")

    logging.info("")
    logging.info("{0} batches, {1} sent".format(batches, sent,))
    logging.info("done in {0:.2f} seconds".format(time.time() - start_time))
Exemplo n.º 8
0
 def test_digest_creator(self):
     send_now([self.user], "label")
     send_now([self.user], "label")
     send_now([self.user], "label2")
     send_digest([self.user2], ["label"])
     self.assertEqual(len(mail.outbox), 4)
     send_digest([self.user2], ["label", "label2"])
     self.assertEqual(len(mail.outbox), 5)
Exemplo n.º 9
0
 def test_history_collection(self):
     send_now([self.user], "label")
     send_now([self.user], "label")
     send_now([self.user], "label2")
     send_now([self.user], "different")
     query = NoticeHistory.objects.filter(notice_type__label__in=["label"])
     self.assertEqual(len(query), 2)
     query = NoticeHistory.objects.filter(notice_type__label__in=["label2"])
     self.assertEqual(len(query), 1)
     query = NoticeHistory.objects.filter(notice_type__label__in=["different"])
     self.assertEqual(len(query), 1)
     query = NoticeHistory.objects.filter(notice_type__label__in=["label", "label2", "different"])
     self.assertEqual(len(query), 4)
     query = NoticeHistory.objects.filter(sent_at__gte=(timezone.now() - timezone.timedelta(days=1)),  notice_type__label__in=["label", "label2", "different"])
     self.assertEqual(len(query), 4)
     query = NoticeHistory.objects.filter(sent_at__gte=timezone.now(),  notice_type__label__in=["label", "label2", "different"])
     self.assertEqual(len(query), 0)