예제 #1
0
def get(session):
    '''
    Uses memcache or the datastore to fetch a single setting by wave_id,
    wavelet_id and email. Ideally this should fetch session only if needed but
    this wouldn't work with the appengine transaction framework.
    @transaction_safe
    @param session: the parent session object

    @return the setting using the most efficient means possible or None if it
    couldn't be found
    '''
    if not session:
        return None
    key = base64.b64encode( memcacheConfig.PREFIX['SETTINGS'] + 
                            session.wave_id + 
                            session.wavelet_id +
                            session.email)
    setting = memcache.get(key)
    if not setting == None:
        return setting
    else:
        query = Settings.all()
        query.ancestor(session)
        setting = query.get()
        memcache.add(key, setting, time=memcacheConfig.DEFAULT_EXPIRE_SECS)
        return setting
예제 #2
0
def send_text(to, subject, text):
    message = mail.EmailMessage()
    message.sender = Settings.all().get().bot
    message.to = to
    message.subject = subject
    message.body = '\n'.join(text)
    message.html = u"<html><body>%s</body></html>" % ('<br>'.join(text),)
    message.send()
예제 #3
0
def notify_task(queue_id):
    try:
        settings = Settings.all().get()
        client = TwilioRestClient(settings.account_sid, settings.auth_code)
        call_queue = CallQueue.get_by_id(queue_id)
        next_entry = call_queue.entries.filter('status =', 'P').order('sequence').get()

        if next_entry and call_queue.status == 'P':

            if next_entry.entry_type == 'phone':
                next_entry.status = 'C'
                next_entry.put()
                client.calls.create(to=next_entry.recipient.phone_number, from_=settings.twilio_number,
                                    url='http://%s.appspot.com/call?call_queue_id=%s&queue_entry_id=%s' % (
                                        app_identity.get_application_id(), queue_id, next_entry.key().id()),
                                    status_callback='http://%s.appspot.com/callStatus?call_queue_id=%s&queue_entry_id=%s' % (
                                        app_identity.get_application_id(), queue_id, next_entry.key().id()),
                                    method='GET', timeout=15)
                event_log = 'Called %s (%s)' % (next_entry.recipient.name, next_entry.recipient.phone_number)
                alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
                alert_trace.put()

            if next_entry.entry_type == 'sms':
                next_entry.status = 'C'
                next_entry.put()
                sms_message = '%s Send 1 to accept' % call_queue.notifier.sms_message
                client.sms.messages.create(to=next_entry.recipient.phone_number,
                                           from_=settings.twilio_number,
                                           body=sms_message)
                deferred.defer(notify_task, queue_id, _countdown=settings.sms_timeout)
                event_log = 'SMS %s (%s)' % (next_entry.recipient.name, next_entry.recipient.phone_number)
                alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
                alert_trace.put()

        elif next_entry == None and call_queue.status == 'P' and call_queue.loop_count <= 5:
            call_queue.loop_count = call_queue.loop_count + 1
            call_queue.put()
            event_log = 'Alert not accepted yet. Restarting. Loop count:%s' % call_queue.loop_count
            alert_trace = AlertTrace(event_log=event_log, call_queue=call_queue)
            alert_trace.put()
            # re start the alert propagation
            entries = []
            for entry in call_queue.entries:
                new_entry = clone_entity(entry, status='P')
                entries.append(new_entry)
            if len(entries) != 0:
                db.put(entries)
                deferred.defer(notify_task, queue_id, _countdown=5 * 60)

    except:
        # raise
        logging.error("notify_task failed for  queue_id : %s" % queue_id)
        logging.error(traceback.format_exc())
예제 #4
0
 def post(self):
     enable_desable = self.request.get('enable_desable')
     settings = Settings.all().get()
     if not settings:
         self.redirect('/settings')
     else:
         if 'enable' == enable_desable:
             settings.alert_enabled = True
         else:
             settings.alert_enabled = False
         settings.put()
     self.redirect('/')
예제 #5
0
def send_pdf(pdf, name, email):
    logging.info(u"Отправляем детализацию абонента %s на адрес %s" % (pdf.name, email))
    message = mail.EmailMessage()
    message.sender = Settings.all().get().bot
    if name:
        message.to = u"%s <%s>" % (name, email)
    else:
        message.to = email
    message.subject = u"Детализация Beeline абонента %s %s %s" % (pdf.name, gen_date(pdf), pdf.num)
    message.attachments = [(u"Beeline %s %s %s.pdf" % (pdf.name, gen_date(pdf), pdf.num), pdf.blob)]
    message.body = u"Детализация во вложении"
    message.send()
예제 #6
0
 def render_response(self, _template, **context):
     settings = Settings.all().get()
     # Renders a template and writes the result to the response.
     logout = '/logout'
     email = users.get_current_user().email()
     context['admin'] = users.is_current_user_admin()
     context['session'] = self.session
     context['request'] = self.request
     context['logout'] = logout
     context['email'] = email
     context['settings'] = settings
     rv = self.jinja2.render_template(_template, **context)
     self.response.write(rv)
예제 #7
0
def sms_task(queue_id):
    try:
        settings = Settings.all().get()
        client = TwilioRestClient(settings.account_sid, settings.auth_code)
        sms_queue = CallQueue.get_by_id(queue_id)
        next_entry = sms_queue.entries.filter('status =', 'P').filter('entry_type =', 'sms').order('sequence').get()
        if next_entry and sms_queue.status == 'P':
            next_entry.status = 'C'
            next_entry.put()
            sms_message = '%s Send 1 to accept' % sms_queue.notifier.sms_message
            client.sms.messages.create(to=next_entry.phone_number,
                                       from_=settings.twilio_number,
                                       body=sms_message)
            deferred.defer(sms_task, queue_id, _countdown=settings.sms_timeout)
    except:
        logging.error("sms_task failed for  queue_id : %s" % queue_id)
예제 #8
0
def call_task(call_queue_id):
    try:
        settings = Settings.all().get()
        client = TwilioRestClient(settings.account_sid, settings.auth_code)
        call_queue = CallQueue.get_by_id(call_queue_id)
        next_entry = call_queue.entries.filter('status =', 'P').filter('entry_type =', 'phone').order('sequence').get()
        if next_entry and call_queue.status == 'P':
            next_entry.status = 'C'
            next_entry.put()
            client.calls.create(to=next_entry.phone_number, from_=settings.twilio_number,
                                url='http://%s.appspot.com/call?call_queue_id=%s&queue_entry_id=%s' % (
                                    app_identity.get_application_id(), call_queue_id, next_entry.key().id()),
                                status_callback='http://%s.appspot.com/callStatus?call_queue_id=%s&queue_entry_id=%s' % (
                                    app_identity.get_application_id(), call_queue_id, next_entry.key().id()),
                                method='GET', timeout=15)

    except:
        logging.error("call_task failed for  queue_id : %s" % call_queue_id)
예제 #9
0
 def post(self):
     settings = Settings.all().get()
     form = SettingsForm(self.request.POST, obj=settings)
     if form.validate():
         if settings:
             settings.auth_code = form.auth_code.data
             settings.account_sid = form.account_sid.data
             settings.twilio_number = form.twilio_number.data
             settings.tz = form.tz.data
             settings.sms_timeout = form.sms_timeout.data
         else:
             settings = Settings(auth_code=form.auth_code.data, account_sid=form.account_sid.data,
                                 twilio_number=form.twilio_number.data, tz=form.tz.data,
                                 sms_timeout=form.sms_timeout.data)
         settings.put()
         self.redirect('/settings')
     else:
         self.render_response('settings.html', form=form, settings=settings)
예제 #10
0
    def receive(self, mail_message):
        logging.info('Incoming email')
        settings = Settings.all().get()
        logging.info('Alerts are enabled:%s' % settings.alert_enabled)
        if settings == None or settings.alert_enabled == False:
            logging.info('Alerts are paused. Ignoring in coming e-mails.')
            return
        plaintext_bodies = mail_message.bodies('text/plain')
        text_bodies = []
        for b in plaintext_bodies:
            payload = b[1]
            text_bodies.append(payload.decode())
        text_body = " ".join(text_bodies)
        logging.info("Mail raw body:%s" % mail_message.body)
        logging.info("Mail body text:%s" % text_body)

        tomail = mail_message.to.replace('"', '').replace("'", '')
        from_mail = mail_message.sender.replace('"', '').replace("'", '')
        if mail_message.sender.find('<') != -1:
            from_mail = from_mail.split('<')[1].split('>')[0]
        if mail_message.to.find('<') != -1:
            tomail = tomail.split('<')[1].split('>')[0]
        subject = ''
        try:
            subject = mail_message.subject
        except:
            logging.info("No Subject")
            pass
        logging.info('To:%s From:%s Subject:%s' % (tomail, from_mail, subject))
        notif = Notifier.all().filter('alert_email =', tomail).get()
        eligible = notif and from_mail.find(notif.from_email) != -1 and (
            notif.subject_pattern == None or notif.subject_pattern == '' or subject.find(
                notif.subject_pattern) != -1) and is_notifier_in_alert_period(notif)
        logging.info("Alert eligible : %s" % eligible)

        if eligible:
            logging.info("Calling create_notify_queue_task")
            twilio_tasks.create_notify_queue_task(notif, email_body=text_body)
예제 #11
0
 def get(self):
     settings = Settings.all().get()
     form = SettingsForm(self.request.GET, obj=settings)
     self.render_response('settings.html', form=form)
예제 #12
0
def make_mailto_link(text, label):
    return "<a href='mailto:%s?subject=%s&body=.'>%s</a>" % (Settings.all().get().bot, text, label)
예제 #13
0
def make_mailto_link_pdf(pdf, label, send_to=[]):
    return "<a href='mailto:%s?subject=beeline%%20get%%20%s%s&body=.'>%s</a>" % (Settings.all().get().bot, pdf.num, "%20" + " ".join(send_to) if send_to else "", label)