def test_decoding_generic_wap_push(self): pdus = [ "0791947122725014440C8500947122921105F5112042519582408C0B05040B8423F0000396020101060B03AE81EAC3958D01A2B48403056A0A20566F6461666F6E650045C60C037761702E6D65696E63616C6C79612E64652F000801035A756D206B6F7374656E6C6F73656E20506F7274616C20224D65696E0083000322202D2065696E66616368206175662064656E20666F6C67656E64656E204C696E6B206B6C69636B656E", "0791947122725014440C8500947122921105F5112042519592403C0B05040B8423F00003960202206F6465722064696520536569746520646972656B7420617566727566656E2E2049687200830003205465616D000101", ] number = binascii.unhexlify(b'303034393137323232393131').decode() csca = "+491722270541" data = b"" sms = SmsDeliver(pdus[0]) self.assertEqual(sms.udh.concat.ref, 150) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 1) self.assertEqual(sms.number, number) self.assertEqual(sms.csca, csca) data += sms.text sms = SmsDeliver(pdus[1]) self.assertEqual(sms.udh.concat.ref, 150) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 2) self.assertEqual(sms.number, number) data += sms.text self.assertEqual( data, b'\x01\x06\x0b\x03\xae\x81\xea\xc3\x95\x8d\x01\xa2\xb4\x84\x03\x05j\n Vodafone\x00E\xc6\x0c\x03wap.meincallya.de/\x00\x08\x01\x03Zum kostenlosen Portal "Mein\x00\x83\x00\x03" - einfach auf den folgenden Link klicken oder die Seite direkt aufrufen. Ihr\x00\x83\x00\x03 Team\x00\x01\x01' ) push = extract_push_notification(data) self.assertEqual(is_mms_notification(push), False)
def smsing(self, pdu): # Called by ChipMo 2001:4002 # 1 Unpack SMS from pdu string # 2 Format other number # 3 Gen new SMS id # 4 Set Sms info # 5 Add Sms to Asynchronous System:Sms list # 6 Find Users atk which should push smsing # 7 Remove Timeout News Session # 8 Find News Session which should push smsing # 9 Add Calling to Asynchronous System:Smsing smsing sms = SmsDeliver(pdu).data if self['mod'] == 'MG2639' else CdmaSmsDeliver(pdu).data tim = int(time.mktime(sms['date'].utctimetuple())) + 28800 now = int(time.time()*1000) (fnum, inum, loc) = phoneNum.loads(sms['number']) smsid = "%s%d%d"%(inum[-20:], now, random.randrange(100, 999)) now = now/1000 msg = base64.b64encode(sms['text'].encode('utf8')) # _script = """ # redis.call('hmset', 'Sms:'..KEYS[1]..':info', 'id', KEYS[1], 'cpid', KEYS[2], 'cdid', KEYS[3], 'bid', KEYS[4], 'oth', KEYS[5], 'fnum', KEYS[6], 'inum', KEYS[7], 'loc', KEYS[8], 'msg', KEYS[9], 'st', KEYS[10], 'ed', KEYS[11]) # redis.call('rpush', 'System:Sms', KEYS[1]) # local ids = redis.call('zrange', 'Box:'..KEYS[4]..':Users', 0, -1) # local ses = {} # local atk = '' # for k, v in pairs(ids) do # for m,n in pairs(redis.call('hvals', 'User:'******':atk')) do # atk = atk..n..',' # end # redis.call('zremrangebyscore', 'User:'******':news', 0, KEYS[10] - 5*60) # for p,q in pairs(redis.call('zrange', 'User:'******':news', 0, -1)) do # table.insert(ses, {q,redis.call('hget', 'Session:'..q..':info', 'chn')}) # end # end # if atk ~= '' then redis.call('rpush', 'System:Smsing', atk..KEYS[1]) end # return ses # """ print '----', repr([smsid, self.id, self['cdid'], self['bid'], sms['number'], fnum, inum, loc, msg, tim, now]) _script = """ redis.call('hmset', 'Sms:'..KEYS[1]..':info', 'id', KEYS[1], 'cpid', KEYS[2], 'cdid', KEYS[3], 'bid', KEYS[4], 'oth', KEYS[5], 'fnum', KEYS[6], 'inum', KEYS[7], 'loc', KEYS[8], 'msg', KEYS[9], 'st', KEYS[10], 'ed', KEYS[11]) redis.call('rpush', 'System:Sms', KEYS[1]) local ids = redis.call('zrange', 'Box:'..KEYS[4]..':Users', 0, -1) local ses = {} local an = '' local n = '' for k, v in pairs(ids) do n = redis.call('hget', 'User:'******':info', 'atkname') if n then an = an..n..',' end redis.call('zremrangebyscore', 'User:'******':news', 0, tonumber(KEYS[11]) - 5*60) for p,q in pairs(redis.call('zrange', 'User:'******':news', 0, -1)) do table.insert(ses, {q,redis.call('hget', 'Session:'..q..':info', 'chn')}) end end if an ~= '' then redis.call('rpush', 'System:Smsing', an..KEYS[1]) end return ses """ d = self._redis.eval(_script, [smsid, self.id, self['cdid'], self['bid'], sms['number'], fnum, inum, loc, msg, tim, now ]) d.addCallback(lambda sa: self._debug_(sa)) d.addCallback(lambda sa: (sa, [sms['number'], sms['text'], tim, inum, smsid])) return d
def readlAllSMS(s): s.write("AT+CMGL=4\r") rets = s.readlines() #print(rets) total_sms = 0 for l in rets: if len(l) > 20: #print(l) pdu = l.splitlines()[0] sms = SmsDeliver(pdu) smsc = sms.data['csca'] nomor = sms.data['number'] tgl = sms.data['date'].replace(tzinfo=timezone('UTC')).astimezone( timezone(TIMEZONE)).strftime("%Y-%m-%d %H:%M:%S") pesan = sms.data['text'].splitlines()[0] payload = { 'smsc': smsc, 'tgl': tgl, 'sender': nomor, 'text': pesan } ret = requests.post("http://35.185.178.17:7744/api/v1/sms", data=json.dumps(payload)) log(payload) total_sms += 1 #delete all message in simcard memory after read if total_sms > 0: s.write("AT+CMGD=0,4\r") readAllsms
def set_pdu(): try: pdu = SmsDeliver(msg.strip()) except ValueError, e: # IM3 pernah mengirim '00/00/12 05:27:14' (Kokocell) self.log(e) return
def test_decoding_odd_length_pdu_no_strict(self): # same pdu as in test_decoding_number_alpha1 minus last char pdu = "07919471060040340409D0C6A733390400009060920173018093CC74595C96838C4F6772085AD6DDE4320B444E9741D4B03C6D7EC3E9E9B71B9474D3CB727799DEA286CFE5B9991DA6CBC3F432E85E9793CBA0F09A9EB6A7CB72BA0B9474D3CB727799DE72D6E9FABAFB0CBAA7E56490BA4CD7D34170F91BE4ACD3F575F7794E0F9F4161F1B92C2F8FD1EE32DD054AA2E520E3D3991C82A8E5701" text = "Lieber FONIC Kunde, die Tarifoption Internet-Tagesflatrate wurde aktiviert. Internet-Nutzung wird jetzt pro Nutzungstag abgerechnet. Ihr FONIC Tea" sms = SmsDeliver(pdu, strict=False) self.assertEqual(sms.text, text)
def processSMS(self,pdu=None,cardnum="0"): if not pdu or not len(strip(pdu)): return False sms=None try: sms=SmsDeliver(pdu) except: pass if sms: sender = sms.data['number'] msg = sms.data['text'] msg = msg.strip() #print msg try: msg.encode('utf-8') except: Log("processSMS msg ENCodeerror, skip:",msg.decode('utf-8', 'ignore').encode('utf-8')) return True #for unicode testing ################# #try: # msg.decode('utf-8') #except: # Log("processSMS msg DECodeerror, skip:",msg.encode('utf-8')) # return False ################# msg = msg.encode('utf-8') Log("New incoming SMS: ",sender,msg) smsdate = sms.data['date'].strftime('%Y-%m-%d %H:%M:%S') h=hashlib.sha1() h.update(str(smsdate)+str(sender)+str(msg)) shahash=h.hexdigest() sqlobj=initSQLite(True) qry_check = "SELECT 1 FROM sms WHERE hash = '"+shahash+"'" check=SQLiteQuery(qry_check,sqlobj,True) if not check: qry = 'INSERT INTO sms (smsdate, cardnum, fromnum, status, deleted, hash, msg) \ VALUES ("%s", "%s", "%s", "received", "no", "%s", "%s")' % ( str(smsdate), str(cardnum), str(sender), str(shahash), str(msg)) rowid=SQLiteExec(qry,sqlobj) SQLiteClose(sqlobj) if rowid > 0: return True else: return False elif check < 0: SQLiteClose(sqlobj) return False else: SQLiteClose(sqlobj) return True
def readSMS(): print("LOOKING FOR SMS") list = sendCommand("AT+CMGL=0") ret = [] for item in list: #print item if item.startswith("+CMGL:") == False: if item!="OK": ret.append(SmsDeliver(item)) return ret
def test_decoding_ucs2_pdu(self): pdu = "07914306073011F0040B914316709807F2000880604290224080084E2D5174901A8BAF" text = u"中兴通讯" csca = "+34607003110" number = '2b3334363130373839373032'.decode('hex') sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.csca, csca) self.assertEqual(sms.number, number)
def test_decoding_datetime_gmtplusone(self): pdu = "0791447758100650040C914497716247010000909010711423400A2050EC468B81C4733A" text = " 1741 bst" number = '2b343437393137323637343130'.decode('hex') date = datetime(2009, 9, 1, 16, 41, 32) sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.number, number) self.assertEqual(sms.date, date)
def test_decoding_7bit_pdu(self): pdu = "07911326040000F0040B911346610089F60000208062917314080CC8F71D14969741F977FD07" text = "How are you?" csca = "+31624000000" number = '2b3331363431363030393836'.decode('hex') sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.csca, csca) self.assertEqual(sms.number, number)
def test_decode_sms_confirmation(self): pdu = "07914306073011F006270B913426565711F7012081111345400120811174054043" csca = "+34607003110" date = datetime(2010, 2, 18, 10, 31, 54) number = "SR-UNKNOWN" # XXX: the number should be +344626575117, is the prefix flipped ? text = "+43626575117|10/02/18 11:31:54|" sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.csca, csca) self.assertEqual(sms.number, number) self.assertEqual(sms.date, date)
def test_decoding_number_alphanumeric(self): # Odd length test pdu = "07919471060040340409D0C6A733390400009060920173018093CC74595C96838C4F6772085AD6DDE4320B444E9741D4B03C6D7EC3E9E9B71B9474D3CB727799DEA286CFE5B9991DA6CBC3F432E85E9793CBA0F09A9EB6A7CB72BA0B9474D3CB727799DE72D6E9FABAFB0CBAA7E56490BA4CD7D34170F91BE4ACD3F575F7794E0F9F4161F1B92C2F8FD1EE32DD054AA2E520E3D3991C82A8E5701B" number = "FONIC" text = "Lieber FONIC Kunde, die Tarifoption Internet-Tagesflatrate wurde aktiviert. Internet-Nutzung wird jetzt pro Nutzungstag abgerechnet. Ihr FONIC Team" csca = "+491760000443" sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.csca, csca) self.assertEqual(sms.number, number) # Even length test pdu = "07919333852804000412D0F7FBDD454FB75D693A0000903002801153402BCD301E9F0605D9E971191483C140412A35690D52832063D2F9040599A058EE05A3BD6430580E" number = "www.tim.it" text = 'Maxxi Alice 100 ATTIVATA FINO AL 19/04/2009' csca = '+393358824000' sms = SmsDeliver(pdu) self.assertEqual(sms.text, text) self.assertEqual(sms.csca, csca) self.assertEqual(sms.number, number)
def test_decoding_7bit_pdu_data(self): pdu = "07911326040000F0040B911346610089F60000208062917314080CC8F71D14969741F977FD07" text = "How are you?" csca = "+31624000000" number = '2b3331363431363030393836'.decode('hex') data = SmsDeliver(pdu).data self.assertEqual(data['text'], text) self.assertEqual(data['csca'], csca) self.assertEqual(data['number'], number) self.assertEqual(data['pid'], 0) self.assertEqual(data['fmt'], 0) self.assertEqual(data['date'], datetime(2002, 8, 26, 19, 37, 41))
def test_decoding_delivery_status_report_without_smsc_address(self): pdu = "00060505810531F1010150610000400101506100004000" sr = { 'status': 0, 'scts': datetime(2010, 10, 5, 15, 0), 'dt': datetime(2010, 10, 5, 15, 0), 'recipient': '50131' } sms = SmsDeliver(pdu) self.assertEqual(sms.csca, None) data = sms.data self.assertEqual(data['ref'], 5) self.assertEqual(sms.sr, sr)
def parse_cmgl_response(result): response = result['response'] # Lines alternative between the +CMGL response and the # actual PDU containing the SMS found = False messages = [] for line in response: if line.startswith('+CMGL:'): found = True elif found: messages.append(SmsDeliver(line)) found = False return messages
def test_decoding_delivery_status_report(self): pdu = "0791538375000075061805810531F1019082416500400190824165004000" sr = { 'status': 0, 'scts': datetime(2010, 9, 28, 13, 56), 'dt': datetime(2010, 9, 28, 13, 56), 'recipient': '50131' } sms = SmsDeliver(pdu) self.assertEqual(sms.csca, "+353857000057") data = sms.data self.assertEqual(data['ref'], 24) self.assertEqual(sms.sr, sr)
def readSMS(self): print("LOOKING FOR SMS") list = self.sendCommand("AT+CMGL=0") print list ret = [] if "ZTE" in self.MANUFACTURER and self.MODEL == "MF192": print len(list) if len(list) > 2 and "+CMGL" in list[1]: print "Liste ", list[2] ret.append(SmsDeliver(list[2])) else: for item in list: #print item if item.startswith("+CMGL:") == False: print item if item != "OK": ret.append(SmsDeliver(item)) # print ret # print len(list) # print list[1] # print self.MANUFACTURER,self.MODEL,str(list[1]).startswith("+CGML:") return ret
def decodepdu(pdu): list =[] reci = SmsDeliver(pdu) #print(reci.number) #print(reci.date) date = reci.date.strftime("%Y-%m-%d %H:%M:%S") #print(date) #print(reci.text) #print("hello world!") list.append(reci.number) list.append(date) list.append(reci.text) return list
def smsDeliver(args): from messaging.sms import SmsDeliver sms = SmsDeliver(args["pdu"]).data.copy() if sms["date"] != None: sms["date"] = str(sms["date"]) if sms["type"] == 0b10: if sms["sr"]["dt"] != None: sms["sr"]["dt"] = str(sms["sr"]["dt"]) if sms["sr"]["scts"] != None: sms["sr"]["scts"] = str(sms["sr"]["scts"]) return sms
def readMsg(self): self.ser.flushInput() self.ser.flushOutput() command = 'AT+CMGL=1\r\n' self.ser.write(command) cmd = self.ser.readline() cmd += self.ser.readline() head = self.ser.readline() a = [] while "CMGL" in head: data = self.ser.readline() sms = SmsDeliver(data.rstrip()) idx = head.rstrip().split(',')[0].split(' ')[1] self.insertInbox(sms.data) #print idx a.append(int(idx)) head = self.ser.readline() return a
def __handle_sms(self, pdu): sms = SmsDeliver(pdu) print_dbg('SMS from:', sms.number, 'text:', sms.text) cmd = sms.text.split(None, 1)[0] # only use first word if cmd in self.playlist.keys(): song = self.playlist.get(cmd) print_dbg('PLAY: ', cmd) self.__place_call(sms.number, song) else: print_dbg('SEND PLAYLIST') response = SmsSubmit( sms.number, 'Select song:\n> ' + '\n> '.join(self.playlist.keys())) for resp_pdu in response.to_pdu(): print_dbg('RESP:', resp_pdu.pdu) # cannot wait for response '> ' due to missing '\r' self.command(b'AT+CMGS=%d' % resp_pdu.length, None) time.sleep(1) # just wait 1sec instead self.command(b'%s\x1a' % resp_pdu.pdu)
def importMessage(self, pduText, details=''): logger.debug('importMessage()-%s (%s)' % (pduText, details)) try: message = SmsDeliver(pduText) self._sMessage = message.text self._sFrom = message.number msgDetails = details.split(",") self._sId = msgDetails[0].split(":")[1].strip() if msgDetails[1] != '0': self._bStatus = True else: self._bStatus = False except Exception, e: logger.exception(e) logger.error('Failed to decode incoming message') return False
def ShowLatestSMS(AutoDelete = False): """ Fetch Latest SMS ShowLatestSMS(AutoDelete = False) return False when empty """ #WriteLog("Latest SMS as following: ") # Firstly, Get all sms, and their ID global InboxIsEmpty results = execute("AT+CMGL=4") smsids = [] cmgl = [r for r in results if r.startswith("+CMGL")] for a in cmgl: smsids.append( int(a.split(",")[0].replace("+CMGL:","")) ) if len(cmgl) == 0: ShowTime() WriteLog("Empty. No SMS") InboxIsEmpty = True return False currentid = str(smsids.pop()) results = execute("AT+CMGR="+ currentid + ";") if results[2].startswith("08") != True : WriteLog("ERROR") ShowTime() WriteLog(":::::: SMS # " + currentid + " ::::::") pducode = results[2].replace('\r\n','') pduresult = SmsDeliver(pducode) WriteLog("Sender: " + str(pduresult.number)) #WriteLog(pduresult.text.decode('utf8','ignore').encode('utf8') WriteLog(pduresult.text.decode('utf8','ignore').encode(output_coding)) if AutoDelete: DeleteSMS(int(currentid)) return False if len(smsids) == 0 else True
def readlAllSMS(s): s.write("AT+CMGL=4\r") rets = s.readlines() #print(rets) total_sms=0 for l in rets: if len(l)>20: #print(l) pdu = l.splitlines()[0] sms = SmsDeliver(pdu) smsc = sms.data['csca'] nomor = sms.data['number'] tgl = sms.data['date'].replace(tzinfo=timezone('UTC')).astimezone(timezone(TIMEZONE)).strftime("%Y-%m-%d %H:%M:%S") pesan = sms.data['text'].splitlines()[0] data={'smsc':smsc,'tgl':tgl,'sender':nomor,'text':pesan} log(data) total_sms+=1 #delete all message in simcard memory after read if total_sms>0: s.write("AT+CMGD=0,4\r") readAllsms
def from_pdu(cls, pdu): """ Converts ``pdu`` to a :class:`Message` object :param pdu: The PDU to convert :rtype: ``Message`` """ ret = SmsDeliver(pdu).data if 'date' not in ret: # XXX: Should we really fake a date? _datetime = get_tz_aware_now() else: # SmsDeliver dates are UTC but naive _datetime = ret['date'].replace(tzinfo=timezone('UTC')) m = cls(ret['number'], _datetime=_datetime, csca=ret['csca'], ref=ret.get('ref'), cnt=ret.get('cnt'), seq=ret.get('seq', 0), fmt=ret.get('fmt')) m.type = ret.get('type') m.add_text_fragment(ret['text'], ret.get('seq', 0)) return m
def test_decoding_m_notification_ind(self): pdus = [ "0791447758100650400E80885810000000810004016082415464408C0C08049F8E020105040B8423F00106226170706C69636174696F6E2F766E642E7761702E6D6D732D6D65737361676500AF848C82984E4F4B3543694B636F544D595347344D4253774141734B7631344655484141414141414141008D908919802B3434373738353334323734392F545950453D504C4D4E008A808E0274008805810301194083687474703A2F", "0791447758100650440E8088581000000081000401608241547440440C08049F8E020205040B8423F02F70726F6D6D732F736572766C6574732F4E4F4B3543694B636F544D595347344D4253774141734B763134465548414141414141414100", ] number = binascii.unhexlify(b'3838383530313030303030303138').decode() csca = "+447785016005" data = b"" sms = SmsDeliver(pdus[0]) self.assertEqual(sms.udh.concat.ref, 40846) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 1) self.assertEqual(sms.number, number) self.assertEqual(sms.csca, csca) data += sms.text sms = SmsDeliver(pdus[1]) self.assertEqual(sms.udh.concat.ref, 40846) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 2) self.assertEqual(sms.number, number) data += sms.text mms = extract_push_notification(data) self.assertEqual(is_mms_notification(mms), True) self.assertEqual(mms.headers['Message-Type'], 'm-notification-ind') self.assertEqual(mms.headers['Transaction-Id'], 'NOK5CiKcoTMYSG4MBSwAAsKv14FUHAAAAAAAA') self.assertEqual(mms.headers['MMS-Version'], '1.0') self.assertEqual( mms.headers['From'], binascii.unhexlify( b'2b3434373738353334323734392f545950453d504c4d4e').decode()) self.assertEqual(mms.headers['Message-Class'], 'Personal') self.assertEqual(mms.headers['Message-Size'], 29696) self.assertEqual(mms.headers['Expiry'], 72000) self.assertEqual( mms.headers['Content-Location'], 'http://promms/servlets/NOK5CiKcoTMYSG4MBSwAAsKv14FUHAAAAAAAA') pdus = [ "0791447758100650400E80885810000000800004017002314303408C0C0804DFD3020105040B8423F00106226170706C69636174696F6E2F766E642E7761702E6D6D732D6D65737361676500AF848C82984E4F4B3541315A6446544D595347344F3356514141734A763934476F4E4141414141414141008D908919802B3434373731373237353034392F545950453D504C4D4E008A808E0274008805810303F47F83687474703A2F", "0791447758100650440E8088581000000080000401700231431340440C0804DFD3020205040B8423F02F70726F6D6D732F736572766C6574732F4E4F4B3541315A6446544D595347344F3356514141734A763934476F4E414141414141414100", ] number = "88850100000008" data = b"" sms = SmsDeliver(pdus[0]) self.assertEqual(sms.udh.concat.ref, 57299) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 1) self.assertEqual(sms.number, number) data += sms.text sms = SmsDeliver(pdus[1]) self.assertEqual(sms.udh.concat.ref, 57299) self.assertEqual(sms.udh.concat.cnt, 2) self.assertEqual(sms.udh.concat.seq, 2) self.assertEqual(sms.number, number) data += sms.text mms = extract_push_notification(data) self.assertEqual(is_mms_notification(mms), True) self.assertEqual(mms.headers['Message-Type'], 'm-notification-ind') self.assertEqual(mms.headers['Transaction-Id'], 'NOK5A1ZdFTMYSG4O3VQAAsJv94GoNAAAAAAAA') self.assertEqual(mms.headers['MMS-Version'], '1.0') self.assertEqual( mms.headers['From'], binascii.unhexlify( b'2b3434373731373237353034392f545950453d504c4d4e').decode()) self.assertEqual(mms.headers['Message-Class'], 'Personal') self.assertEqual(mms.headers['Message-Size'], 29696) self.assertEqual(mms.headers['Expiry'], 259199) self.assertEqual( mms.headers['Content-Location'], 'http://promms/servlets/NOK5A1ZdFTMYSG4O3VQAAsJv94GoNAAAAAAAA')
def is_pdu(s): try: return SmsDeliver(s) except: return
def printFile(file, toplevel=""): # print file name as page title if (toplevel == ""): ptext = "%s" % (file.localName) else: ptext = "%s / %s" % (toplevel, file.localName) Story.append( Paragraph("<font size=14>File: %s</font>" % ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # print file description (attribute "description") description = file.attributes['description'].value ptext = "%s" % description Story.append(Paragraph("<font size=10>%s</font>" % ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # look for unknown elements contained in EF files # not "header" nor "content" for element in file.childNodes: if (element.localName == "header"): continue if (element.localName == "content"): continue if (element.nodeType == element.TEXT_NODE): continue log.warning("Element of not standard type \"%s\" in \"%s\". Ignored." % (element.localName, file.localName)) # print header data (if available) header = file.getElementsByTagName('header') if (len(header) > 0): ptext = "Header data:" Story.append( Paragraph("<font size=10>%s</font>" % ptext, styles["Normal"])) Story.append(Spacer(1, 12)) headerData = [['Field name', 'Field data']] for element in header[0].childNodes: if (element.nodeType == element.TEXT_NODE): continue headerData.append([element.localName, element.firstChild.toxml()]) t = Table(headerData, colWidths=[100, 350]) t.setStyle(tableStyleWithHeader) Story.append(t) else: Story.append( Paragraph("<font size=10>Header data not available</font>", styles["Normal"])) log.info("Header data not found for EF file %s" % file.localName) Story.append(Spacer(1, 12)) # File content ptext = "File content:" Story.append(Paragraph("<font size=10>%s</font>" % ptext, styles["Normal"])) Story.append(Spacer(1, 12)) contents = file.getElementsByTagName('content') if (len(contents) < 1): Story.append( Paragraph("<font size=10>No file content</font>", styles["Normal"])) log.info("No content for EF file %s" % file.localName) index = 0 emptyCount = 0 for content in contents: #content nodes with just text if (len(content.childNodes) == 1): elementData = [] if (content.firstChild.toxml() == "Empty"): emptyCount += 1 continue # SMS Data file if (file.localName == "SMS"): elementData = [['Field name', 'Field data']] def addLine(one, two): elementData.append([ Paragraph("<font size=8>%s</font>" % one, styles["Normal"]), Paragraph("<font size=8>%s</font>" % two, styles["Normal"]) ]) smsData = string.strip(content.firstChild.toxml()) smsData = smsData[2:] try: sms = SmsDeliver(smsData) except: # if unable to decode SMS log.info( 'Unable to decode SMS structure (probably empty record)' ) elementData.append([ Paragraph("<font size=8>ERR</font>", styles["Normal"]), Paragraph( "<font size=8>Unable to decode, probably empty record</font>", styles["Normal"]) ]) length = 70 smsDataRows = [ smsData[i:i + length] for i in range(0, len(smsData), length) ] for row in smsDataRows: elementData.append([ Paragraph("", styles["Normal"]), Paragraph("<font size=8>%s</font>" % row, styles["Normal"]) ]) t = Table(elementData, colWidths=[50, 400]) t.setStyle(tableStyleWithHeader) Story.append(t) Story.append(Spacer(1, 2)) continue # if sms data decoded correctly addLine('Csca', sms.csca) addLine('Number', sms.number) addLine('Date', sms.date) addLine('Text', sms.text) addLine( "Meta", "SR: %s, FMT: %s, PID: %s, Type: %s, DCS: %s" % (sms.sr, sms.fmt, sms.pid, sms.type, sms.dcs)) t = Table(elementData, colWidths=[50, 400]) t.setStyle(tableStyleWithHeader) Story.append(t) Story.append(Spacer(1, 2)) # any other type of file else: # string split by '###' string_rows = string.split(content.firstChild.toxml(), '###') # Insert string rows in table rows (with index in the first row) firstLine = 1 for string_row in string_rows: if (len(string_row.strip()) == 0): continue indexData = '' if firstLine == 1: indexData = index firstLine = 0 ptext = string_row elementData.append([ Paragraph("<font size=8>%s</font>" % indexData, styles["Normal"]), Paragraph("<font size=8>%s</font>" % ptext, styles["Normal"]) ]) if (len(elementData) > 0): t = Table(elementData, colWidths=[20, 430]) t.setStyle(tableStyleSingleRow) Story.append(t) Story.append(Spacer(1, 2)) #content nodes with an underlying structure else: elementData = [['Field name', 'Field data']] elements = content.childNodes for element in elements: if (element.nodeType == element.TEXT_NODE): continue elementData.append([ Paragraph("<font size=8>%s</font>" % element.localName, styles["Normal"]), Paragraph("<font size=8>%s</font>" % element.toxml(), styles["Normal"]) ]) t = Table(elementData, colWidths=[100, 350]) t.setStyle(tableStyleWithHeader) Story.append(t) Story.append(Spacer(1, 12)) index += 1 if (emptyCount > 0): Story.append(Spacer(1, 12)) Story.append( Paragraph( "<font size=10>The file also contains %i empty fields.</font>" % emptyCount, styles["Normal"])) Story.append(PageBreak())
def test_decoding_datetime_gmtminusthree(self): pdu = "0791553001000001040491578800000190115101112979CF340B342F9FEBE536E83D0791C3E4F71C440E83E6F53068FE66A7C7697A781C7EBB4050F99BFE1EBFD96F1D48068BC16030182E66ABD560B41988FC06D1D3F03768FA66A7C7697A781C7E83CCEF34282C2ECBE96F50B90D8AC55EB0DC4B068BC140B1994E16D3D1622E" date = datetime(2010, 9, 11, 18, 10, 11) # 11/09/10 15:10 GMT-3.00 sms = SmsDeliver(pdu) self.assertEqual(sms.date, date)