def smsSubmit(args): from messaging.sms import SmsSubmit from datetime import datetime text = ''.join(map(unichr, args["text_as_char_code_arr"])) sms = SmsSubmit(args["number"], text) if "csca" in args: sms.csca = args["csca"] if "validity" in args: sms.validity = datetime.strptime(args["validity"], "%a, %d %b %Y %H:%M:%S %Z") if "klass" in args: sms.klass = args["klass"] if "request_status" in args: sms.request_status = args["request_status"] out = [] for pdu in sms.to_pdu(): out.append(pdu.__dict__) return out
def to_pdu(self, store=False): """Returns the PDU representation of this message""" sms = SmsSubmit(self.number, self.text) sms.csca = self.csca sms.request_status = self.status_request if store: sms.validity = None return sms.to_pdu()
def test_encoding_validity(self): # no validity number = '2b3334363136353835313139'.decode('hex') text = "hola" expected = "0001000B914316565811F9000004E8373B0C" sms = SmsSubmit(number, text) sms.ref = 0x0 pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # absolute validity number = '2b3334363136353835313139'.decode('hex') text = "hola" expected = "0019000B914316565811F900000170520251930004E8373B0C" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = datetime(2010, 7, 25, 20, 15, 39) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # relative validity number = '2b3334363136353835313139'.decode('hex') text = "hola" expected = "0011000B914316565811F90000AA04E8373B0C" expected_len = 18 sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) self.assertEqual(pdu.length, expected_len)
def test_encoding_validity(self): # no validity number = "+34616585119" text = "hola" expected = "0001000B914316565811F9000004E8373B0C" sms = SmsSubmit(number, text) sms.ref = 0x0 pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # absolute validity number = "+34616585119" text = "hola" expected = "0019000B914316565811F900000170520251930004E8373B0C" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = datetime(2010, 7, 25, 20, 15, 39) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # relative validity number = "+34616585119" text = "hola" expected = "0011000B914316565811F90000AA04E8373B0C" expected_len = 18 sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) self.assertEqual(pdu.length, expected_len)
def test_encoding_multipart_7bit(self): # text encoded with umts-tools text = "Or walk with Kings - nor lose the common touch, if neither foes nor loving friends can hurt you, If all men count with you, but none too much; If you can fill the unforgiving minute With sixty seconds' worth of distance run, Yours is the Earth and everything thats in it, And - which is more - you will be a Man, my son" number = '363535333435363738'.decode('hex') expected = [ "005100098156355476F80000AAA00500038803019E72D03DCC5E83EE693A1AB44CBBCF73500BE47ECB41ECF7BC0CA2A3CBA0F1BBDD7EBB41F4777D8C6681D26690BB9CA6A3CB7290F95D9E83DC6F3988FDB6A7DD6790599E2EBBC973D038EC06A1EB723A28FFAEB340493328CC6683DA653768FCAEBBE9A07B9A8E06E5DF7516485CA783DC6F7719447FBF41EDFA18BD0325CDA0FCBB0E1A87DD", "005100098156355476F80000AAA005000388030240E6349B0DA2A3CBA0BADBFC969FD3F6B4FB0C6AA7DD757A19744DD3D1A0791A4FCF83E6E5F1DB4D9E9F40F7B79C8E06BDCD20727A4E0FBBC76590BCEE6681B2EFBA7C0E4ACF41747419540CCBE96850D84D0695ED65799E8E4EBBCF203A3A4C9F83D26E509ACE0205DD64500B7447A7C768507A0E6ABFE565500B947FD741F7349B0D129741", "005100098156355476F80000AA14050003880303C2A066D8CD02B5F3A0F9DB0D", ] sms = SmsSubmit(number, text) sms.ref = 0x0 sms.rand_id = 136 sms.validity = timedelta(days=4) ret = sms.to_pdu() cnt = len(ret) for i, pdu in enumerate(ret): self.assertEqual(pdu.pdu, expected[i]) self.assertEqual(pdu.seq, i + 1) self.assertEqual(pdu.cnt, cnt)
def test_encoding_multipart_7bit(self): # text encoded with umts-tools text = "Or walk with Kings - nor lose the common touch, if neither foes nor loving friends can hurt you, If all men count with you, but none too much; If you can fill the unforgiving minute With sixty seconds' worth of distance run, Yours is the Earth and everything thats in it, And - which is more - you will be a Man, my son" number = "655345678" expected = [ "005100098156355476F80000AAA00500038803019E72D03DCC5E83EE693A1AB44CBBCF73500BE47ECB41ECF7BC0CA2A3CBA0F1BBDD7EBB41F4777D8C6681D26690BB9CA6A3CB7290F95D9E83DC6F3988FDB6A7DD6790599E2EBBC973D038EC06A1EB723A28FFAEB340493328CC6683DA653768FCAEBBE9A07B9A8E06E5DF7516485CA783DC6F7719447FBF41EDFA18BD0325CDA0FCBB0E1A87DD", "005100098156355476F80000AAA005000388030240E6349B0DA2A3CBA0BADBFC969FD3F6B4FB0C6AA7DD757A19744DD3D1A0791A4FCF83E6E5F1DB4D9E9F40F7B79C8E06BDCD20727A4E0FBBC76590BCEE6681B2EFBA7C0E4ACF41747419540CCBE96850D84D0695ED65799E8E4EBBCF203A3A4C9F83D26E509ACE0205DD64500B7447A7C768507A0E6ABFE565500B947FD741F7349B0D129741", "005100098156355476F80000AA14050003880303C2A066D8CD02B5F3A0F9DB0D", ] sms = SmsSubmit(number, text) sms.ref = 0x0 sms.rand_id = 136 sms.validity = timedelta(days=4) ret = sms.to_pdu() cnt = len(ret) for i, pdu in enumerate(ret): self.assertEqual(pdu.pdu, expected[i]) self.assertEqual(pdu.seq, i + 1) self.assertEqual(pdu.cnt, cnt)
def test_encoding_multipart_7bit_egsm(self): # text encoded with umts-tools self.maxDiff = None text = '€' * 229 + 'x' number = binascii.unhexlify(b'363535333435363738').decode() expected = [ "005100098156355476F80000AAA005000388030136E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437", "005100098156355476F80000AAA0050003880302CA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA9BF2A6BC296FCA", "005100098156355476F80000AAA005000388030336E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE9437E54D7953DE94F1", ] sms = SmsSubmit(number, text) sms.ref = 0x0 sms.rand_id = 136 sms.validity = timedelta(days=4) ret = sms.to_pdu() cnt = len(ret) for i, pdu in enumerate(ret): self.assertEqual(pdu.pdu, expected[i]) self.assertEqual(pdu.seq, i + 1) self.assertEqual(pdu.cnt, cnt)
def test_encoding_ucs2_message(self): number = '2b3334363136353835313139'.decode('hex') text = u'あ叶葉' csca = '+34646456456' expected = "07914346466554F601000B914316565811F9000806304253F68449" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.csca = csca pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) text = u"Русский" number = '363535333435363738'.decode('hex') expected = "001100098156355476F80008AA0E0420044304410441043A04380439" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected)
def test_encoding_message_with_latin1_chars(self): # tested with pduspy.exe number = '2b3334363534313233343536'.decode('hex') text = u"Hölä" expected = "0011000B914356143254F60000AA04483E7B0F" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # tested with pduspy.exe number = '2b3334363534313233343536'.decode('hex') text = u"BÄRÇA äñ@" expected = "0001000B914356143254F6000009C2AD341104EDFB00" sms = SmsSubmit(number, text) sms.ref = 0x0 pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected)
def test_encoding_ucs2_message(self): number = "+34616585119" text = u'あ叶葉' csca = '+34646456456' expected = "07914346466554F601000B914316565811F9000806304253F68449" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.csca = csca pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) text = u"Русский" number = "655345678" expected = "001100098156355476F80008AA0E0420044304410441043A04380439" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected)
def test_encoding_message_with_latin1_chars(self): # tested with pduspy.exe number = "+34654123456" text = u"Hölä" expected = "0011000B914356143254F60000AA04483E7B0F" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) # tested with pduspy.exe number = "+34654123456" text = u"BÄRÇA äñ@" expected = "0001000B914356143254F6000009C2AD341104EDFB00" sms = SmsSubmit(number, text) sms.ref = 0x0 pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected)
def test_encoding_ucs2_message(self): number = codecs.decode(b'2b3334363136353835313139', 'hex').decode() text = u'あ叶葉' csca = '+34646456456' expected = "07914346466554F601000B914316565811F9000806304253F68449" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.csca = csca pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected) text = u"Русский" number = codecs.decode(b'363535333435363738', 'hex').decode() expected = "001100098156355476F80008AA0E0420044304410441043A04380439" sms = SmsSubmit(number, text) sms.ref = 0x0 sms.validity = timedelta(days=4) pdu = sms.to_pdu()[0] self.assertEqual(pdu.pdu, expected)
def createSMS(self,num,msg,smsc,shahash): num=str(strip(num)) msg=str(strip(msg)) smsc=str(strip(smsc)) ### Log('createSMS new msg (0): NUM: '+num+", MSG: "+msg+", SMSC: "+smsc+", LEN:"+str(len(msg))+", HASH: "+shahash) if smsc[0] != "+" and smsc[0] != "0": smsc = "+"+smsc if num[0] != "0" and num[0] != "+": num = "+"+num Log('createSMS new msg (1): NUM: '+num+", MSG: "+msg+", SMSC: "+smsc+", LEN:"+str(len(msg))+", HASH: "+shahash) #reaplace unusual characters and white spaces msg=msg.replace("*","") msg=msg.replace("[","") msg=msg.replace("]","") msg=msg.replace("/","") msg=msg.replace("\\"," ") msg=msg.replace("\t"," ") msg=msg.replace("\n"," ") while True: if " " in msg: msg=msg.replace(" "," ") else: break msg=strip(msg) if len(msg) > SMSLENGTH: Log('createSMS cutted msg: '+msg) msg=msg[0:SMSLENGTH] Log(' : NUM: '+num+", MSG:"+msg+", SMSC: "+smsc+", MSGLEN:"+str(len(msg))+", ID: "+shahash) if not USE_GSM_MODEM: #create sms format pdu y=strftime("%Y", gmtime()) sms = SmsSubmit(num, msg) #validity= end of this year sms.validity = datetime(int(y)+1, 12, 31, 23, 59, 59) sms.csca = smsc pdu = sms.to_pdu()[0] s=pdu.pdu #print s ##calculate checksum l=0 sum=0 for i in xrange(len(s)): if (i == 0 or i%2 == 0): j=i+2 h= s[i:j] #print "hex:",h ih=int(h,16) #print "int:",str(ih) sum=(sum+ih) % 256 l+=1 fulllength=str((l/2)-8) chsum=str(hex(sum))[2:] #print "length: ",fulllength #print "sum: ",chsum tosend="AT^SM=32,"+fulllength+","+s+","+chsum #print "pdu:", tosend #try to send sms 5 times: Log('createSMS: SMS SENDING, BODY: '+str(tosend)) msgsent=self.CommandSender(tosend,False,False,"smsout",20) else: if not len(self.GSMModules): Log("ERROR! No GSM module found! Message not sent.") return r=randint(0,(len(self.GSMModules)-1)) usemod=str(self.GSMModules[r]) self.initTelnetConnection() self.sendTelnetCommand("AT",False,False,'OK') self.sendTelnetCommand("AT!G=55",False,False,'OK') self.sendTelnetCommand("AT!G=A6",False,False,'OK') self.sendTelnetCommand("AT&G0"+usemod+"=AT+CMGF=1",False,False,'OK') #1 tosend='AT&G0'+usemod+'=AT+CMGS="%s"' % num result=self.sendTelnetCommand(tosend,False,False,"++g00") Log("USE_GSM_MODEM, step1: ",result) #2 tosend=msg+'\x1A' msgsent=self.sendTelnetCommand(tosend,False,False,"OK") Log("USE_GSM_MODEM, step2: ",msgsent) self.sendTelnetCommand("AT!G=55",False,False,'OK') #if not sent, put back to the queue: if not msgsent: Log('createSMS ERROR: cannot send SMS. Put back to INQ:'+str(msgsent)) nowdate=str(strftime('%Y-%m-%d %H:%M:%S', localtime())) sqlobj=initSQLite(True) qry="UPDATE sms SET status = 'senderror', lastdate='"+nowdate+"' WHERE hash = '"+shahash+"'" SQLiteExec(qry,sqlobj) SQLiteClose(sqlobj) ###INQ.put_nowait([num,msg,smsc,shahash]) sleep(1) return False #if sent: change status: else: nowdate=str(strftime('%Y-%m-%d %H:%M:%S', localtime())) sqlobj=initSQLite(True) qry="UPDATE sms SET status = 'sent', lastdate='"+nowdate+"' WHERE hash = '"+shahash+"'" SQLiteExec(qry,sqlobj) SQLiteClose(sqlobj) Log('createSMS: SMS sent OK:'+str(msgsent)) return True
def createSMS(self,num,msg,smsc,shahash): num=str(strip(num)) msg=str(strip(msg)) smsc=str(strip(smsc)) ### Log('createSMS new msg (0): NUM: '+num+", MSG: "+msg+", SMSC: "+smsc+", LEN:"+str(len(msg))+", HASH: "+shahash) if smsc[0] != "+" and smsc[0] != "0": smsc = "+"+smsc if num[0] != "0" and num[0] != "+": num = "+"+num ### Log('createSMS new msg (1): NUM: '+num+", MSG: "+msg+", SMSC: "+smsc+", LEN:"+str(len(msg))+", HASH: "+shahash) #reaplace unusual characters and white spaces msg=msg.replace("*","") msg=msg.replace("\t"," ") msg=msg.replace("\n"," ") while True: if " " in msg: msg=msg.replace(" "," ") else: break msg=strip(msg) if len(msg) > SMSLENGTH: Log('createSMS cutted msg: '+msg) msg=msg[0:SMSLENGTH] Log('createSMS new msg: NUM: '+num+", MSG:"+msg+", SMSC: "+smsc+", MSGLEN:"+str(len(msg))+", ID: "+shahash) #create sms format pdu y=strftime("%Y", gmtime()) sms = SmsSubmit(num, msg) #validity= end of this year sms.validity = datetime(int(y)+1, 12, 31, 23, 59, 59) sms.csca = smsc pdu = sms.to_pdu()[0] s=pdu.pdu #print s ##calculate checksum l=0 sum=0 for i in xrange(len(s)): if (i == 0 or i%2 == 0): j=i+2 h= s[i:j] #print "hex:",h ih=int(h,16) #print "int:",str(ih) sum=(sum+ih) % 256 l+=1 fulllength=str((l/2)-8) chsum=str(hex(sum))[2:] #print "length: ",fulllength #print "sum: ",chsum tosend="AT^SM=32,"+fulllength+","+s+","+chsum #print "pdu:", tosend #try to send sms 5 times: Log('createSMS: SMS SENDING, BODY: '+str(tosend)) msgsent=self.CommandSender(tosend,False,False,"smsout",20) #if not sent, put back to the queue: if not msgsent: Log('createSMS ERROR: cannot send SMS. Put back to INQ:'+str(msgsent)) nowdate=str(strftime('%Y-%m-%d %H:%M:%S', localtime())) sqlobj=initSQLite(True) qry="UPDATE sms SET status = 'senderror', lastdate='"+nowdate+"' WHERE hash = '"+shahash+"'" SQLiteExec(qry,sqlobj) SQLiteClose(sqlobj) ###INQ.put_nowait([num,msg,smsc,shahash]) sleep(1) return False #if sent: change status: else: nowdate=str(strftime('%Y-%m-%d %H:%M:%S', localtime())) sqlobj=initSQLite(True) qry="UPDATE sms SET status = 'sent', lastdate='"+nowdate+"' WHERE hash = '"+shahash+"'" SQLiteExec(qry,sqlobj) SQLiteClose(sqlobj) Log('createSMS: SMS sent OK:'+str(msgsent)) return True
def send_sms(*args, **kwargs): sms_pk = kwargs.get('sms_pk') try: sms_inst = SMS.objects.get( pk=sms_pk, is_send=False, ) except SMS.DoesNotExist: return False manager = asterisk.manager.Manager() # connect to the manager try: manager.connect(settings.ASTERISK_HOST) manager.login(*settings.ASTERISK_AUTH) # get a status report response = manager.status() print('print: response: ', response) logger.info('logger: response: %s' % response) # Success number = '+380{code}{phone}'\ .format( code=sms_inst.to_code, phone=sms_inst.to_phone, ) sms_to_pdu = SmsSubmit( number=number, text=sms_inst.message, ) sms_to_pdu.request_status = True sms_to_pdu.validity = timedelta(days=2) sms_list = sms_to_pdu.to_pdu() # last_loop = len(sms_list) - 1 for i, pdu_sms in enumerate(sms_list): time.sleep(0.5) response = manager.command( 'dongle pdu {device} {pdu}'.format( device='Vodafone1', pdu=pdu_sms.pdu, ), ) print('print: response.data: ', response.data) logger.info('logger: response.data: %s' % response.data) # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n sended_sms = increase_send_sms() print('print: sended SMS: ', sended_sms) logger.info('logger: sended SMS: %s' % sended_sms) # if i != last_loop: # time.sleep(1.5) time.sleep(0.5) manager.logoff() except asterisk.manager.ManagerSocketException as e: print("Error connecting to the manager: %s" % e, ) except asterisk.manager.ManagerAuthException as e: print("Error logging in to the manager: %s" % e, ) except asterisk.manager.ManagerException as e: print("Error: %s" % e, ) finally: # remember to clean up try: manager.close() except Exception as e: print('print: sms_ussd/task.py: e: ', e) logger.info('logger: sms_ussd/task.py: e: %s' % e) sms_inst.task_id = None sms_inst.is_send = True sms_inst.send_at = timezone.now() sms_inst.save(skip_super_save=True, ) return True, timezone.now(), '__name__: {0}'.format(str(__name__))
def send_template_sms(*args, **kwargs): phone = kwargs.pop( 'sms_to_phone_char', False, ) if not phone: return False phone = phone.replace(' ', '').strip('+') \ .replace('(', '').replace(')', '').replace('-', '') \ .lstrip('380').lstrip('38').lstrip('80').lstrip('0') try: int_phone = int(phone[2:]) int_code = int(phone[:2]) except ValueError: return False template_name = kwargs.pop( 'sms_template_name', False, ) try: template = Template.objects.get(name=template_name, ) except Template.DoesNotExist: return False template_dict = {} for key, value in kwargs.items(): if key.startswith('sms_'): template_dict.update({key.lstrip('sms_'): value}) message = template.template.format(**template_dict) sms_inst = SMS( template=template, direction=2, task_id=None, sim_id=255016140761290, is_send=True, message=message, to_phone_char=phone, to_code=int_code, to_phone=int_phone, send_at=timezone.now(), ) manager = asterisk.manager.Manager() # connect to the manager try: manager.connect(settings.ASTERISK_HOST) manager.login(*settings.ASTERISK_AUTH) # get a status report response = manager.status() print('response: ', response) number = '+380{code}{phone}'\ .format( code=sms_inst.to_code, phone=sms_inst.to_phone, ) sms_to_pdu = SmsSubmit( number=number, text=sms_inst.message, ) sms_to_pdu.request_status = False sms_to_pdu.validity = timedelta(days=2) sms_list = sms_to_pdu.to_pdu() # last_loop = len(sms_list) - 1 for i, pdu_sms in enumerate(sms_list): time.sleep(0.5) response = manager.command( 'dongle pdu {device} {pdu}'.format( device='Vodafone1', pdu=pdu_sms.pdu, ), ) print('print: response.data: ', response.data) logger.info('logger: response.data: %s' % response.data) # [Vodafone1] SMS queued for send with id 0x7f98c8004420\n--END COMMAND--\r\n sended_sms = increase_send_sms() print('print: sended SMS: ', sended_sms) logger.info('logger: sended SMS: %s' % sended_sms) # if i != last_loop: # time.sleep(1.5) time.sleep(0.5) manager.logoff() except asterisk.manager.ManagerSocketException as e: print("Error connecting to the manager: %s" % e, ) except asterisk.manager.ManagerAuthException as e: print("Error logging in to the manager: %s" % e, ) except asterisk.manager.ManagerException as e: print("Error: %s" % e, ) finally: # remember to clean up try: manager.close() except Exception as e: print( 'sms_ussd/tasks.py: e: ', e, ) sms_inst.save(skip_super_save=True, ) return True, timezone.now(), '__name__: {0}'.format(str(__name__))