Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- import locale
- from datetime import datetime
- from django.conf import settings
- from django.contrib.sites.models import Site
- from django.contrib.auth.models import User
- from celery.decorators import periodic_task
- from celery.schedules import crontab
- from django.template.loader import render_to_string
- from textmagic.client import TextMagicClient, TextMagicError
- from ella.user_accounts.models import UserProfile
- from ella.events.models import BiddingRoundUsers
- from ella.sms.models import Message
- from ella.notices.models import EmailMessage
- from ella.utils import SendSMS, proper_absolute_url, randstr
- from ella.utils.amazon_ses import AmazonSES, EmailMessage as Email,\
- AmazonError, AmazonAPIError
- from ella.utils.nexmomessage import NexmoMessage
- @periodic_task(run_every=crontab())
- def queue_message_handler():
- print "RUN RUN RUN"
- '''
- Message.objects.filter(direction=0, status=0).update(status=1)
- incomming_messages = Message.objects.filter(direction=0,
- status=1).values_list('id', flat=True)
- incomming_message_handler(incomming_messages)
- Message.objects.filter(direction=1, status=0).update(status=1)
- outgoing_messages = Message.objects.filter(direction=1,
- status=1).values_list('id', flat=True)
- outgoing_message_handler(outgoing_messages)
- # FIXME: Change EmailMessage model also.
- email_message_handler(EmailMessage.objects.filter(proceed=False))
- '''
- Message.objects.filter(direction=1, status=0).update(status=1)
- outgoing_messages = Message.objects.filter(direction=1,
- status=1).values_list('id', flat=True)
- print "Oungoing messages" + str(len(outgoing_messages))
- print outgoing_messages
- outgoing_message_handler(outgoing_messages)
- def incomming_message_handler(incomming_messages):
- def parse_message(text):
- result = {'argument': ''}
- text = text.replace('"', '').lower()
- data = text.split(' ', 1)
- if len(data) == 2:
- result['command'], result['argument'] = data[0], data[1].replace(' ', '')
- else:
- result['command'] = data[0]
- return result
- def get_user(phone):
- try:
- user = UserProfile.objects.filter(mobile_phone=phone[2:],
- country__mobile_prefix=phone[:2])[0].user
- except IndexError:
- user = None
- return user
- def make_bid(user, code):
- try:
- bidding_round_user = BiddingRoundUsers.objects.get(code=code,
- user=user)
- except BiddingRoundUsers.DoesNotExist:
- SendSMS(user, render_to_string('notices/sms/bru_does_not_exist',
- {'code': code}))
- return
- event = bidding_round_user.event
- profile = user.get_profile()
- message = ''
- if not event.is_open:
- message = render_to_string('notices/sms/event_closed',
- {'code': code})
- elif event.deleted:
- message = render_to_string('notices/sms/event_deleted',
- {'code': code})
- elif profile.conflicting_appointments(event.start_date,
- event.end_date, event.start_time,
- event.end_time).filter(is_assigned=True):
- message = render_to_string('notices/sms/conflicting_appointments',
- {'code': code})
- else:
- if profile.receive_event_confirmation:
- message = render_to_string('notices/sms/bid_accepted',
- {'bru': bidding_round_user})
- bidding_round_user.responded_yes = True
- bidding_round_user.responded_no = False
- bidding_round_user.agreed_at = datetime.now()
- bidding_round_user.save()
- if message:
- SendSMS(user, message)
- def activate_user(user, code):
- profile = user.get_profile()
- if profile.activation_code.lower() == code:
- password = randstr(length=4, allowed_chars='23456789')
- user.set_password(password)
- user.is_active = True
- user.save()
- SendSMS(user, render_to_string('notices/sms/user_activated',
- {'link': proper_absolute_url('/', False,
- profile.municipalities.all()[0])[:-1],
- 'login': user.username, 'password': password }))
- else:
- SendSMS(user, render_to_string('notices/sms/wrong_activation_code',
- {'code': profile.activation_code}))
- def send_events_date(user, date):
- try:
- event_date = datetime.strptime(date, '%d%m%y')
- except ValueError:
- SendSMS(user, render_to_string('notices/sms/gibberish_date',
- {'wrong_date': date,
- 'curr_short_date': datetime.now().strftime('%d%m%y')}))
- return
- brus = BiddingRoundUsers.objects.filter(event__start_date=event_date,
- user=user)
- for bru in brus:
- sms_msg = render_to_string('notices/sms/events_to_date',
- {'bru': bru })
- SendSMS(bru.user, sms_msg)
- def unknown_command(user):
- SendSMS(user, render_to_string('notices/sms/unknown_command'))
- for message in Message.objects.filter(id__in=incomming_messages):
- user = get_user(message.phone)
- if not user:
- message.status = 2
- message.save()
- continue
- data = parse_message(message.text)
- if data['command'] == u'vagt':
- make_bid(user, data['argument'])
- elif data['command'] == u'aktiver':
- activate_user(user, data['argument'])
- elif data['command'] == u'vagter':
- send_events_date(user, data['argument'])
- else:
- unknown_command(user)
- message.status = 2
- message.save()
- def outgoing_message_handler(outgoing_messages):
- client = TextMagicClient(settings.TEXTMAGIC_LOGIN,
- settings.TEXTMAGIC_PASSWORD)
- for message in Message.objects.filter(id__in=outgoing_messages):
- print "send sms %s" % settings.SEND_SMS
- if settings.SEND_SMS:
- try:
- '''
- result = client.send(message.text,
- message.phone, send_time=message.timestamp.timetuple())
- '''
- msg = {'reqtype': "json",
- 'username': settings.NEXMO_LOGIN,
- 'password': settings.NEXMO_PASSWORD,
- 'text': message.text,
- 'from': "???",
- 'to': message.phone}
- sms = NexmoMessage(msg)
- print("SMS details: %s") % sms.get_details()
- #result = sms.send_request()
- print result
- except TextMagicError, e:
- print e
- print message
- else:
- message.msg_id = result['message_id'].keys()[0]
- else:
- dbg_msg = u'Handle %s SMS: %s | %s' % (u'outgoing' if message.direction\
- else u'incomming', message.phone, message.text)
- print dbg_msg.encode(locale.getpreferredencoding())
- message.status = 2
- message.save()
- def email_message_handler(queue):
- amazon_ses = AmazonSES(settings.ASES_ACCESS_KEY_ID,
- settings.ASES_SECRET_ACCESS_KEY)
- for message in queue:
- email_message = Email()
- email_message.subject = message.text.split('\n', 1)[0].encode('utf-8')
- email_message.bodyText = message.text.split('\n', 1)[1].encode('utf-8')
- if settings.SEND_EMAIL:
- try:
- amazon_ses.sendEmail(message.sender, message.receiver,
- email_message)
- except (AmazonError, AmazonAPIError), e:
- print e
- print message
- else:
- dbg_msg = u'Handle email:\n>To: %s\n%s' % (message.receiver,
- message.text)
- print dbg_msg.encode(locale.getpreferredencoding())
- message.proceed = True
- message.save()
Add Comment
Please, Sign In to add comment