示例#1
0
文件: api.py 项目: airoswell/continue
def pm_write(sender, recipient, subject, body='', skip_notification=False,
        auto_archive=False, auto_delete=False, auto_moderators=None):
    """
    Write a message to a User.
    Contrary to pm_broadcast(), the message is archived and/or deleted on
    the sender side only if requested.
    The message may come from an untrusted application, a gateway for example,
    so it may be useful to involve some auto moderators in the processing.

    Optional arguments:
        ``skip_notification``: if the normal notification event is not wished
        ``auto_archive``: to mark the message as archived on the sender side
        ``auto_delete``: to mark the message as deleted on the sender side
        ``auto_moderators``: a list of auto-moderation functions
    """
    if type(sender) is str:
        message = Message(subject=subject, body=body,
                          email=sender, recipient=recipient)
    else:
        message = Message(subject=subject, body=body,
                          sender=sender, recipient=recipient)
    initial_status = message.moderation_status
    if auto_moderators:
        message.auto_moderate(auto_moderators)
    else:
        message.moderation_status = STATUS_ACCEPTED
    message.clean_moderation(initial_status)
    if auto_archive:
        message.sender_archived = True
    if auto_delete:
        message.sender_deleted_at = now()
    message.save()
    if not skip_notification:
        message.notify_users(initial_status, _get_site())
示例#2
0
 def _send_private_messages_recipient_and_admin(subject, body, recipient):
     status = STATUS_ACCEPTED
     sender = User.objects.filter(username='******').first()
     message_user = Message(subject=subject, body=body, sender=sender, recipient=recipient, moderation_status=status)
     message_user.save()
     message_admin = Message(subject=subject, body=body, sender=recipient, recipient=sender,
                             moderation_status=status)
     message_admin.save()
示例#3
0
文件: api.py 项目: ppp0/openbroadcast
def pm_broadcast(sender,
                 recipients,
                 subject,
                 body='',
                 skip_notification=False):
    """
    Broadcast a message to multiple Users.
    For an easier cleanup, all these messages are directly marked as archived
    and deleted on the sender side.
    The message is expected to be issued from a trusted application, so moderation
    is not necessary and the status is automatically set to 'accepted'.

    Optional argument:
        ``skip_notification``: if the normal notification event is not wished
    """
    message = Message(subject=subject,
                      body=body,
                      sender=sender,
                      sender_archived=True,
                      sender_deleted_at=now(),
                      moderation_status=STATUS_ACCEPTED,
                      moderation_date=now())
    if not isinstance(recipients, (tuple, list)):
        recipients = (recipients, )
    for recipient in recipients:
        message.recipient = recipient
        message.pk = None
        message.save()
        if not skip_notification:
            message.notify_users(STATUS_PENDING)
示例#4
0
文件: api.py 项目: hannanxp/uface
def pm_write(sender,
             recipient,
             subject,
             body='',
             skip_notification=False,
             auto_archive=False,
             auto_delete=False):
    """
    Write a message to a User.
    Contrary to pm_broadcast(), the message is archived and/or deleted on the sender side only if requested.

    Optional arguments:
        ``skip_notification``: if the normal notification event is not wished
        ``auto_archive``: to mark the message as archived on the sender side
        ``auto_delete``: to mark the message as deleted on the sender side
    """
    message = Message(subject=subject,
                      body=body,
                      sender=sender,
                      recipient=recipient,
                      moderation_status=STATUS_ACCEPTED,
                      moderation_date=now())
    if auto_archive:
        message.sender_archived = True
    if auto_delete:
        message.sender_deleted_at = now()
    message.save()
    if not skip_notification:
        message.notify_users(STATUS_PENDING)
示例#5
0
    def handle(self, *args, **options):
        now = datetime.datetime.now()
        dow = now.weekday()
        begin = now + datetime.timedelta(minutes=WARN_DELAY_MIN)
        end = now + datetime.timedelta(minutes=WARN_DELAY_MAX)
        slots = WebclassSlot.published.filter(day=dow,
                                              start_hour__gte=begin.time(),
                                              start_hour__lt=end.time())
        site = Site.objects.all()[0]
        admin = User.objects.get(username='******')
        date = now.strftime('%d/%m/%Y')
        for slot in slots:
            hour = slot.start_hour.strftime('%Hh%M')
            print("Sending notifications for %s:%s (%s)" %
                  (slot.webclass.course, slot.start_hour, slot.id))
            subject = "Webclass_%s_%s_%s" % (slot.webclass.course, date, hour)

            body = """Votre Webclasse va commencer."""

            users = slot.participants.all()
            for user in users:
                print(" => %s" % user)
                msg = Message(subject=subject,
                              body=body,
                              sender=admin,
                              recipient=user)
                msg.moderation_status = 'a'
                msg.save()
                notify_user(msg, 'acceptance', site)
示例#6
0
 def _setup_test_message(cls, sender):
     message = Message(
         subject=cls.faker.sentence(),
         body=cls.faker.paragraph(),
         sender=sender,
         recipient=cls.sender,
     )
     message.auto_moderate([])
     message.save()
     return message
示例#7
0
 def send(self):
     site = Site.objects.all()[0]
     users = [student.user for student in self.group.students.all()]
     for user in users:
         mess = Message(sender=self.sender,
                        recipient=user,
                        subject=self.subject[:119],
                        body=self.message)
         mess.moderation_status = 'a'
         mess.save()
         notify_user(mess, 'acceptance', site)
示例#8
0
def deliver_pending(request):

    '''
    Find notifications in Queue state and deliver to all recipients. We actually
    do two things here: 1) Created a Delivered record in our own Notifications app,
    so we have a custom record that can be displayed in the widget, which the user
    can check off as completed, etc.; and 2) Deliver a system message via Postman.
    
    The get_members() method on DynamicList aggregates all logical recipients.
    Django-Postman lets us save a Message instance and takes care of delivery.
    This function is never accessed by users - superusers and cron jobs only.
    Superusers can trigger delivery without cron by accessing /notifications/deliver_pending
    '''
    
    notifications = Notification.objects.filter(state='queue')
    
    for n in notifications:
        
        # Find all members associated with this notification's associated dynamic list
        if n.dlist:
            recips = n.dlist.get_members()

        if n.offering:
            recips = n.offering.get_members()
        
        # What if there's both a dlist and an offering? Need a way to combine them here
        
        for r in recips:
            # Create Postman message
            msg = Message() # Instantiate new message on Postman's Message class
            msg.subject = 'New %s on CalCentral: %s' % (n.type, n.title)
            msg.body = n.description
            msg.sender = n.author
            msg.recipient = r
            msg.moderation_status = STATUS_ACCEPTED # a = accepted. Override postman default = all msgs are pending
            msg.notify_users(STATUS_PENDING,is_auto_moderated=True)
            msg.save()
            
            # Create a Deliver instance for each user
            d = Delivered()
            d.notification = n
            d.user = r
            d.completed = False
            d.deliver_date = datetime.datetime.now()
            d.save()
            
            # Move the notification from the queue to the archive
            n.state = 'arch'
            n.save()
    
    # Since this is not a browser view, just need an empty httpresponse
    return HttpResponseRedirect(reverse('notifications'))            
    
    
示例#9
0
 def reject(self):
     self.date_marked = datetime.datetime.now()
     self.date_rejected = datetime.datetime.now()
     site = Site.objects.all()[0]
     context = {'script': self, 'site': site}
     text = render_to_string('exam/messages/script_rejected.txt', context)
     a = ugettext('Script')
     v = ugettext('rejected')
     subject = '%s %s' % (a, v)
     mess = Message(sender=self.corrector, recipient=self.author, subject=subject[:119], body=text)
     mess.moderation_status = 'a'
     mess.save()
     notify_user(mess, 'acceptance', site)
示例#10
0
文件: api.py 项目: kishan3/castcore
def pm_write(sender,
             recipient,
             subject=None,
             body='',
             skip_notification=False,
             auto_archive=False,
             auto_delete=False,
             auto_moderators=None,
             set_thread=False):
    """
    Write a message to a User.

    Contrary to pm_broadcast(), the message is archived and/or deleted on
    the sender side only if requested.
    The message may come from an untrusted application, a gateway for example,
    so it may be useful to involve some auto moderators in the processing.

    Optional arguments:
        ``skip_notification``: if the normal notification event is not wished
        ``auto_archive``: to mark the message as archived on the sender side
        ``auto_delete``: to mark the message as deleted on the sender side
        ``auto_moderators``: a list of auto-moderation functions
    """
    if subject is None or subject == '':
        raise ValidationError("Subject can not be blank")
    message = Message(subject=subject,
                      body=body,
                      sender=sender,
                      recipient=recipient)
    initial_status = message.moderation_status
    if auto_moderators:
        message.auto_moderate(auto_moderators)
    else:
        message.moderation_status = STATUS_ACCEPTED
    message.clean_moderation(initial_status)
    if auto_archive:
        message.sender_archived = True
    if auto_delete:
        message.sender_deleted_at = now()
    message.save()
    if set_thread:
        message.thread = message
    message.save()
    if not skip_notification:
        action.send(recipient,
                    verb=u"got a new message.",
                    description=u"Got the message.")
        # message.notify_users(initial_status, _get_site())
    return message
示例#11
0
def order_notification(cart, order, user):
    cart_storages = make_cart_storages(cart, user)

    for cart_storage, items in cart_storages.items():
        body = 'Новый заказ от {date} #{order_number}.\r\n\r\nИнформация о заказе:\r\n'.format(
            date=order.added.strftime('%d.%m.%Y %H:%M'), order_number=order.id)
        profile = UserProfile.objects.get(user=user)
        body += 'Заказчик: {name} \r\n'.format(
            name=profile.fullname or profile)
        body += 'Код заказчика: {vip_code}\r\n'.format(
            vip_code=profile.vip_code or 'код заказчика отсутствует')

        storage = cart_storage
        order_total = 0
        for idx, item in enumerate(items):
            product = item.item
            price = product.get_price(user, item.storage)
            qty = item.quantity
            order_total += price * qty
            body += '{idx}. {title} {brand} {sku}, {qty} шт. x {price} руб.., на общую сумму: {line_total} руб.\r\n'.format(
                idx=idx + 1,
                title=product.title,
                brand=product.brand,
                sku=product.get_sku(),
                qty=qty,
                price=price,
                line_total=qty * price)
            op = OrderProduct(order=order, item=product, qty=qty, price=price)
            op.save()

        body += '\r\nИтого: {total} руб.'.format(total=order_total)
        body += '\r\nСклад: {storage}'.format(storage=storage.name)
        body += '\r\n\r\nEmail клиента: {email}'.format(email=user.email)
        body += '\r\n\r\nКомментарии к заказу:\r\n{comment}'.format(
            comment=order.comment)

        subject = 'Сформирован новый заказ от {date} № {order_num}!'.format(
            date=order.added.strftime("%d.%m.%Y %H:%M"), order_num=order.id)
        sender = User.objects.filter(username='******').first()
        recipient = user
        status = STATUS_ACCEPTED
        message_user = Message(subject=subject,
                               body=body,
                               sender=sender,
                               recipient=recipient,
                               moderation_status=status)
        message_user.save()
        message_admin = Message(subject=subject,
                                body=body,
                                sender=recipient,
                                recipient=sender,
                                moderation_status=status)
        message_admin.save()

        # XLS document
        wb = Workbook()
        ws = wb.active
        ws.title = 'Заказ'

        thin_border = Border(left=Side(style='thin'),
                             right=Side(style='thin'),
                             top=Side(style='thin'),
                             bottom=Side(style='thin'))
        data = []

        for idx, item in enumerate(cart.cartitem_set.all()):
            product = item.item
            price = product.get_price(user, item.storage)
            print(item.storage)
            print(price)
            qty = item.quantity
            coordinate = 'B' + str(idx)
            article = '%s %s' % (product.brand, product.get_sku())
            data.append(
                [idx + 1, product.title, article, qty, price, qty * price])

        ws.append([
            '#', 'Товар', 'Брэнд', 'Количество', 'Цена за единицу',
            'Цена (общая)'
        ])
        for row in data:
            ws.append(row)
        ws.append(['', '', '', '', 'Итого:', order_total])

        row_count = ws.max_row + 1
        column_count = ws.max_column + 1

        for i in range(1, row_count):
            for j in range(1, column_count):
                ws.cell(row=i, column=j).border = thin_border

        ws.column_dimensions["A"].width = 5.0
        ws.column_dimensions["B"].width = 17.0
        ws.column_dimensions["C"].width = 23.0
        ws.column_dimensions["D"].width = 13.0
        ws.column_dimensions["E"].width = 18.0
        ws.column_dimensions["F"].width = 18.0

        email = EmailMessage(
            subject,
            body,
            EMAIL_NOREPLY,
            [storage.email],
            EMAIL_BCC,
            reply_to=EMAIL_NOREPLY_LIST,
            headers={'Message-ID': 'foo'},
        )

        output = BytesIO()
        wb.save(output)

        email.attach('order.xlsx', output.getvalue(), 'application/excel')
        email.send()

    return True