def handle(self, **options): try: connection = Connection.objects.get(identity=settings.PING_NUMBER) text = datetime.datetime.now().strftime('Worked at %H:%M %Y-%m-%d') get_router().handle_outgoing(OutgoingMessage(connection, text)) except: print "exception" pass
def send_password(self): # generate a one time use password password = User.objects.make_random_password(length=6, allowed_chars='1234567890') self.set_password(password) self.save() # send the SMS out (backend, created) = Backend.objects.get_or_create(name='mtn_3071') (connection, created) = Connection.objects.get_or_create(backend=backend, identity=self.username) get_router().add_outgoing(connection, "Your motome password is: %s %s %s" % (password[:2], password[2:4], password[4:]))
def view_message_history(request, connection_id): """ This view lists all (sms message) correspondence between RapidSMS and a User """ direction_choices = DIRECTION_CHOICES status_choices = STATUS_CHOICES reply_form = ReplyForm() connection = get_object_or_404(Connection, pk=connection_id) if connection.contact: messages = Message.objects.filter( connection__contact=connection.contact) else: messages = Message.objects.filter(connection=connection) messages = messages.order_by('-date') total_incoming = messages.filter(direction="I").count() total_outgoing = messages.filter(direction="O").count() latest_message = None if total_incoming: latest_message = messages.filter(direction="I").latest('date') if request.method == 'POST': reply_form = ReplyForm(request.POST) if reply_form.is_valid(): if Connection.objects.filter( identity=reply_form.cleaned_data['recipient']).count(): text = reply_form.cleaned_data.get('message') conn = Connection.objects.filter( identity=reply_form.cleaned_data['recipient'])[0] in_response_to = reply_form.cleaned_data['in_response_to'] outgoing = OutgoingMessage(conn, text) get_router().handle_outgoing(outgoing, in_response_to) return redirect("/contact/%d/message_history/" % connection.pk) else: reply_form.errors.setdefault('short_description', ErrorList()) reply_form.errors['recipient'].append( "This number isn't in the system") return render_to_response("contact/message_history.html", { "messages": messages, "stats_latest_message": latest_message, "stats_total_incoming": total_incoming, "stats_total_outgoing": total_outgoing, "connection": connection, "direction_choices": direction_choices, "status_choices": status_choices, "replyForm": reply_form }, context_instance=RequestContext(request))
def dashboard(req): """ dashboard for viewing poll status and incoming / outgoing messages """ # lets flush the messages & starts the workers get_router(True) if req.method.upper() == "GET": reply_form = ReplyForm() elif req.POST["action"].upper() == "REPLY": reply_form = ReplyForm(req.POST) if reply_form.is_valid(): if Connection.objects.filter(identity=reply_form.cleaned_data["recipient"]).count(): text = reply_form.cleaned_data["message"] try: # if the contact is in the database perform a mailmerge conn = Connection.objects.filter(identity=reply_form.cleaned_data["recipient"])[0] text = _mail_merge(Contact.objects.get(connection__identity=conn.identity), text) except: pass outgoing = OutgoingMessage(conn, text) get_router().handle_outgoing(outgoing) else: ## Create the contact and send it an email ??? # reply_form.errors['recipient']="This number isn't in the system. please add a contact" print "the message was ignored because the contact is not in the database" else: reply_form.errors.setdefault("short_description", ErrorList()) if "recipient" in reply_form.errors: reply_form.errors["recipient"].append("This number isn't in the system") if "message" in reply_form.errors: reply_form.errors["message"].append("A message is required") polls = Poll.objects.annotate(Count("responses")).order_by("start_date")[:5] data_collections = XForm.objects.annotate(Count("submissions")).order_by("created")[:5] messages = Message.objects.all().order_by("-date")[0:10] # get some real names per connection for message in messages: message.connection.name = "Unknown" if Contact.objects.filter(connection__identity=message.connection.identity).exists(): message.connection.name = Contact.objects.get(connection__identity=message.connection.identity).name # prepare for the message table titles = [_("Text"), _("Direction"), _("Phone number"), _("Status"), _("Time")] table = read_only_message_table(messages, titles) return render_to_response( "polls/poll_dashboard.html", {"polls": polls, "data_collections": data_collections, "reply_form": reply_form, "messages_table": table}, context_instance=RequestContext(req), )
def send_password(self): # generate a one time use password password = User.objects.make_random_password( length=6, allowed_chars='1234567890') self.set_password(password) self.save() # send the SMS out (backend, created) = Backend.objects.get_or_create(name='mtn_3071') (connection, created) = Connection.objects.get_or_create(backend=backend, identity=self.username) get_router().add_outgoing( connection, "Your motome password is: %s %s %s" % (password[:2], password[2:4], password[4:]))
def send_reminders_for_wetmills(xform, wetmills, context, default_text): router = get_router() # for each wetmill for wetmill in wetmills: context['wetmill'] = wetmill # send to all accountants for accountant in Accountant.objects.filter(wetmill=wetmill): # activate our language if there is one trans_real.activate(accountant.language) text = Blurb.get(xform, 'accountant-reminder', context, default_text) # and send it off router.add_outgoing(accountant.connection, text) # and all observers for observer in WetmillObserver.objects.filter(wetmill=wetmill): # activate our language if there is one trans_real.activate(observer.language) text = Blurb.get(xform, 'observer-reminder', context, default_text) # and send it off router.add_outgoing(observer.connection, text) activate('en-us')
def testRouter(self): router = get_router() msg = OutgoingMessage(self.connection, "test") db_msg = router.handle_outgoing(msg) # assert a db message was created self.assertTrue(db_msg.pk) self.assertEqual(db_msg.text, "test") self.assertEqual(db_msg.direction, "O") self.assertEqual(db_msg.connection, self.connection) self.assertEqual(db_msg.status, 'Q') # check our queue msgs = Message.objects.filter(status='Q') self.assertEqual(1, len(msgs)) # now mark the message as delivered router.mark_delivered(db_msg.pk) # load it back up db_msg = Message.objects.get(id=db_msg.pk) # assert it looks ok now self.assertEqual(db_msg.text, "test") self.assertEqual(db_msg.direction, 'O') self.assertEqual(db_msg.connection, self.connection) self.assertEqual(db_msg.status, 'D')
def send(self, wetmill_chosen, season): """ send the message to all connections linked to a broadcast object """ router = get_router() now = datetime.now() msg_recipients = self.get_recipients_for_wetmill(wetmill_chosen) # for each recipient, render the message for recipient in msg_recipients: try: message_text = self.render(wetmill_chosen, season, recipient, now) # ignore messages that have no content (if statements make this possible) if message_text: db_message = router.add_outgoing(recipient.connection, message_text) self.messages.add(db_message) self.report_seasons.add(season) self.wetmills.add(wetmill_chosen) except Exception as e: print("Error sending end of season messages: %d for recipient: %d and wetmill %d" % (self.name, recipient.id, wetmill_chosen.id), e) self.save()
def fake_incoming_with_date(self, message, connection, date): router = get_router() handled = router.handle_incoming(connection.backend.name, connection.identity, message) for response in handled.poll_responses.all(): response.date = date response.save()
def sendSMS(self, msg, connection=None): if not connection: connection = self.conn1 router = get_router() db_msg = router.handle_incoming(connection.backend.name, connection.identity, msg) return db_msg
def demo(req, poll_id): poll = get_object_or_404(Poll, pk=poll_id) (b1, created) = Backend.objects.get_or_create(name='yo') # Terra (c1, created) = \ Connection.objects.get_or_create(identity='256785137868', defaults={'backend': b1}) # Sharad (b2, created) = Backend.objects.get_or_create(name='utl') (c2, created) = \ Connection.objects.get_or_create(identity='256717171100', defaults={'backend': b2}) router = get_router() outgoing = OutgoingMessage(c1, "dear Bulambuli representative: uReport, Uganda's community-level monitoring system, shows that 75% of young reporters in your district found that their local water point IS NOT functioning." ) router.handle_outgoing(outgoing) outgoing = OutgoingMessage(c2, "dear Amuru representative: uReport, Uganda's community-level monitoring system, shows that 46.7% of young reporters in your district found that their local water point IS NOT functioning." ) router.handle_outgoing(outgoing) return HttpResponse(status=200)
def handle(self, **options): #file1=open("/home/mossplix/log_8.txt") file2=open("/home/mossplix/incoming2.log") files=[file2] num=re.compile('([0-9]+)') for f in files: lines=f.readlines() for line in lines: parts=line.strip().rsplit('[FID:]')[1].split('] [') identity=num.search(parts[1]).groups()[0] message_text=parts[4].split(':')[2] try: connection=Connection.objects.get(identity=identity) msg=Message.objects.filter(connection__identity=identity,text__icontains=message_text,direction="I") if msg.exists(): pass else: router=get_router() router.handle_incoming(connection.backend.name, connection.identity, message_text) # with open("/home/mossplix/desc.log", "r+") as f: # old = f.read() # read everything in the file # f.seek(0) # rewind # f.write(line + old) # msg=Message.objects.create(connection__identity=identity,text=message_text,direction="I") # print "created "+msg.text # if poll.objects.filter(pk=connection.contact.pk): # poll.process_response(msg) except Connection.DoesNotExist: pass
def testAppCancel(self): router = get_router() class CancelApp(AppBase): # cancel outgoing phases by returning True def outgoing(self, msg): return False @property def name(self): return "ReplyApp" try: router.apps.append(CancelApp(router)) msg = OutgoingMessage(self.connection, "test") db_msg = router.handle_outgoing(msg) # assert a db message was created, but also cancelled self.assertTrue(db_msg.pk) self.assertEqual(db_msg.text, "test") self.assertEqual(db_msg.direction, "O") self.assertEqual(db_msg.connection, self.connection) self.assertEqual(db_msg.status, 'C') finally: router.apps = []
def setUp(self): """ Create a dummy connection """ self.backend = Backend.objects.create(name='test') self.connection = Connection.objects.create(identity='11235811', backend=self.backend) self.connection1 = Connection.objects.create(identity='4162549', backend=self.backend) self.connection2 = Connection.objects.create(identity='82764125', backend=self.backend) self.connection3 = Connection.objects.create(identity='256777773260', backend=self.backend) self.connection4 = Connection.objects.create(identity='25677771234', backend=self.backend) self.user, created = User.objects.get_or_create(username="******") self.router = get_router() #create test contact self.connection.contact = Contact.objects.create(name='Anonymous User') self.connection.save() #create message flags word_list = ['zombies', 'inferi', 'waves', 'living dead', 'monsters'] for word in word_list: flag = Flag.objects.create(name=word) Flag.objects.create(name="jedi", words="luke,sky,walker,jedi", rule=2) #create test group self.gem_group = Group.objects.create(name="GEM") Location.objects.create(name="kampala", type=LocationType.objects.create( name="district", slug="district"))
def send(self): """ send the message to all connections linked to a broadcast object """ router = get_router() now = datetime.now() for wetmill in self.get_wetmills(): recipients = self.get_recipients_for_wetmill(wetmill) # for each recipient, render the message for recipient in recipients: try: message_text = self.render(wetmill, recipient, now) # ignore messages that have no content (if statements make this possible) if message_text: db_message = router.add_outgoing( recipient.connection, message_text) self.messages.add(db_message) except Exception as e: #pragma: no cover print( "Error sending broadcast: %d for recipient: %d and wetmill %d" % (self.id, recipient.id, wetmill.id), e) self.sent = True self.save()
def approve(request,payment_pk): from requests.auth import HTTPBasicAuth payment=MobilePayment.objects.get(pk=payment_pk) s = requests.Session() s.auth = (settings.USERNAME, settings.PASSWORD) s.headers.update({'x-test': 'true'}) payment.approved=True payment.save() client=payment.client loan=MLoan.objects.get(client=client) no_ofpayements=loan.term_frequency principal=int(loan.principal_amount) loan_officer=loan.loan_officer_id payements_count=MNote.objects.filter(loan_id=loan.id,client_id=client.id).count() next_payement=MLoanRepaymentSchedule.objects.filter(installment=payements_count+1)[0] pm=int(MLoanRepaymentSchedule.objects.filter(loan_id=loan.id)[0].principal_amount) balance=(no_ofpayements-(payements_count+1))*pm message="Thanks %s for your payment of %d on %s. Your remaining balance is %d and your next payment is due %s"%(client.firstname,payment.amount,payment.created.strftime("%d %b %Y"),balance,next_payement.duedate.strftime("%d %b")) post_url=settings.BASE_URL+"loans/%d/transactions?tenantIdentifier=default&command=repayment"%loan.id headers={"Content-type": "application/json"} now=datetime.datetime.now() post_dict={"locale": "en_GB","accountNumber": "%s"%payment.client.account_no,"dateFormat": "dd MMMM yyyy","transactionDate": "%s"%now.strftime("%d %b %Y"),"transactionAmount": "%d"%payment.amount,"note": "Mobile Payment"} r=requests.post(post_url,json.dumps(dict(post_dict)),verify=False,headers=headers,auth=HTTPBasicAuth(settings.USERNAME, settings.PASSWORD),) router = get_router() backend, created = Backend.objects.get_or_create(name="mifos") connection, created = Connection.objects.get_or_create(backend=backend, identity=payment.sender) msg1 = router.add_outgoing(connection, message) return HttpResponse(r.text)
def handle(self, **options): num = re.compile(r'(\d+)') router = get_router() file = options['f'] log = open(file) lines = log.readlines() for line in lines: parts = line.split() date = dateutil.parser.parse(parts[0]) url = parts[-1].strip()[1:-1] url_parts = urlparse.urlparse(url) incoming = urlparse.parse_qs(url_parts.query) try: id_parts = num.split(incoming['sender'][0]) id = id_parts[1] if not Message.objects.filter(direction="I", text=incoming['message'][0], connection__identity=id, date__gte=date): router.handle_incoming(incoming['backend'][0], id, incoming['message'][0]) print incoming except (IndexError, KeyError): pass
def fake_incoming(self, message, connection=None): if connection is None: connection = self.connection router = get_router() handled = router.handle_incoming(connection.backend.name, connection.identity, message) return handled
def demo(req, poll_id): poll = get_object_or_404(Poll, pk=poll_id) (b1, created) = Backend.objects.get_or_create(name='dmark') # Terra (c1, created) = \ Connection.objects.get_or_create(identity='256785137868', defaults={'backend': b1}) # Sharad (b2, created) = Backend.objects.get_or_create(name='utl') (c2, created) = \ Connection.objects.get_or_create(identity='256717171100', defaults={'backend': b2}) router = get_router() outgoing = OutgoingMessage(c1, "dear Bulambuli representative: uReport, Uganda's community-level monitoring system, shows that 75% of young reporters in your district found that their local water point IS NOT functioning." ) router.handle_outgoing(outgoing) outgoing = OutgoingMessage(c2, "dear Amuru representative: uReport, Uganda's community-level monitoring system, shows that 46.7% of young reporters in your district found that their local water point IS NOT functioning." ) router.handle_outgoing(outgoing) return HttpResponse(status=200)
def setUp(self): """ Create a dummy connection """ self.backend = Backend.objects.create(name='test') self.connection = Connection.objects.create(identity='11235811', backend=self.backend) self.connection1 = Connection.objects.create(identity='4162549', backend=self.backend) self.connection2 = Connection.objects.create(identity='82764125', backend=self.backend) self.connection3 = Connection.objects.create(identity='256777773260', backend=self.backend) self.user,created=User.objects.get_or_create(username="******") self.router=get_router() #create test contact self.connection.contact = Contact.objects.create(name='Anonymous User') self.connection.save() #create message flags word_list=['zombies','inferi','waves','living dead','monsters'] for word in word_list: flag=Flag.objects.create(name=word) Flag.objects.create(name="jedi",words="luke,sky,walker,jedi",rule=2) #create test group self.gem_group=Group.objects.create(name="GEM") Location.objects.create(name="kampala",type=LocationType.objects.create(name="district",slug="district"))
def view_message_history(request, connection_id): """ This view lists all (sms message) correspondence between RapidSMS and a User """ direction_choices = DIRECTION_CHOICES status_choices = STATUS_CHOICES reply_form = ReplyForm() connection = get_object_or_404(Connection, pk=connection_id) if connection.contact: messages = Message.objects.filter(connection__contact=connection.contact) else: messages = Message.objects.filter(connection=connection) messages = messages.order_by('-date') total_incoming = messages.filter(direction="I").count() total_outgoing = messages.filter(direction="O").count() latest_message = None if total_incoming: latest_message = messages.filter(direction="I").latest('date') if request.method == 'POST': reply_form = ReplyForm(request.POST) if reply_form.is_valid(): if Connection.objects.filter(identity=reply_form.cleaned_data['recipient']).count(): text = reply_form.cleaned_data.get('message') conn = Connection.objects.filter(identity=reply_form.cleaned_data['recipient'])[0] in_response_to = reply_form.cleaned_data['in_response_to'] outgoing = OutgoingMessage(conn, text) get_router().handle_outgoing(outgoing, in_response_to) return redirect("/contact/%d/message_history/" % connection.pk) else: reply_form.errors.setdefault('short_description', ErrorList()) reply_form.errors['recipient'].append("This number isn't in the system") return render_to_response("contact/message_history.html", { "messages": messages, "stats_latest_message": latest_message, "stats_total_incoming": total_incoming, "stats_total_outgoing": total_outgoing, "connection": connection, "direction_choices": direction_choices, "status_choices": status_choices, "replyForm": reply_form }, context_instance=RequestContext(request))
def fake_incoming_with_date(self, message, connection, date): router = get_router() handled = router.handle_incoming(connection.backend.name, connection.identity, message) for response in handled.poll_responses.all(): response.date = date response.save() return handled
def fake_incoming(self, message, connection=None): if connection is None: connection = self.connection router = get_router() router.handle_incoming(connection.backend.name, connection.identity, message) form = XForm.find_form(message) if form: return XFormSubmission.objects.all().order_by('-created')[0]
def handle(self, **options): phone = options["phone"] or raw_input("Phone number you wish the message to appear to come from: ") text = options["text"] or raw_input("Text of the message: ") connection = Connection.objects.get(identity=phone) router = get_router() handled = router.handle_incoming(connection.backend.name, connection.identity, text) self.stdout.write("Done!\n")
def get_backend_class(self, backend_config, backend_name): path = backend_config["ENGINE"] module_name, class_name = path.rsplit('.', 1) module = __import__(module_name, globals(), locals(), [class_name]) backend_class = getattr(module, class_name) router = get_router() backend = backend_class(router, backend_name, **backend_config) return backend
def handle(self, **options): phone = options['phone'] or raw_input( 'Phone number you wish the message to appear to come from: ') text = options['text'] or raw_input('Text of the message: ') connection = Connection.objects.get(identity=phone) router = get_router() handled = router.handle_incoming(connection.backend.name, connection.identity, text) self.stdout.write('Done!\n')
def dashboard(req): """ dashboard for viewing poll status and incoming / outgoing messages """ if req.method.upper() == 'GET': reply_form = ReplyForm() elif req.POST['action'].upper() == 'REPLY': reply_form = ReplyForm(req.POST) if reply_form.is_valid(): if Connection.objects.filter(identity=reply_form.cleaned_data['recipient']).count(): text = reply_form.cleaned_data['message'] try: # if the contact is in the database perform a mailmerge conn = Connection.objects.filter(identity=reply_form.cleaned_data['recipient'])[0] text = _mail_merge(Contact.objects.get(connection__identity=conn.identity), text) except: pass outgoing = OutgoingMessage(conn, text) get_router().handle_outgoing(outgoing) else: reply_form.errors.setdefault('short_description', ErrorList()) reply_form.errors['recipient'].append("This number isn't in the system") polls = Poll.objects.annotate(Count('responses')).order_by('start_date')[:5] data_collections = XForm.objects.annotate(Count('submissions')).order_by('created')[:5] messages = Message.objects.all().order_by('-date')[0:10] # get some real names per connection for message in messages: message.connection.name = "Unknown" if Contact.objects.filter(connection__identity=message.connection.identity).exists(): message.connection.name = Contact.objects.get(connection__identity=message.connection.identity).name # prepare for the message table titles = ["Text", "Direction", "Phone number", "Status", "Time"] table = read_only_message_table(messages, titles) return render_to_response( "polls/poll_dashboard.html", {"polls": polls, "data_collections": data_collections, "reply_form": reply_form, "messages_table": table}, context_instance=RequestContext(req))
def post(self, *args, **kwargs): # valid form, then process the message form = MessageTesterForm(self.request.POST) if form.is_valid(): message = get_router().handle_incoming(form.cleaned_data.get('backend', 'tester'), form.cleaned_data['sender'], form.cleaned_data['text']) # and off we go return HttpResponseRedirect(reverse('console.message_list') + "?backend_id=%d" % message.connection.backend.id) return self.get(*args, **kwargs)
def setUp(self): (self.backend, created) = Backend.objects.get_or_create(name="test_backend") (self.connection, created) = Connection.objects.get_or_create(backend=self.backend, identity='2067799294') # add an echo app class EchoApp(AppBase): def handle(self, msg): msg.respond("echo %s" % msg.text) return True router = get_router() router.apps.append(EchoApp(router))
def handle(self, **options): if len(sys.argv) < 2: sys.stderr.write('number message\n') sys.exit(1) con, _ = Connection.objects.get_or_create(identity = options.get('num', '256772344681'), backend = Backend.objects.get_or_create(name = 'TestBackend')[0]) r = get_router() lp = Message.objects.order_by('-pk')[0].pk r.handle_incoming(con.backend.name, con.identity, options.get('text', 'EMPTY')) for m in Message.objects.filter(pk__gt = lp): print m print '==' * 12
def perform(self, request, results): if not request.user.has_perm('status160.add_alert'): return ("You don't have permission to send alerts!", 'error',) try: alert = Alert.objects.latest('sent') td = datetime.datetime.now() - alert.sent total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 # don't spam like crazy if (total_seconds < 900): return ('An alert was sent in the past 15 minutes, please try later.', 'error',) except Alert.DoesNotExist: # first alert can be sent whenever pass alert = Alert() alert.save() for warden in WardenRelationship.objects.all(): outstanding = [] for dependent in warden.dependents.all(): status_num = status(dependent, 'priority') if int(status_num) < 3: outstanding.append((dependent, status_num)) if (len(outstanding)): outstanding = sorted(outstanding, key=itemgetter(1), reverse=True) smstext = "%s persons still unaccounted for/unsafe:" % str(len(outstanding)) text = smstext toadd = '' off = 0 while (len(text) < 476) and (off < len(outstanding)): smstext = text if outstanding[off][0].default_connection: text += "%s(%s)" % (outstanding[off][0].name, outstanding[off][0].default_connection.identity) else: text +="%s" % outstanding[off][0].name if off < (len(outstanding) - 1): text += ',' off += 1 if off == len(outstanding) and len(text) < 476: smstext = text if off < len(outstanding): smstext += '...' router = get_router() for conn in Connection.objects.filter(contact=warden.warden): outgoing = OutgoingMessage(conn, smstext) router.handle_outgoing(outgoing) return ('Alerts sent!', 'success',)
def post(self, *args, **kwargs): # valid form, then process the message form = MessageTesterForm(self.request.POST) if form.is_valid(): message = get_router().handle_incoming( "console", form.cleaned_data["sender"], form.cleaned_data["text"] ) # and off we go self.object_list = self.get_queryset() context = self.get_context_data(object_list=self.object_list) return self.render_to_response(context)
def post(self, *args, **kwargs): # valid form, then process the message form = MessageTesterForm(self.request.POST) if form.is_valid(): message = get_router().handle_incoming( 'console', form.cleaned_data['sender'], form.cleaned_data['text']) # and off we go self.object_list = self.get_queryset() context = self.get_context_data(object_list=self.object_list) return self.render_to_response(context)
def testNoRouterURL(self): # send something off router = get_router() # tests that messages are correctly build msg1 = router.add_outgoing(self.connection, "test") # sleep a teeny bit to let it send self.assertEquals('test_backend', msg1.connection.backend.name) self.assertEquals('2067799294', msg1.connection.identity) self.assertEquals('test', msg1.text) self.assertEquals('O', msg1.direction) self.assertEquals('Q', msg1.status)
def post(self, *args, **kwargs): # valid form, then process the message form = MessageTesterForm(self.request.POST) if form.is_valid(): message = get_router().handle_incoming( form.cleaned_data.get('backend', 'tester'), form.cleaned_data['sender'], form.cleaned_data['text']) # and off we go return HttpResponseRedirect( reverse('console.message_list') + "?backend_id=%d" % message.connection.backend.id) return self.get(*args, **kwargs)
def testAppReply(self): router = get_router() class ReplyApp(AppBase): def handle(self, msg): # make sure a db message was given to us if not msg.db_message: raise Exception("ReplyApp was not handed a db message") # and trigger a reply msg.respond("reply") # return that we handled it return True @property def name(self): return "ReplyApp" class ExceptionApp(AppBase): def handle(self, msg): raise Exception("handle() process was not shortcut by ReplyApp returning True") try: router.apps.append(ReplyApp(router)) router.apps.append(ExceptionApp(router)) db_msg = router.handle_incoming(self.backend.name, self.connection.identity, "test send") # assert a db message was created and handled self.assertTrue(db_msg.pk) self.assertEqual(db_msg.text, "test send") self.assertEqual(db_msg.direction, "I") self.assertEqual(db_msg.connection, self.connection) self.assertEqual(db_msg.status, 'H') # assert that a response was associated responses = db_msg.responses.all() self.assertEqual(1, len(responses)) response = responses[0] self.assertEqual(response.text, "reply") self.assertEqual(response.direction, "O") self.assertEqual(response.connection, self.connection) self.assertEqual(response.status, "Q") finally: router.apps = []
def perform(self, request, results): if results is None or len(results) == 0: return ('A message must have one or more recipients!', 'error') if request.user and request.user.has_perm('contact.can_message'): router = get_router() text = self.cleaned_data['text'] start_sending_mass_messages() for msg in results: outgoing = OutgoingMessage(msg.connection, text) router.handle_outgoing(outgoing, msg) stop_sending_mass_messages() return ('%d messages sent successfully' % results.count(), 'success',) else: return ("You don't have permission to send messages!", 'error',)
def approve(request, payment_pk): from requests.auth import HTTPBasicAuth payment = MobilePayment.objects.get(pk=payment_pk) s = requests.Session() s.auth = (settings.USERNAME, settings.PASSWORD) s.headers.update({'x-test': 'true'}) payment.approved = True payment.save() client = payment.client loan = MLoan.objects.get(client=client) no_ofpayements = loan.term_frequency principal = int(loan.principal_amount) loan_officer = loan.loan_officer_id payements_count = MNote.objects.filter(loan_id=loan.id, client_id=client.id).count() next_payement = MLoanRepaymentSchedule.objects.filter( installment=payements_count + 1)[0] pm = int( MLoanRepaymentSchedule.objects.filter( loan_id=loan.id)[0].principal_amount) balance = (no_ofpayements - (payements_count + 1)) * pm message = "Thanks %s for your payment of %d on %s. Your remaining balance is %d and your next payment is due %s" % ( client.firstname, payment.amount, payment.created.strftime("%d %b %Y"), balance, next_payement.duedate.strftime("%d %b")) post_url = settings.BASE_URL + "loans/%d/transactions?tenantIdentifier=default&command=repayment" % loan.id headers = {"Content-type": "application/json"} now = datetime.datetime.now() post_dict = { "locale": "en_GB", "accountNumber": "%s" % payment.client.account_no, "dateFormat": "dd MMMM yyyy", "transactionDate": "%s" % now.strftime("%d %b %Y"), "transactionAmount": "%d" % payment.amount, "note": "Mobile Payment" } r = requests.post( post_url, json.dumps(dict(post_dict)), verify=False, headers=headers, auth=HTTPBasicAuth(settings.USERNAME, settings.PASSWORD), ) router = get_router() backend, created = Backend.objects.get_or_create(name="mifos") connection, created = Connection.objects.get_or_create( backend=backend, identity=payment.sender) msg1 = router.add_outgoing(connection, message) return HttpResponse(r.text)
def start(self): """ This starts the poll: outgoing messages are sent to all the contacts registered with this poll, and the start date is updated accordingly. All incoming messages from these users will be considered as potentially a response to this poll. """ self.start_date = datetime.datetime.now() self.save() router = get_router() for contact in self.contacts.all(): for connection in Connection.objects.filter(contact=contact): outgoing = OutgoingMessage(connection, self.question) self.messages.add(router.handle_outgoing(outgoing)) pass
def demo(req, poll_id): b1, created = Backend.objects.get_or_create(name="dmark") # Terra c1, created = Connection.objects.get_or_create(identity="256785137868", defaults={ 'backend': b1, }) # Sharad b2, created = Backend.objects.get_or_create(name="utl") c2, created = Connection.objects.get_or_create(identity="256717171100", defaults={ 'backend': b2, }) router = get_router() outgoing = OutgoingMessage(c1, "dear Bulambuli representative: uReport, Uganda's community-level monitoring system, shows that 75% of young reporters in your district found that their local water point IS NOT functioning.") router.handle_outgoing(outgoing) outgoing = OutgoingMessage(c2, "dear Amuru representative: uReport, Uganda's community-level monitoring system, shows that 46.7% of young reporters in your district found that their local water point IS NOT functioning.") router.handle_outgoing(outgoing) return HttpResponse(status=200)
def send_messages(request): mform=MessageForm() if request.method == 'POST': mform = MessageForm(request.POST) if mform.is_valid(): contacts=mform.cleaned_data['contacts'] message=mform.cleaned_data['text'] router = get_router() backend, created = Backend.objects.get_or_create(name="mifos") for m in contacts: try: connection, created = Connection.objects.get_or_create(backend=backend, identity=clean_number(m.external_id)) router.add_outgoing(connection, message) except AttributeError: pass return render_to_response("relay/contacts.html",{'mform':mform,'status':'Messages Sent'}) return render_to_response("relay/contacts.html",{'mform':mform},context_instance=RequestContext(request))
def testRouterDictURL(self): # set our router URL settings.ROUTER_URL = { "default": "http://mykannel.com/cgi-bin/sendsms?from=1234&text=%(text)s&to=%(recipient)s&smsc=%(backend)s&id=%(id)s", "test_backend2": "http://mykannel2.com/cgi-bin/sendsms?from=1234&text=%(text)s&to=%(recipient)s&smsc=%(backend)s&id=%(id)s" } # monkey patch the router's fetch_url request def test_fetch_url(self, url): test_fetch_url.url = url return 200 router = get_router() msg1 = router.add_outgoing(self.connection, "test") # sleep to let our sending thread take care of things # TODO: this is pretty fragile but good enough for now time.sleep(2) msg1 = Message.objects.get(id=msg1.id) self.assertEquals('O', msg1.direction) self.assertEquals('S', msg1.status) # check whether our url was set right self.assertEquals( "http://mykannel.com/cgi-bin/sendsms?from=1234&text=test&to=2067799294&smsc=test_backend&id=%d" % msg1.id, test_fetch_url.url) # now send to our other backend msg2 = router.add_outgoing(self.connection2, "test2") # sleep to let our sending thread take care of things # TODO: this is pretty fragile but good enough for now time.sleep(2) msg2 = Message.objects.get(id=msg2.id) self.assertEquals('O', msg2.direction) self.assertEquals('S', msg2.status) # check whether our url was set right again self.assertEquals( "http://mykannel2.com/cgi-bin/sendsms?from=1234&text=test2&to=2067799291&smsc=test_backend2&id=%d" % msg2.id, test_fetch_url.url)
def receive(text, connection, **kwargs): """ Creates an incoming message and passes it to the router for processing. :param text: text message :param connection: RapidSMS :py:class:`~rapidsms.models.Connection` object :param kwargs: Extra kwargs to pass to :py:class:`~rapidsms.messages.incoming.IncomingMessage` constructor :returns: :py:class:`~rapidsms.messages.incoming.IncomingMessage` object constructed by router. A returned message object does not indicate that router processing has finished or even started, as this depends on the router defined in :setting:`RAPIDSMS_ROUTER`. :rtype: :py:class:`~rapidsms.messages.incoming.IncomingMessage` """ router = get_router() message = IncomingMessage(connection, text) router.handle_incoming(connection.backend, connection.identity, text) return message
def setUp(self): """ Create a dummy connection """ self.backend = Backend.objects.create(name='test') self.connection = Connection.objects.create(identity='8675309', backend=self.backend) self.user, _ = User.objects.get_or_create(username="******") self.router = get_router() # create test contact self.connection.contact = Contact.objects.create(name='Anonymous User') self.connection.save() Location.objects.create(name="Busia", type=LocationType.objects.create(name="district", slug="district")) Location.objects.create(name="Gwinnett", type=LocationType.objects.create(name="sub_county", slug="sub_county")) # call_command('create_hotline_script') call_command('create_script')
def bulksend(request): if request.method.upper() == 'GET': return render_to_response( "bulksend/dashboard.html", { "groups": Group.objects.all(), "sms_cost":k_SMSPrice, "sms_length":k_SMSLength, }, context_instance=RequestContext(request) ) elif request.method.upper() == 'POST': text = _sanitize_text(request.POST.get('message')) group_id = request.POST.get('group_id') group = Group.objects.get(pk=group_id) # Kickin' it ol'school #import datetime #print datetime.datetime.now() #for contact in group.contacts.all(): # connection = contact.connection_set.all()[0] # post = {"connection_id": unicode(connection.id), "text": text} # call_router("messaging", "send_message", **post) #print datetime.datetime.now() # The leaders of the New School router = get_router() for contact in group.contacts.all(): connection = contact.connection_set.all()[0] outgoing = OutgoingMessage(connection, _mail_merge(contact, text)) router.handle_outgoing(outgoing) messages.success(request, 'Thank you, you successfully sent your bulk message.') return render_to_response( "bulksend/dashboard.html", { "groups": Group.objects.all(), "sms_cost":k_SMSPrice, "sms_length":k_SMSLength, }, context_instance=RequestContext(request) )
def perform(self, request, results): if results is None or len(results) == 0: return ('A message must have one or more recipients!', 'error') if request.user and request.user.has_perm('contact.can_message'): router = get_router() text = self.cleaned_data['text'] start_sending_mass_messages() for msg in results: outgoing = OutgoingMessage(msg.connection, text) router.handle_outgoing(outgoing, msg) stop_sending_mass_messages() return ( '%d messages sent successfully' % results.count(), 'success', ) else: return ( "You don't have permission to send messages!", 'error', )
def send_messages(request): mform = MessageForm() if request.method == 'POST': mform = MessageForm(request.POST) if mform.is_valid(): contacts = mform.cleaned_data['contacts'] message = mform.cleaned_data['text'] router = get_router() backend, created = Backend.objects.get_or_create(name="mifos") for m in contacts: try: connection, created = Connection.objects.get_or_create( backend=backend, identity=clean_number(m.external_id)) router.add_outgoing(connection, message) except AttributeError: pass return render_to_response("relay/contacts.html", { 'mform': mform, 'status': 'Messages Sent' }) return render_to_response("relay/contacts.html", {'mform': mform}, context_instance=RequestContext(request))
def handle(self, **options): #file1=open("/home/mossplix/log_8.txt") file2 = open("/home/mossplix/incoming2.log") files = [file2] num = re.compile('([0-9]+)') for f in files: lines = f.readlines() for line in lines: parts = line.strip().rsplit('[FID:]')[1].split('] [') identity = num.search(parts[1]).groups()[0] message_text = parts[4].split(':')[2] try: connection = Connection.objects.get(identity=identity) msg = Message.objects.filter(connection__identity=identity, text__icontains=message_text, direction="I") if msg.exists(): pass else: router = get_router() router.handle_incoming(connection.backend.name, connection.identity, message_text) # with open("/home/mossplix/desc.log", "r+") as f: # old = f.read() # read everything in the file # f.seek(0) # rewind # f.write(line + old) # msg=Message.objects.create(connection__identity=identity,text=message_text,direction="I") # print "created "+msg.text # if poll.objects.filter(pk=connection.contact.pk): # poll.process_response(msg) except Connection.DoesNotExist: pass
def handle(self, **options): num = re.compile(r'(\d+)') router = get_router() file = options['f'] log = open(file) lines = log.readlines() for line in lines: parts = line.split() date = dateutil.parser.parse(parts[0] + " " + parts[1]) try: id_parts = num.split(parts[9]) id = id_parts[1] message = parts[12].rsplit(":")[2][:-1] backend = parts[4].split(':')[1][:-1] if not Message.objects.filter(direction="I", text=message, connection__identity=id, date__gte=date): router.handle_incoming(backend, id, message) except (IndexError, KeyError): pass
def process_report(self, message): handle_incoming.delay(get_router(), self.backend, self.user_address, message)
def create_fake_response(connection, incoming_message): router = get_router() incoming = router.handle_incoming(connection.backend.name, connection.identity, incoming_message) return incoming
def setUp(self): #call_command("loaddata","locations.json") user, created = User.objects.get_or_create(username='******') self.user = user site = Site.objects.get_or_create(pk=settings.SITE_ID, defaults={ 'domain': 'example.com', }) self.router = get_router() contact1, _ = Contact.objects.get_or_create(name="foo") contact2, _ = Contact.objects.get_or_create(name="foo2") backend, _ = Backend.objects.get_or_create(name='TEST') self.connection1, _ = Connection.objects.get_or_create( identity='80001', backend=backend) self.connection2, _ = Connection.objects.get_or_create( identity='80002', backend=backend) self.connection3, _ = Connection.objects.get_or_create( identity='80004', backend=backend) self.connection4, _ = Connection.objects.get_or_create( identity='80005', backend=backend) self.connection5, _ = Connection.objects.get_or_create( identity='80006', backend=backend) self.connection6, _ = Connection.objects.get_or_create( identity='80007', backend=backend) script = Script.objects.get(slug="ntd_autoreg") self.script = script script.sites.add(Site.objects.get_current()) poll1, _ = Poll.objects.get_or_create(name='ntds_parish', type=Poll.TYPE_TEXT, question='What is your Parish?', default_response='', user=user) poll2, _ = Poll.objects.get_or_create( name='ntds_subcounty', type=Poll.TYPE_TEXT, question='What is your Subcounty?', default_response='', user=user) poll3, _ = Poll.objects.get_or_create( name='ntds_district', type=Poll.TYPE_TEXT, question='What is your district?', default_response='', user=user) step1, _ = ScriptStep.objects.get_or_create( script=script, message="Welcome to NTDs Mass drug administration program", order=0, rule=ScriptStep.WAIT_MOVEON, start_offset=0, giveup_offset=0, ) script.steps.add(step1) step2, _ = ScriptStep.objects.get_or_create( script=script, poll=poll1, order=1, rule=ScriptStep.WAIT_MOVEON, start_offset=0, giveup_offset=8640000, ) script.steps.add(step2) step3, _ = ScriptStep.objects.get_or_create( script=script, poll=poll2, order=2, rule=ScriptStep.WAIT_MOVEON, start_offset=0, giveup_offset=8640000, ) script.steps.add(step3) step4, _ = ScriptStep.objects.get_or_create( script=script, poll=poll3, order=3, rule=ScriptStep.WAIT_MOVEON, start_offset=0, giveup_offset=8640000, ) script.steps.add(step4) OptinWord.objects.get_or_create(language="en", words="ntds") self.reg_xform, _ = XForm.on_site.get_or_create( name='ntd_parish', keyword='par', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response= "The parish has been set to {{ parish }}. Please send the data for it" ) f1, _ = self.reg_xform.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Reporting Parish', command='parish', order=0) self.villages_targeted, _ = XForm.on_site.get_or_create( name='ntd_villages_targeted', keyword='vlg', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Vilages in Parish', command='vlg_no', order=0) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Vilages Targeted', command='vlg_tgt', order=1) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Vilages Treated', command='vlg_trd', order=2) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Vilages Incomplete', command='vlg_incpt', order=3) self.villages_targeted, _ = XForm.on_site.get_or_create( name='ntd_schools_targeted', keyword='sch', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Schools in Parish', command='sch_no', order=0) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Schools Targeted', command='sch_tgt', order=1) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Schools Treated', command='sch_trd', order=2) f1, _ = self.villages_targeted.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Schools Incomplete', command='sch_incpt', order=3) self.treated_by_age, _ = XForm.on_site.get_or_create( name='ntd_treated_by_age', keyword='agg', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated Less Than 6 Months male', command='trd_less_6month_male', order=0) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated Less Than 6 Months female', command='trd_less_6month_female', order=1) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated 6 Months to 4 years male', command='trd_6_to_4years_male', order=2) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated 6 Months to 4 years female', command='trd_6_to_4years_female', order=3) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated 5 to 14 male', command='trd_5_to_14_male', order=4) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated 5 to 14 female', command='trd_5_to_14_female', order=5) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated greater than 15 male', command='trd_greater_15_male', order=6) f1, _ = self.treated_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Treated greater than 15 female', command='trd_greater_15_female', order=7) self.village_population_by_age, _ = XForm.on_site.get_or_create( name='ntd_village_pop_by_age', keyword='pop', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop Less Than 6 Months male', command='pop_less_6month_male', order=0) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop Less Than 6 Months female', command='pop_less_6month_female', order=1) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop 6 Months to 4 years male', command='pop_6_to_4years_male', order=2) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop 6 Months to 4 years female', command='pop_6_to_4years_female', order=3) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop 5 to 14 male', command='pop_5_to_14_male', order=4) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop 5 to 14 female', command='pop_5_to_14_female', order=5) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop greater than 15 male', command='pop_greater_15_male', order=6) f1, _ = self.village_population_by_age.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Pop greater than 15 female', command='pop_greater_15_female', order=7) self.drugs_used, _ = XForm.on_site.get_or_create( name='ntd_drugs_used', keyword='dru', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='praziquantel', command='pzq', order=0) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='mebendazole', command='mbd', order=1) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='albendazole', command='alb', order=2) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='ivermectin', command='ivm', order=3) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='teo', command='tetracycline', order=4) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Zithromax syrup', command='zith_syr', order=5) f1, _ = self.drugs_used.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Zithromax tabs', command='zith_tabs', order=6) self.drugs_leftover, _ = XForm.on_site.get_or_create( name='ntd_drugs_left', keyword='drl', owner=self.user, command_prefix=None, separator='.', site=Site.objects.get_current(), response='Thanks for your report') f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='praziquantel', command='pzq', order=0) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='mebendazole', command='mbd', order=1) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='albendazole', command='alb', order=2) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='ivermectin', command='ivm', order=3) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='teo', command='tetracycline', order=4) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Zithromax syrup', command='zith_syr', order=5) f1, _ = self.drugs_leftover.fields.get_or_create( field_type=XFormField.TYPE_TEXT, name='Zithromax tabs', command='zith_tabs', order=6)
def fakeIncoming(self, message, connection): self.router = get_router() self.router.handle_incoming(connection.backend.name, connection.identity, message)
def fake_incoming(self, message, reporter): router = get_router() connection = reporter.default_connection return router.handle_incoming(connection.backend.name, connection.identity, message)
(r'^admin/', include(admin.site.urls)), # RapidSMS core URLs (r'^account/', include('rapidsms.urls.login_logout')), url('^accounts/login', 'rapidsms.views.login', name="login"), url('^accounts/logout', 'rapidsms.views.logout', name="logout"), # RapidSMS contrib app URLs (r'^ajax/', include('rapidsms.contrib.ajax.urls')), (r'^export/', include('rapidsms.contrib.export.urls')), (r'^httptester/', include('rapidsms.contrib.httptester.urls')), (r'^locations/', include('rapidsms.contrib.locations.urls')), (r'^messaging/', include('rapidsms.contrib.messaging.urls')), (r'^registration/', include('auth.urls')), (r'^scheduler/', include('rapidsms.contrib.scheduler.urls')), (r'^polls/', include('poll.urls')), # testing excel export ) + router_urls + xform_urls + contact_urls + edtrac_urls if settings.DEBUG: urlpatterns += patterns('', # helper URLs file that automatically serves the 'static' folder in # INSTALLED_APPS via the Django static media server (NOT for use in # production) (r'^', include('rapidsms.urls.static_media')), ) from rapidsms_httprouter.router import get_router get_router(start_workers=True)
def send_message(self, connection, message): router = get_router() router.handle_incoming(connection.backend.name, connection.identity, message)
def fake_incoming(self, connection, incoming_message): router = get_router() return router.handle_incoming(connection.backend.name, connection.identity, incoming_message)