def savephonebook(self, data): "Saves out the phonebook" res=com_lgvx8100.Phone.savephonebook(self, data) # fix up the Wallpaper ID issue _wp_paths=self.protocolclass.wallpaper_id_file() _path_entry=self.protocolclass.wallpaper_id() # clear out all entries for i in range(self.protocolclass.NUMPHONEBOOKENTRIES): _wp_paths.items.append(_path_entry) # go through each entry and update the wallpaper path _buf=prototypes.buffer(self.getfilecontents( self.protocolclass.pb_file_name)) _pb_entries=self.protocolclass.pbfile() _pb_entries.readfrombuffer(_buf, logtitle="Read phonebook file "+self.protocolclass.pb_file_name) _wp_index=res.get('wallpaper-index', {}) for _entry in _pb_entries.items: try: if _entry.wallpaper==0 or _entry.wallpaper==0xffff: # no picture ID assigned continue _filename=_wp_index[_entry.wallpaper]['filename'] if _filename: _path_str=_filename+'\x00' _path=self.protocolclass.wallpaper_id() _path.path=_path_str _wp_paths.items[_entry.entrynumber]=_path except: if __debug__: raise _buf=prototypes.buffer() _wp_paths.writetobuffer(_buf, logtitle="Updated wallpaper ids "+self.protocolclass.wallpaper_id_file_name) self.writefile(self.protocolclass.wallpaper_id_file_name, _buf.getvalue())
def sendATcommand(self, request, responseclass, ignoreerror=False): """Similar to the sendpbcommand in com_sanyo and com_lg, except that a list of responses is returned, one per line of information returned from the phone""" buffer=prototypes.buffer() request.writetobuffer(buffer) data=buffer.getvalue() try: response_lines=self.comm.sendatcommand(data, ignoreerror=ignoreerror) except commport.ATError: raise except: self.comm.success=False self.mode=self.MODENONE self.raisecommsdnaexception("sending AT command") self.comm.success=True if responseclass is None: return response_lines reslist=[] for line in response_lines: res=responseclass() buffer=prototypes.buffer(line) res.readfrombuffer(buffer) reslist.append(res) return reslist
def sendpbcommand(self, request, responseclass, ignoreerror=False, fixup=None): """Similar to the sendpbcommand in com_sanyo and com_lg, except that a list of responses is returned, one per line of information returned from the phone""" buffer=prototypes.buffer() request.writetobuffer(buffer) data=buffer.getvalue() self.logdata("Samsung phonebook request", data, request) try: response_lines=self.comm.sendatcommand(data, ignoreerror=ignoreerror) except commport.ATError: self.comm.success=False self.mode=self.MODENONE self.raisecommsdnaexception("manipulating the phonebook") self.comm.success=True reslist=[] for line in response_lines: if fixup: line=fixup(line) self.logdata("Samsung phonebook response", line, responseclass) res=responseclass() buffer=prototypes.buffer(line) res.readfrombuffer(buffer) reslist.append(res) return reslist
def savephonebook(self, data): "Saves out the phonebook" res=com_lgvx8100.Phone.savephonebook(self, data) _wp_paths=self.protocolclass.wallpaper_id_file() _path_entry=self.protocolclass.wallpaper_id() for i in range(self.protocolclass.NUMPHONEBOOKENTRIES): _wp_paths.items.append(_path_entry) _buf=prototypes.buffer(self.getfilecontents( self.protocolclass.pb_file_name)) _pb_entries=self.protocolclass.pbfile() _pb_entries.readfrombuffer(_buf, logtitle="Read phonebook file "+self.protocolclass.pb_file_name) _wp_index=res.get('wallpaper-index', {}) for _entry in _pb_entries.items: try: if _entry.wallpaper==0 or _entry.wallpaper==0xffff: continue _filename=_wp_index[_entry.wallpaper]['filename'] if _filename: _path_str=_filename+'\x00' _path=self.protocolclass.wallpaper_id() _path.path=_path_str _wp_paths.items[_entry.entrynumber]=_path except: if __debug__: raise _buf=prototypes.buffer() _wp_paths.writetobuffer(_buf, logtitle="Updated wallpaper ids "+self.protocolclass.wallpaper_id_file_name) self.writefile(self.protocolclass.wallpaper_id_file_name, _buf.getvalue())
def _readsms(self): res={} # The Voyager and Venus use index files to keep track of SMS messages for item in self.getindex(self.protocolclass.drafts_index): buf=prototypes.buffer(self.getfilecontents(item.filename, True)) self.logdata("SMS message file " +item.filename, buf.getdata()) sf=self.protocolclass.sms_saved() sf.readfrombuffer(buf, logtitle="SMS saved item") entry=self._getoutboxmessage(sf.outbox) entry.folder=entry.Folder_Saved res[entry.id]=entry for item in self.getindex(self.protocolclass.inbox_index): buf=prototypes.buffer(self.getfilecontents(item.filename, True)) self.logdata("SMS message file " +item.filename, buf.getdata()) sf=self.protocolclass.sms_in() sf.readfrombuffer(buf, logtitle="SMS inbox item") entry=self._getinboxmessage(sf) res[entry.id]=entry for item in self.getindex(self.protocolclass.outbox_index): buf=prototypes.buffer(self.getfilecontents(item.filename, True)) self.logdata("SMS message file " +item.filename, buf.getdata()) sf=self.protocolclass.sms_out() sf.readfrombuffer(buf, logtitle="SMS sent item") entry=self._getoutboxmessage(sf) res[entry.id]=entry return res
def _update_wp_index_file(self, filelist): # update the wp/picture index file with list of new files if not filelist: # no new files to update, bail return _index_file = self.protocolclass.PictureIndexFile() try: # read existing index items ... _data = self.getfilecontents( self.protocolclass.PIC_INDEX_FILE_NAME) if _data: _index_file.readfrombuffer(prototypes.buffer(_data)) except (com_brew.BrewNoSuchFileException, com_brew.BrewBadPathnameException, com_brew.BrewFileLockedException, com_brew.BrewAccessDeniedException): pass # and append the new files for _fileitem in filelist: _index_file.items.append( self.protocolclass.PictureIndexEntry(**_fileitem)) # and write out the new index file _buffer = prototypes.buffer() _index_file.writetobuffer(_buffer) self.writefile(self.protocolclass.PIC_INDEX_FILE_NAME, _buffer.getvalue())
def sendpbcommand(self, request, responseclass, ignoreerror=False, fixup=None): """Similar to the sendpbcommand in com_sanyo and com_lg, except that a list of responses is returned, one per line of information returned from the phone""" buffer=prototypes.buffer() request.writetobuffer(buffer, logtitle="Samsung phonebook request") data=buffer.getvalue() try: response_lines=self.comm.sendatcommand(data, ignoreerror=ignoreerror) except commport.ATError: self.comm.success=False self.mode=self.MODENONE self.raisecommsdnaexception("manipulating the phonebook") self.comm.success=True reslist=[] for line in response_lines: if fixup: line=fixup(line) res=responseclass() buffer=prototypes.buffer(line) res.readfrombuffer(buffer, logtitle="Samsung phonebook response") reslist.append(res) return reslist
def _update_wallpaper_index(self, wpi): # manually update wallpaper indices since the normal update process # does not seem to work buf = prototypes.buffer( self.getfilecontents(self.protocolclass.pb_file_name)) pb = self.protocolclass.pbfile() pb.readfrombuffer(buf, logtitle="Read " + self.protocolclass.pb_file_name) update_flg = False for e in pb.items: _info = wpi.get(e.serial1, None) if _info: wp = _info.get('wallpaper', None) if wp is not None and wp != e.wallpaper: update_flg = True e.wallpaper = wp gr = _info.get('group', None) if gr is not None and gr != e.group: update_flg = True e.group = gr if update_flg: self.log('Updating wallpaper index') buf = prototypes.buffer() pb.writetobuffer(buf, logtitle="Updated index " + self.protocolclass.pb_file_name) self.writefile(self.protocolclass.pb_file_name, buf.getvalue()) return update_flg
def sendATcommand(self, request, responseclass, ignoreerror=False): """Similar to the sendpbcommand in com_sanyo and com_lg, except that a list of responses is returned, one per line of information returned from the phone""" buffer=prototypes.buffer() request.writetobuffer(buffer, logtitle="GSM sendATcommand") data=buffer.getvalue() try: response_lines=self.comm.sendatcommand(data, ignoreerror=ignoreerror) except commport.ATError: raise except: self.comm.success=False self.mode=self.MODENONE self.raisecommsdnaexception("sending AT command") self.comm.success=True if responseclass is None: return response_lines reslist=[] for line in response_lines: res=responseclass() buffer=prototypes.buffer(line) res.readfrombuffer(buffer, logtitle="GSM receive AT response") reslist.append(res) return reslist
def getcalendar(self,result): res={} # Read exceptions file first try: buf=prototypes.buffer(self.getfilecontents(self.calendarexceptionlocation)) ex=self.protocolclass.scheduleexceptionfile() ex.readfrombuffer(buf, logtitle="Calendar exceptions") exceptions={} for i in ex.items: try: exceptions[i.pos].append( (i.year,i.month,i.day) ) except KeyError: exceptions[i.pos]=[ (i.year,i.month,i.day) ] except com_brew.BrewNoSuchFileException: exceptions={} # Now read schedule try: buf=prototypes.buffer(self.getfilecontents(self.calendarlocation)) if len(buf.getdata())<3: # file is empty, and hence same as non-existent raise com_brew.BrewNoSuchFileException() sc=self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") for event in sc.events: # the vx8100 has a bad entry when the calender is empty # stop processing the calender when we hit this record if event.pos==0: #invalid entry continue entry=bpcalendar.CalendarEntry() entry.desc_loc=event.description try: # delete events are still in the calender file but have garbage dates entry.start=event.start entry.end=event.end except ValueError: continue if event.alarmindex_vibrate&0x1: entry.vibrate=0 # vibarate bit is inverted in phone 0=on, 1=off else: entry.vibrate=1 entry.repeat = self.makerepeat(event.repeat, event.start) min=event.alarmminutes hour=event.alarmhours if min==0x64 or hour==0x64: entry.alarm=None # no alarm set else: entry.alarm=hour*60+min entry.ringtone=result['ringtone-index'][event.ringtone]['name'] entry.snoozedelay=0 # check for exceptions and remove them if event.repeat[3] and exceptions.has_key(event.pos): for year, month, day in exceptions[event.pos]: entry.suppress_repeat_entry(year, month, day) res[entry.id]=entry assert sc.numactiveitems==len(res) except com_brew.BrewNoSuchFileException: pass # do nothing if file doesn't exist result['calendar']=res return result
def getcalendar(self,result): try: buf=prototypes.buffer(self.getfilecontents( self.protocolclass.cal_exception_file_name)) ex=self.protocolclass.scheduleexceptionfile() ex.readfrombuffer(buf) self.logdata("Calendar exceptions", buf.getdata(), ex) exceptions={} for i in ex.items: exceptions.setdefault(i.pos, []).append( (i.year,i.month,i.day) ) except com_brew.BrewNoSuchFileException: exceptions={} try: buf=prototypes.buffer(self.getfilecontents( self.protocolclass.cal_data_file_name)) if len(buf.getdata())<2: raise com_brew.BrewNoSuchFileException() sc=self.protocolclass.schedulefile() self.logdata("Calendar", buf.getdata(), sc) sc.readfrombuffer(buf) sc.readfrombuffer(buf) res=self.get_cal(sc, exceptions, result.get('ringtone-index', {})) except com_brew.BrewNoSuchFileException: res={} result['calendar']=res return result
def getindex(self, indexfile, location, getmedia=False): "Read an index file" index={} try: buf=prototypes.buffer(self.getfilecontents(indexfile)) except com_brew.BrewNoSuchFileException: return index g=self.protocolclass.indexfile() g.readfrombuffer(buf, logtitle="Index file %s read" % (indexfile,)) for i in g.items: if i.index!=0xffff and len(i.name): try: buf=prototypes.buffer(self.getfilecontents(location+"/"+i.name+"/.desc")) except com_brew.BrewNoSuchFileException: self.log("No .desc file in "+location+"/"+i.name+" - ignoring directory") continue desc=self.protocolclass.mediadesc() desc.readfrombuffer(buf, logtitle=".desc file %s/.desc read" % (location+"/"+i.name,)) filename=self._createnamewithmimetype(i.name, desc.mimetype) if not getmedia: index[i.index]=filename else: try: contents=self.getfilecontents(location+"/"+i.name+"/"+desc.filename) except (com_brew.BrewNoSuchFileException,com_brew.BrewNoSuchDirectoryException): try: contents=self.getfilecontents(location+"/"+i.name+"/body") except (com_brew.BrewNoSuchFileException,com_brew.BrewNoSuchDirectoryException,com_brew.BrewNameTooLongException): self.log("Can't find the actual content in "+location+"/"+i.name+"/body") continue index[filename]=contents return index
def getcalendar(self, result): res = {} # Read exceptions file first exceptions = self.getexceptions() try: buf = prototypes.buffer( self.getfilecontents(self.calendarringerlocation)) ringersf = self.protocolclass.scheduleringerfile() ringersf.readfrombuffer(buf) except: self.log("unable to read schedule ringer path file") # Now read schedule try: buf = prototypes.buffer(self.getfilecontents( self.calendarlocation)) if len(buf.getdata()) < 3: # file is empty, and hence same as non-existent raise com_brew.BrewNoSuchFileException() sc = self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") for event in sc.events: # the vx8100 has a bad entry when the calender is empty # stop processing the calender when we hit this record if event.pos == 0: #invalid entry continue entry = bpcalendar.CalendarEntry() try: # delete events are still in the calender file but have garbage dates self.getcalendarcommon(entry, event) except ValueError: continue try: if (event.ringtone >= 100 ): # MIC Ringer is downloaded to phone or microSD entry.ringtone = common.basename( ringersf.ringerpaths[event.ringtone - 100].path) else: # MIC Ringer is built-in entry.ringtone = self.builtinringtones[event.ringtone] except: self.log("Setting default ringer for event\n") # hack, not having a phone makes it hard to figure out the best approach if entry.alarm == None: entry.ringtone = 'No Ring' else: entry.ringtone = 'Loud Beeps' # check for exceptions and remove them if event.repeat[3] and exceptions.has_key(event.pos): for year, month, day in exceptions[event.pos]: entry.suppress_repeat_entry(year, month, day) res[entry.id] = entry assert sc.numactiveitems == len(res) except com_brew.BrewNoSuchFileException: pass # do nothing if file doesn't exist result['calendar'] = res return result
def sendpbcommand(self, request, responseclass): self.setmode(self.MODEBREW) buffer = prototypes.buffer() request.writetobuffer(buffer, logtitle="audiovox cdm8900 phonebook request") data = buffer.getvalue() data = common.pppescape(data + common.crcs(data)) + common.pppterminator first = data[0] try: data = self.comm.writethenreaduntil(data, False, common.pppterminator, logreaduntilsuccess=False) except com_phone.modeignoreerrortypes: self.mode = self.MODENONE self.raisecommsdnaexception("manipulating the phonebook") self.comm.success = True origdata = data # sometimes there is junk at the begining, eg if the user # turned off the phone and back on again. So if there is more # than one 7e in the escaped data we should start after the # second to last one d = data.rfind(common.pppterminator, 0, -1) if d >= 0: self.log( "Multiple PB packets in data - taking last one starting at " + ` d + 1 `) self.logdata("Original pb data", origdata, None) data = data[d + 1:] # turn it back to normal data = common.pppunescape(data) # sometimes there is other crap at the begining d = data.find(first) if d > 0: self.log("Junk at begining of pb packet, data at " + ` d `) self.logdata("Original pb data", origdata, None) self.logdata("Working on pb data", data, None) data = data[d:] # take off crc and terminator crc = data[-3:-1] data = data[:-3] if common.crcs(data) != crc: self.logdata("Original pb data", origdata, None) self.logdata("Working on pb data", data, None) raise common.CommsDataCorruption( "Audiovox phonebook packet failed CRC check", self.desc) # parse data buffer = prototypes.buffer(data) res = responseclass() res.readfrombuffer(buffer, logtitle="Audiovox phonebook response") return res
def readobject(self, filename, object_class, logtitle=None, uselocalfs=False): """Read the specified filename and bind it to the object class""" if uselocalfs: self.log("Reading local file: %s" % filename) _buf = prototypes.buffer(file(filename, "rb").read()) else: _buf = prototypes.buffer(self.getfilecontents(filename)) _obj = object_class() _obj.readfrombuffer(_buf, logtitle=logtitle) return _obj
def getcalendar(self,result): res={} # Read exceptions file first exceptions = self.getexceptions() try: buf = prototypes.buffer(self.getfilecontents(self.calendarringerlocation)) ringersf = self.protocolclass.scheduleringerfile() ringersf.readfrombuffer (buf) except: self.log ("unable to read schedule ringer path file") # Now read schedule try: buf=prototypes.buffer(self.getfilecontents(self.calendarlocation)) if len(buf.getdata())<3: # file is empty, and hence same as non-existent raise com_brew.BrewNoSuchFileException() sc=self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") for event in sc.events: # the vx8100 has a bad entry when the calender is empty # stop processing the calender when we hit this record if event.pos==0: #invalid entry continue entry=bpcalendar.CalendarEntry() try: # delete events are still in the calender file but have garbage dates self.getcalendarcommon(entry, event) except ValueError: continue try: if (event.ringtone >= 100): # MIC Ringer is downloaded to phone or microSD entry.ringtone = common.basename(ringersf.ringerpaths[event.ringtone-100].path) else: # MIC Ringer is built-in entry.ringtone=self.builtinringtones[event.ringtone] except: self.log ("Setting default ringer for event\n") # hack, not having a phone makes it hard to figure out the best approach if entry.alarm==None: entry.ringtone='No Ring' else: entry.ringtone='Loud Beeps' # check for exceptions and remove them if event.repeat[3] and exceptions.has_key(event.pos): for year, month, day in exceptions[event.pos]: entry.suppress_repeat_entry(year, month, day) res[entry.id]=entry assert sc.numactiveitems==len(res) except com_brew.BrewNoSuchFileException: pass # do nothing if file doesn't exist result['calendar']=res return result
def getphonebook(self, results): # Get a list of phone numbers: phonebuf = prototypes.buffer( self.getfilecontents('SKY/PBK/number.pbk')) phones = self.protocolclass.phones() phones.readfrombuffer(phonebuf, logtitle="Phonenumbers") # Drop empty phone records, listify: phones = [phone for phone in phones.records if phone.owner_id] # Retrieve people names and groups pbook = {} bookbuf = prototypes.buffer(self.getfilecontents('SKY/PBK/book.pbk')) entries = self.protocolclass.wholebook() entries.readfrombuffer(bookbuf, logtitle="Names read") for entry in entries.pbentries: # Ignore deleted records if not entry.record: continue # Find group name: group_name = "Group not recognised" for group in results['groups']: if group.group_id == entry.group_id: group_name = group.name break pbook[entry.slot] = { 'names': [{ 'title': '', 'first': '', 'last': '', 'full': entry.name, 'nickname': '' }], 'categories': [{ 'category': group_name }], 'numbers': [{ 'number': phone.number, 'type': self.phonetypes[phone.type - 1] } for phone in phones if phone.owner_id == entry.slot], 'serials': [{ 'sourcetype': self.serialsname }] } results['phonebook'] = pbook results['categories'] = [group.name for group in results['groups']] return pbook
def _update_wallpaper_index(self, wpi): buf=prototypes.buffer(self.getfilecontents( self.protocolclass.pb_file_name)) pb=self.protocolclass.pbfile() pb.readfrombuffer(buf) update_flg=False for e in pb.items: _info=wpi.get(e.serial1, None) if _info: wp=_info.get('wallpaper', None) if wp is not None and wp!=e.wallpaper: update_flg=True e.wallpaper=wp gr=_info.get('group', None) if gr is not None and gr!=e.group: update_flg=True e.group=gr if update_flg: self.log('Updating wallpaper index') buf=prototypes.buffer() pb.writetobuffer(buf) self.writefile(self.protocolclass.pb_file_name, buf.getvalue()) return update_flg _call_history_info={ call_history.CallHistoryEntry.Folder_Incoming: protocolclass.incoming_call_file, call_history.CallHistoryEntry.Folder_Outgoing: protocolclass.outgoing_call_file, call_history.CallHistoryEntry.Folder_Missed: protocolclass.missed_call_file } def getcallhistory(self, result):
def savegroups(self, data): groups=data['groups'] keys=groups.keys() keys.sort() g=self.protocolclass.pbgroups() sg=self.protocolclass.pbseqgroups() for k in keys: e=self.protocolclass.pbgroup() e.number=k e.unknown1=48 e.ring=groups[k]['ring'] e.unknown7=0 e.unknown8=0 e.name=groups[k]['name'] g.groups.append(e) e=self.protocolclass.pbseqgroup() e.number=k e.unknown=48 sg.seqgroups.append(e) for k in xrange(k+1,20): e=self.protocolclass.pbseqgroup() e.number=0 e.unknown=0 sg.seqgroups.append(e) groupnums=[] for k in range(self.protocolclass.NUMMAPGROUPS): groupnums.append(-1); for k in data['phonebook'].keys(): groupnums[data['phonebook'][k]['serial1']]=data['phonebook'][k]['group'] mg=self.protocolclass.pbmapgroups() for k in range(len(groupnums)): e=self.protocolclass.pbmapgroup() if (groupnums[k]==-1): e.number=255 e.unknown=255 else: e.number=groupnums[k] e.unknown=48 mg.mapgroups.append(e) buffer=prototypes.buffer() g.writetobuffer(buffer) self.logdata("New group file", buffer.getvalue(), g) self.writefile("pim/pbookgroup.dat", buffer.getvalue()) buffer=prototypes.buffer() sg.writetobuffer(buffer) self.logdata("New seqgroup file", buffer.getvalue(), sg) self.writefile("pim/pbookseqgroup.dat", buffer.getvalue()) buffer=prototypes.buffer() mg.writetobuffer(buffer) self.logdata("New mapgroup file", buffer.getvalue(), mg) self.writefile("pim/pbookmapgroup.dat", buffer.getvalue())
def readobject(self, filename, object_class, logtitle=None, uselocalfs=False): """Read the specified filename and bind it to the object class""" if uselocalfs: self.log('Reading local file: %s' % filename) _buf = prototypes.buffer(file(filename, 'rb').read()) else: _buf = prototypes.buffer(self.getfilecontents(filename)) _obj = object_class() _obj.readfrombuffer(_buf, logtitle=logtitle) return _obj
def _write_pb_rec(self, pb_list, rec_cnt, fundamentals): _filename='%s%04d'%(self.protocolclass.PB_ENTRY_FILE_PREFIX, rec_cnt) _rec_file=self.protocolclass.PBFile() for _rec in pb_list: _item_len=self.protocolclass.LenEntry() if _rec: _buf=prototypes.buffer() _rec.writetobuffer(_buf) _item_len.itemlen=len(_buf.getvalue()) _rec_file.items.append(_rec.pb) _rec_file.lens.append(_item_len) _buf=prototypes.buffer() _rec_file.writetobuffer(_buf) self.writefile(_filename, _buf.getvalue())
def _readsms(self): res = {} # The Voyager and Venus use index files to keep track of SMS messages for item in self.getindex(self.protocolclass.drafts_index): try: buf = prototypes.buffer( self.getfilecontents(item.filename, True)) self.logdata("SMS message file " + item.filename, buf.getdata()) sf = self.protocolclass.sms_saved() sf.readfrombuffer(buf, logtitle="SMS saved item") entry = self._getoutboxmessage(sf.outbox) entry.folder = entry.Folder_Saved entry.datetime = "%d%02d%02dT%02d%02d%02d" % (sf.GPStime) res[entry.id] = entry except: self.log('Failed to process SMS file: ' + item.filename) if __debug__: raise for item in self.getindex(self.protocolclass.inbox_index): try: buf = prototypes.buffer( self.getfilecontents(item.filename, True)) self.logdata("SMS message file " + item.filename, buf.getdata()) sf = self.protocolclass.sms_in() sf.readfrombuffer(buf, logtitle="SMS inbox item") entry = self._getinboxmessage(sf) res[entry.id] = entry except: self.log('Failed to process SMS file: ' + item.filename) if __debug__: raise for item in self.getindex(self.protocolclass.outbox_index): try: buf = prototypes.buffer( self.getfilecontents(item.filename, True)) self.logdata("SMS message file " + item.filename, buf.getdata()) sf = self.protocolclass.sms_out() sf.readfrombuffer(buf, logtitle="SMS sent item") entry = self._getoutboxmessage(sf) res[entry.id] = entry except: self.log('Failed to process SMS file: ' + item.filename) if __debug__: raise return res
def sendpbcommand(self, request, responseclass): self.setmode(self.MODEBREW) buffer=prototypes.buffer() request.writetobuffer(buffer, logtitle="audiovox cdm8900 phonebook request") data=buffer.getvalue() data=common.pppescape(data+common.crcs(data))+common.pppterminator first=data[0] try: data=self.comm.writethenreaduntil(data, False, common.pppterminator, logreaduntilsuccess=False) except com_phone.modeignoreerrortypes: self.mode=self.MODENONE self.raisecommsdnaexception("manipulating the phonebook") self.comm.success=True origdata=data # sometimes there is junk at the begining, eg if the user # turned off the phone and back on again. So if there is more # than one 7e in the escaped data we should start after the # second to last one d=data.rfind(common.pppterminator,0,-1) if d>=0: self.log("Multiple PB packets in data - taking last one starting at "+`d+1`) self.logdata("Original pb data", origdata, None) data=data[d+1:] # turn it back to normal data=common.pppunescape(data) # sometimes there is other crap at the begining d=data.find(first) if d>0: self.log("Junk at begining of pb packet, data at "+`d`) self.logdata("Original pb data", origdata, None) self.logdata("Working on pb data", data, None) data=data[d:] # take off crc and terminator crc=data[-3:-1] data=data[:-3] if common.crcs(data)!=crc: self.logdata("Original pb data", origdata, None) self.logdata("Working on pb data", data, None) raise common.CommsDataCorruption("Audiovox phonebook packet failed CRC check", self.desc) # parse data buffer=prototypes.buffer(data) res=responseclass() res.readfrombuffer(buffer, logtitle="Audiovox phonebook response") return res
def sendpbcommand(self, request, responseclass, callsetmode=True): if callsetmode: self.setmode(self.MODEPHONEBOOK) buffer=prototypes.buffer() request.header.sequence=self.pbseq self.pbseq+=1 if self.pbseq>0xff: self.pbseq=0 request.writetobuffer(buffer, logtitle="lg phonebook request") data=buffer.getvalue() data=common.pppescape(data+common.crcs(data))+common.pppterminator firsttwo=data[:2] try: data=self.comm.writethenreaduntil(data, False, common.pppterminator, logreaduntilsuccess=False) except com_phone.modeignoreerrortypes: self.mode=self.MODENONE self.raisecommsdnaexception("manipulating the phonebook") self.comm.success=True origdata=data d=data.rfind(common.pppterminator,0,-1) if d>=0: self.log("Multiple LG packets in data - taking last one starting at "+`d+1`) self.logdata("Original LG data", origdata, None) data=data[d+1:] data=common.pppunescape(data) crc=data[-3:-1] data=data[:-3] calccrc=common.crcs(data) if calccrc!=crc: d=data.find(firsttwo) if d>0: self.log("Junk at begining of LG packet, data at "+`d`) self.logdata("Original LG data", origdata, None) self.logdata("Working on LG data", data, None) data=data[d:] calccrc=common.crcs(data) if calccrc!=crc: self.logdata("Original LG data", origdata, None) self.logdata("Working on LG data", data, None) raise common.CommsDataCorruption("LG packet failed CRC check", self.desc) if ord(data[0])==0x13: raise com_brew.BrewBadBrewCommandException() if ord(data[0])==0x14: raise com_brew.BrewMalformedBrewCommandException() buffer=prototypes.buffer(data) res=responseclass() res.readfrombuffer(buffer, logtitle="lg phonebook response") return res
def getindex(self, indexfile, location, getmedia=False): "Read an index file" index = {} try: buf = prototypes.buffer(self.getfilecontents(indexfile)) except com_brew.BrewNoSuchFileException: # file may not exist return index g = self.protocolclass.indexfile() g.readfrombuffer(buf, logtitle="Index file %s read" % (indexfile, )) for i in g.items: if i.index != 0xffff and len(i.name): # read the .desc file try: buf = prototypes.buffer( self.getfilecontents(location + "/" + i.name + "/.desc")) except com_brew.BrewNoSuchFileException: self.log("No .desc file in " + location + "/" + i.name + " - ignoring directory") continue desc = self.protocolclass.mediadesc() desc.readfrombuffer(buf, logtitle=".desc file %s/.desc read" % (location + "/" + i.name, )) filename = self._createnamewithmimetype(i.name, desc.mimetype) if not getmedia: index[i.index] = filename else: try: # try to read it using name in desc file contents = self.getfilecontents(location + "/" + i.name + "/" + desc.filename) except (com_brew.BrewNoSuchFileException, com_brew.BrewNoSuchDirectoryException): try: # then try using "body" contents = self.getfilecontents(location + "/" + i.name + "/body") except (com_brew.BrewNoSuchFileException, com_brew.BrewNoSuchDirectoryException, com_brew.BrewNameTooLongException): self.log("Can't find the actual content in " + location + "/" + i.name + "/body") continue index[filename] = contents return index
def _process_sms(self, _resp, res): # extract the SMS messages from the respons string & update the dict for i in range(0, len(_resp), 2): try: _entry = self.protocolclass.sms_msg_list_header() _buf = prototypes.buffer(_resp[i]) _entry.readfrombuffer(_buf, logtitle="SMS #" + i) _sms = sms.SMSEntry() if _entry.msg_type==self.protocolclass.SMS_MSG_REC_UNREAD or \ _entry.msg_type==self.protocolclass.SMS_MSG_REC_READ: # unread/read inbox _sms._from = _entry.address _sms.folder = sms.SMSEntry.Folder_Inbox _sms.read = _entry.msg_type == self.protocolclass.SMS_MSG_REC_READ elif _entry.msg_type == self.protocolclass.SMS_MSG_STO_SENT: # outbox _sms.add_recipient(_entry.address) _sms.folder = sms.SMSEntry.Folder_Sent elif _entry.msg_type == self.protocolclass.SMS_MSG_STO_UNSENT: # saved _sms.folder = sms.SMSEntry.Folder_Saved _sms.add_recipient(_entry.address) else: self.log('Unknown message type: %s' % _entry.msg_type) _sms = None if _sms: if _entry.timestamp: _sms.datetime = _entry.timestamp _sms.text = _resp[i + 1] res[_sms.id] = _sms except: if __debug__: raise return res
def getcameraindex(self): index={} try: buf=prototypes.buffer(self.getfilecontents("cam/pics.dat")) g=self.protocolclass.campicsdat() g.readfrombuffer(buf) for i in g.items: if len(i.name): index[i.index]={'name': "pic%02d.jpg"%(i.index,), 'date': i.taken, 'origin': 'camera' } except com_brew.BrewNoSuchFileException: pass return index my_model='VX6100' def getphoneinfo(self, phone_info):
def _get_file_ringtone_index(self, idx, result, index_file_name, index_file_class, origin): try: _buf = prototypes.buffer(self.getfilecontents(index_file_name)) except (com_brew.BrewNoSuchFileException, com_brew.BrewBadPathnameException, com_brew.BrewFileLockedException, com_brew.BrewAccessDeniedException): return idx except: if __debug__: raise return idx _index_file = index_file_class() _index_file.readfrombuffer(_buf) for _entry in _index_file.items: if _entry.pathname.startswith('/ff/'): _file_name = _entry.pathname[4:] else: _file_name = _entry.pathname if not _file_name.startswith( self.protocolclass.SND_PRELOADED_PREFIX): result[idx] = { 'name': common.basename(_entry.pathname), 'filename': _file_name, 'origin': origin, } idx += 1 return idx
def get_groups(self): _res={ 0: { 'name': 'No Group' } } try: _file_name=None _path_name=self.protocolclass.GROUP_INDEX_FILE_NAME for i in range(256): _name='%s%d'%(_path_name, i) if self.statfile(_name): _file_name=_name break if not _file_name: return _res _buf=prototypes.buffer(self.getfilecontents(_file_name)) _index_file=self.protocolclass.GroupIndexFile() _index_file.readfrombuffer(_buf) _idx=1 for _entry in _index_file.items[1:]: _res[_entry.index]={ 'name': _entry.name } _idx+=1 except IndexError: pass except: if __debug__: raise return _res
def _write_memo_entries(self, next_index, fundamentals): _memo_dict=fundamentals.get('memo', {}) _idx=next_index _cnt=0 for _key,_entry in _memo_dict.items(): if _cnt>=self.protocolclass.NP_MAX_ENTRIES: break try: _memo_entry=self.protocolclass.NotePadEntry() _text_len=min(self.protocolclass.NP_MAX_LEN, len(_entry.text)) _memo_entry.textlen=_text_len _memo_entry.text=_entry.text[:_text_len] _memo_entry.creation=self._time_now() _buf=prototypes.buffer() _memo_entry.writetobuffer(_buf) _file_name='%s%04d'%(self.protocolclass.NP_FILE_NAME_PREFIX, _idx) self.writefile(_file_name, _buf.getvalue()) _idx+=1 _cnt+=1 except: self.log('Failed to write memo endar entry') if __debug__: raise return _idx
def _get_file_wallpaper_index(self, idx, result): try: _buf=prototypes.buffer(self.getfilecontents(self.protocolclass.PIC_INDEX_FILE_NAME)) except (com_brew.BrewNoSuchFileException, com_brew.BrewBadPathnameException, com_brew.BrewFileLockedException, com_brew.BrewAccessDeniedException): return idx except: if __debug__: raise return idx _index_file=self.protocolclass.RPictureIndexFile() _index_file.readfrombuffer(_buf) for _entry in _index_file.items[1:]: if _entry.pathname.startswith('/ff/'): _file_name=_entry.pathname[4:] else: _file_name=_entry.pathname result[idx]={ 'name': _entry.name, 'filename': _file_name, 'origin': 'images', } idx+=1 return idx
def _get_file_ringtone_index(self, idx, result, index_file_name, index_file_class, origin): try: _buf=prototypes.buffer(self.getfilecontents(index_file_name)) except (com_brew.BrewNoSuchFileException, com_brew.BrewBadPathnameException, com_brew.BrewFileLockedException, com_brew.BrewAccessDeniedException): return idx except: if __debug__: raise return idx _index_file=index_file_class() _index_file.readfrombuffer(_buf) for _entry in _index_file.items: if _entry.pathname.startswith('/ff/'): _file_name=_entry.pathname[4:] else: _file_name=_entry.pathname result[idx]= { 'name': common.basename(_entry.pathname), 'filename': _file_name, 'origin': origin, } idx+=1 return idx
def OnListBoxItem(self, evt): "The user selected an event in the listbox" index = evt.m_itemIndex curtime, curdesc, curclass, curdata = self.packets[index] self.errorinfo = "" self.hex.SetData("") self.hex.highlightrange(-1, -1) if len(curdata): self.hex.SetData(curdata) # self.hex.ShowPosition(self.hex.XYToPosition(0,0)) else: self.hex.SetData(curdesc) # self.hex.ShowPosition(self.hex.XYToPosition(0,0)) self.tree.DeleteAllItems() if len(curclass): b = prototypes.buffer(curdata) try: klass = common.getfullname(curclass) except Exception, e: self.errorme("Finding class", e) wx.TipWindow(self.tree, self.errorinfo) return try: obj = klass() except Exception, e: self.errorme("Instantiating object", e) wx.TipWindow(self.tree, self.errorinfo) return
def getcalendar(self,result): res={} # Now read schedule buf=prototypes.buffer(self.getfilecontents("sch/sch_00.dat")) sc=self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") self.logdata("Calendar", buf.getdata(), sc) for event in sc.events: entry={} if event.state == 0 or event.repeat == 0: continue # deleted entry if event.date == 0x11223344: continue # blanked entry date = event.date date += self._tm520epochtounix entry['start'] = self.decodedate(date) entry['end'] = self.decodedate(date) entry['pos']=event.pos entry['description'] = event.description if event.pos == 0: entry['description'] = 'Wake Up' entry['alarm'] = 0 if event.alarm & 0xB0 == 0xB0: entry['alarm'] = 1 entry['ringtone'] = 0 entry['changeserial'] = 0 entry['repeat'] = self._calrepeatvalues[event.repeat] # Hack - using snoozedelay to store the DST flag entry['snoozedelay'] = time.localtime(date)[8] res[event.pos]=entry result['calendar']=res return result
def get_download_info(self): r = {} try: # first, 'My Image' entries img_idx = self.__phone.protocolclass.images() buf=prototypes.buffer(self.__phone.getfilecontents( \ self.__phone.protocolclass.image_index_file_name)) img_idx.readfrombuffer(buf, logtitle="Read image download index") l = len(self.__phone.protocolclass.image_file_path) + 1 mms_img_path = self.__phone.protocolclass.mms_image_path mms_img_len = len(mms_img_path) for i in range(self.__phone.protocolclass.max_image_entries): e = img_idx.entry[i] if e.name_len and e.file_name_len: if e.file_name[:mms_img_len] == mms_img_path: idx_name = e.name[:e.name_len] else: idx_name = e.file_name[l:e.file_name_len] r[idx_name] = e.file_name[:e.file_name_len] # then 'Gallery' entries try: dir_l=self.__phone.listfiles(\ self.__phone.protocolclass.cam_pix_file_path) except com_brew.BrewNoSuchDirectoryException: dir_l = {} l = len(self.__phone.protocolclass.cam_pix_file_path) + 1 for f in dir_l: r[f[l:] + '.jpg'] = f except: pass return r
def getphonebook(self, result): """Reads the phonebook data. The L{getfundamentals} information will already be in result.""" pbook={} self.enable_data_transfer() count=0 for i in range(self.protocolclass.NUMSLOTS): entry=self.protocolclass.pbentry() self.progress(i, self.protocolclass.NUMSLOTS, "") req=self.protocolclass.tosh_getpbentryrequest() req.entry_index=i res=self.sendpbcommand(req, self.protocolclass.tosh_getpbentryresponse) if not res.swap_ok: raw=self.readdatarecord() if __debug__: open("c:/projects/temp/record_in"+`i`, "wb").write(raw) buf=prototypes.buffer(raw) entry.readfrombuffer(buf, logtitle="phonebook data record") else: continue self.log("Read entry "+`i`+" - "+entry.name) pb_entry=self.extractphonebookentry(entry, result) pbook[i]=pb_entry self.disable_data_transfer() self.progress(self.protocolclass.NUMSLOTS, self.protocolclass.NUMSLOTS, "Phone book read completed") result['phonebook']=pbook return result
def read(self): try: buf=prototypes.buffer(self.__phone.getfilecontents(\ self.__phone.protocolclass.slot_file_name)) self.__slots=self.__phone.protocolclass.pbslots() self.__slots.readfrombuffer(buf) except: self.__slots=[] self.__phone.log('Failed to read slot file') def __getitem__(self, key): if type(key) is not int: raise KeyError if key<0 or key>=self.__phone.protocolclass.max_pb_slots: raise IndexError if self.__slots is None: self.read() return self.__slots.slot[key].pbbook_index """ Class to handle Phonebook entry slot -> memory slot """
def getsms(self, fundamentals): """Read SMS messages from the phone""" self.log('Reading SMS messages') self.setmode(self.MODEPHONEBOOK) _sms={} try: self.select_default_SMS() _req=self.protocolclass.sms_list_req() _sms_list=self.sendATcommand(_req, None, True) _sms_item=self.protocolclass.sms_list_resp() for _entry in _sms_list: _buf=prototypes.buffer(_entry) _sms_item.readfrombuffer(_buf, logtitle='Reading an SMS List Item') try: _res=self.comm.sendatcommand('+MMGR=%d'%_sms_item.index, retry=True) self._process_sms_result(_res, _sms, fundamentals) except commport.ATError: self.log('Failed to read SMS Item %d'%_sms_item.index) except: if __debug__: self.setmode(self.MODEMODEM) raise self.setmode(self.MODEMODEM) fundamentals['canned_msg']=[] fundamentals['sms']=_sms return fundamentals
def _get_file_wallpaper_index(self, idx, result, indexfilename, origin): try: _buf=prototypes.buffer(self.getfilecontents(indexfilename)) except (com_brew.BrewNoSuchFileException, com_brew.BrewBadPathnameException, com_brew.BrewFileLockedException, com_brew.BrewAccessDeniedException): return idx except: if __debug__: raise return idx _index_file=self.protocolclass.RPictureIndexFile() _index_file.readfrombuffer(_buf) for _entry in _index_file.items: if _entry.pictype==self.protocolclass.PIC_TYPE_USERS: if _entry.pathname.startswith('/ff/'): _file_name=_entry.pathname[4:] else: _file_name=_entry.pathname result[idx]={ 'name': common.basename(_entry.pathname), 'filename': _file_name, 'origin': origin, } idx+=1 return idx
def get_download_info(self): r={} try: img_idx=self.__phone.protocolclass.images() buf=prototypes.buffer(self.__phone.getfilecontents( \ self.__phone.protocolclass.image_index_file_name)) img_idx.readfrombuffer(buf) l=len(self.__phone.protocolclass.image_file_path)+1 mms_img_path=self.__phone.protocolclass.mms_image_path mms_img_len=len(mms_img_path) for i in range(self.__phone.protocolclass.max_image_entries): e=img_idx.entry[i] if e.name_len and e.file_name_len: if e.file_name[:mms_img_len]==mms_img_path: idx_name=e.name[:e.name_len] else: idx_name=e.file_name[l:e.file_name_len] r[idx_name]=e.file_name[:e.file_name_len] try: dir_l=self.__phone.listfiles(\ self.__phone.protocolclass.cam_pix_file_path) except com_brew.BrewNoSuchDirectoryException: dir_l={} l=len(self.__phone.protocolclass.cam_pix_file_path)+1 for f in dir_l: r[f[l:]+'.jpg']=f except: pass return r
def savephonebook(self, data): "Saves out the phonebook" res=parentphone.savephonebook(self, data) # retrieve the phonebook entries _buf=prototypes.buffer(self.getfilecontents( self.protocolclass.pb_file_name)) _pb_entries=self.protocolclass.pbfile() _pb_entries.readfrombuffer(_buf, logtitle="Read phonebook file "+self.protocolclass.pb_file_name) _rt_index=data.get('ringtone-index', {}) _wp_index=data.get('wallpaper-index', {}) # update info that the phone software failed to do!! self._update_pb_info(_pb_entries, data) # fix up ringtone index self._write_path_index(_pb_entries, 'ringtone', _rt_index, self.protocolclass.RTPathIndexFile, (0xffff,)) # fix up msg ringtone index self._write_path_index(_pb_entries, 'msgringtone', _rt_index, self.protocolclass.MsgRTIndexFile, (0xffff,)) # fix up wallpaer index self._write_path_index(_pb_entries, 'wallpaper', _wp_index, self.protocolclass.WPPathIndexFile, (0, 0xffff,)) return res
def getmemo(self, result): # read the memo file res = {} try: stat_res = self.statfile(self.memolocation) # allow for zero length file if stat_res != None and stat_res['size'] != 0: buf = prototypes.buffer(self.getfilecontents( self.memolocation)) text_memo = self.protocolclass.textmemofile() text_memo.readfrombuffer(buf, logtitle="Read memo file" + self.memolocation) for m in text_memo.items: entry = memo.MemoEntry() entry.text = m.text try: entry.set_date_isostr("%d%02d%02dT%02d%02d00" % ((m.memotime))) except ValueError: # deleted memos can remain in file but have a bogus date continue res[entry.id] = entry except com_brew.BrewNoSuchFileException: pass result['memo'] = res return result
def getplaylist(self, result): # return a list of all available songs and playlists # first, retrieve the list of all songs result[playlist.masterlist_key]=self._get_all_songs(result) # get a list of playlists and their contents _pl_list=[] try: _req=self.protocolclass.PLIndexFile() _buf=prototypes.buffer( self.getfilecontents(self.protocolclass.PLIndexFileName)) _req.readfrombuffer(_buf, logtitle='Reading Playlist Index') for _item in _req.items: try: _pl_list.append(self._read_pl_list(_item.pathname)) except com_brew.BrewNoSuchFileException: pass except: if __debug__: raise except com_brew.BrewNoSuchFileException: pass except: if __debug__: raise result[playlist.playlist_key]=_pl_list return result
def _get_ringtone_index(self): res = {} # first the builtin ones for _l in self.builtinringtones: _idx = _l[0] for _e in _l[1]: res[_idx] = {'name': _e, 'origin': 'builtin'} _idx += 1 # now the custome one _buf = prototypes.buffer( self.getfilecontents(self.protocolclass.RT_INDEX_FILE)) _idx_file = self.protocolclass.ringtone_index_file() _idx_file.readfrombuffer(_buf, logtitle='Read ringtone index file') for _entry in _idx_file.items: _filename = self.decode_utf16(_entry.name) if _filename.startswith(self.protocolclass.RT_PATH): _origin = 'ringers' elif _filename.startswith(self.protocolclass.SND_PATH): _origin = 'sounds' else: # neither ringtone nor sounds, can't use this continue res[_entry.index] = { 'name': common.basename(_filename), 'filename': _filename, 'type': _entry.ringtone_type, 'origin': _origin } return res
def getindex(self, indexfile): "Read an index file" index={} if re.search("ImageIndex", indexfile) is not None: ind=0 for ifile in 'wallpaper', 'poweron', 'poweroff': ifilefull="download/"+ifile+".bit" try: mediafiledata=self.mediacache.readfile(ifilefull) if len(mediafiledata)!=0: index[ind]=ifile ind = ind + 1 self.log("Index file "+indexfile+" entry added: "+ifile) except: pass else: try: buf=prototypes.buffer(self.getfilecontents(indexfile)) except com_brew.BrewNoSuchFileException: return index g=self.protocolclass.indexfile() g.readfrombuffer(buf) self.logdata("Index file %s read with %d entries" % (indexfile,g.numactiveitems), buf.getdata(), g) for i in g.items: if i.index!=0xffff: ifile=re.sub("\.mid|\.MID", "", i.name) self.log("Index file "+indexfile+" entry added: "+ifile) index[i.index]=ifile return index
def _readsms(self): res={} for item in self.listfiles("sms").values(): folder=None for f,pat in self.protocolclass.SMS_PATTERNS.items(): if pat.match(item['name']): folder=f break if folder: buf=prototypes.buffer(self.getfilecontents(item['name'], True)) self.logdata("SMS message file " +item['name'], buf.getdata()) if folder=='Inbox': sf=self.protocolclass.sms_in() sf.readfrombuffer(buf, logtitle="SMS inbox item") entry=self._getinboxmessage(sf) res[entry.id]=entry elif folder=='Sent': sf=self.protocolclass.sms_out() sf.readfrombuffer(buf, logtitle="SMS sent item") entry=self._getoutboxmessage(sf) res[entry.id]=entry elif folder=='Saved': sf=self.protocolclass.sms_saved() sf.readfrombuffer(buf, logtitle="SMS saved item") if sf.inboxmsg: entry=self._getinboxmessage(sf.inbox) else: entry=self._getoutboxmessage(sf.outbox) entry.folder=entry.Folder_Saved res[entry.id]=entry return res
def _readsms(self): res={} # go through the sms directory looking for messages for item in self.listfiles("sms").values(): folder=None for f,pat in self.protocolclass.SMS_PATTERNS.items(): if pat.match(item['name']): folder=f break if folder: buf=prototypes.buffer(self.getfilecontents(item['name'], True)) self.logdata("SMS message file " +item['name'], buf.getdata()) if folder=='Inbox': sf=self.protocolclass.sms_in() sf.readfrombuffer(buf, logtitle="SMS inbox item") entry=self._getinboxmessage(sf) res[entry.id]=entry elif folder=='Sent': sf=self.protocolclass.sms_out() sf.readfrombuffer(buf, logtitle="SMS sent item") entry=self._getoutboxmessage(sf) res[entry.id]=entry elif folder=='Saved': sf=self.protocolclass.sms_saved() sf.readfrombuffer(buf, logtitle="SMS saved item") if sf.inboxmsg: entry=self._getinboxmessage(sf.inbox) else: entry=self._getoutboxmessage(sf.outbox) entry.folder=entry.Folder_Saved res[entry.id]=entry return res
def get_download_info(self): r={} try: img_idx=self.__phone.protocolclass.images() buf=prototypes.buffer(self.__phone.getfilecontents( \ self.__phone.protocolclass.image_index_file_name)) img_idx.readfrombuffer(buf) l=len(self.__phone.protocolclass.image_file_path)+1 for i in range(self.__phone.protocolclass.max_image_entries): e=img_idx.entry[i] if e.name_len: r[e.file_name[l:e.file_name_len]]=e.file_name[:e.file_name_len] except: pass return r
def getcamindex(self, indexfile, location, getmedia=False): "Read an index file" index = {} try: buf = prototypes.buffer(self.getfilecontents(indexfile)) except com_brew.BrewNoSuchFileException: # file may not exist return index g = self.protocolclass.camindexfile() g.readfrombuffer(buf, logtitle="Camera index file") self.log("Cam index file read") for i in g.items: if len(i.name): # the name in the index file is for display purposes only filename = "pic%02d.jpg" % i.index if not getmedia: index[i.index] = filename else: try: contents = self.getfilecontents(location + "/" + filename + "/body") except (com_brew.BrewNoSuchFileException, com_brew.BrewNoSuchDirectoryException, com_brew.BrewNameTooLongException): self.log("Can't find the actual content in " + location + "/" + filename + "/body") continue index[filename] = contents return index
def getindex(self, location, getmedia=False): """Returns an index based on the sub-directories of location. The key is an integer, and the value is the corresponding name""" index={} try: dirlisting=self.getfilesystem(location) except com_brew.BrewNoSuchDirectoryException: return index for item in dirlisting: if dirlisting[item]['type']!='directory': continue try: buf=prototypes.buffer(self.getfilecontents(dirlisting[item]['name']+"/.desc")) except com_brew.BrewNoSuchFileException: self.log("No .desc file in "+dirlisting[item]['name']+" - ignoring directory") continue desc=self.protocolclass.mediadesc() desc.readfrombuffer(buf, logtitle=".desc file %s/.desc read" % (dirlisting[item]['name'],)) filename=self._createnamewithmimetype(dirlisting[item]['name'], desc.mimetype) if not getmedia: index[desc.index]=filename else: try: contents=self.getfilecontents(dirlisting[item]['name']+"/"+desc.filename) except (com_brew.BrewNoSuchFileException,com_brew.BrewNoSuchDirectoryException): try: contents=self.getfilecontents(dirlisting[item]['name']+"/body") except (com_brew.BrewNoSuchFileException,com_brew.BrewNoSuchDirectoryException,com_brew.BrewNameTooLongException): self.log("Can't find the actual content in "+dirlisting[item]['name']) continue index[filename]=contents return index
def getcalendar(self, result): res = {} # Now read schedule buf = prototypes.buffer(self.getfilecontents("sch/sch_00.dat")) sc = self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") self.logdata("Calendar", buf.getdata(), sc) for event in sc.events: entry = {} if event.state == 0 or event.repeat == 0: continue # deleted entry if event.date == 0x11223344: continue # blanked entry date = event.date date += self._tm520epochtounix entry["start"] = self.decodedate(date) entry["end"] = self.decodedate(date) entry["pos"] = event.pos entry["description"] = event.description if event.pos == 0: entry["description"] = "Wake Up" entry["alarm"] = 0 if event.alarm & 0xB0 == 0xB0: entry["alarm"] = 1 entry["ringtone"] = 0 entry["changeserial"] = 0 entry["repeat"] = self._calrepeatvalues[event.repeat] # Hack - using snoozedelay to store the DST flag entry["snoozedelay"] = time.localtime(date)[8] res[event.pos] = entry result["calendar"] = res return result
def getphonebook(self, result): """Reads the phonebook data. The L{getfundamentals} information will already be in result.""" pbook = {} self.enable_data_transfer() # no way to read the number of entries, just have to read all count = 0 # try: for i in range(self.protocolclass.NUMSLOTS): entry = self.protocolclass.pbentry() self.progress(i, self.protocolclass.NUMSLOTS, "") req = self.protocolclass.tosh_getpbentryrequest() req.entry_index = i res = self.sendpbcommand( req, self.protocolclass.tosh_getpbentryresponse) if not res.swap_ok: raw = self.readdatarecord() if __debug__: open("c:/projects/temp/record_in" + ` i `, "wb").write(raw) buf = prototypes.buffer(raw) entry.readfrombuffer(buf, logtitle="phonebook data record") else: continue self.log("Read entry " + ` i ` + " - " + entry.name) pb_entry = self.extractphonebookentry(entry, result) pbook[i] = pb_entry #except Exception, e: # must disable this to prevent phone problems # self.disable_data_transfer() # raise Exception, e self.disable_data_transfer() self.progress(self.protocolclass.NUMSLOTS, self.protocolclass.NUMSLOTS, "Phone book read completed") result['phonebook'] = pbook return result
def getindex(self, indexfile): "Read an index file" index={} # Hack for LG-VX3200 - wallpaper index file is not real if re.search("ImageIndex", indexfile) is not None: # A little special treatment for wallpaper related media files # Sneek a peek at the file because if it is zero len we do not index it ind=0 for ifile in 'wallpaper', 'poweron', 'poweroff': ifilefull="download/"+ifile+".bit" try: mediafiledata=self.mediacache.readfile(ifilefull) if len(mediafiledata)!=0: index[ind]=ifile ind = ind + 1 self.log("Index file "+indexfile+" entry added: "+ifile) except: pass else: # A little special treatment for ringer related media files try: buf=prototypes.buffer(self.getfilecontents(indexfile)) except com_brew.BrewNoSuchFileException: # file may not exist return index g=self.protocolclass.indexfile() g.readfrombuffer(buf, logtitle="Read index file "+indexfile) for i in g.items: if i.index!=0xffff: ifile=re.sub("\.mid|\.MID", "", i.name) self.log("Index file "+indexfile+" entry added: "+ifile) index[i.index]=ifile return index
def get_content_file(self, key): index={} buf=prototypes.buffer(self.getfilecontents(self.protocolclass.content_file_name)) g=self.protocolclass.content_file() g.readfrombuffer(buf) self.logdata("Content file %s read with %d entries" % (self.protocolclass.content_file_name,len(g.items)), buf.getdata(), g) if key=='ringtone' or key=='ringtone-index': type='Ringers' index_const=self.protocolclass.ringerconst*0x100 indexfile=self.getindex(self.protocolclass.ringerindex) else: type='Screen Savers' index_const=self.protocolclass.imageconst*0x100 indexfile=self.getindex(self.protocolclass.imageindex) for i in g.items: if i.type=='!C' and i.content_type==type: try: ext=self.__reverse_mimetype[i.mime_type] found=False for j in indexfile.keys(): try: if int(common.stripext(indexfile[j]))==int(i.index1): index[j + index_const]=i.name1+'.'+ext found=True break; except: pass if not found: self.logdata("Unable to find index entry for "+i.name1+". Index : "+`i.index1`) except: pass return index, indexfile, index_const
def getfundamentals(self, results): """Gets information fundamental to interoperating with the phone and UI. Currently this is: - 'uniqueserial' a unique serial number representing the phone - 'groups' the phonebook groups This method is called before we read the phonebook data or before we write phonebook data. """ self.log("Retrieving fundamental phone information") self.log("Phone serial number") results['uniqueserial']=sha.new(self.getfilecontents("nvm/$SYS.ESN")).hexdigest() self.log(results) self.log("Reading group information") buf=prototypes.buffer(self.getfilecontents("pim/pbookgroup.dat")) g=self.protocolclass.pbgroups() g.readfrombuffer(buf) self.logdata("Groups read", buf.getdata(), g) groups={} for i in range(len(g.groups)): if len(g.groups[i].name): # sometimes have zero length names groups[i]={ 'group_id': g.groups[i].group_id, 'name': g.groups[i].name } results['groups']=groups self.getwallpaperindices(results) self.getringtoneindices(results) self.log("Fundamentals retrieved") return results
def amsanalyze(self,results): buf=prototypes.buffer(self.getfilecontents(self.protocolclass.AMSREGISTRY)) ams=self.protocolclass.amsregistry() ams.readfrombuffer(buf, logtitle="Read AMS registry") rt={} #Todd added for ringtone index nrt=0 #Todd added for ringtone index wp={} nwp=0 for i in range(ams.nfiles): filetype=ams.info[i].filetype if filetype: dir_ptr=ams.info[i].dir_ptr name_ptr=ams.info[i].name_ptr mimetype_ptr=ams.info[i].mimetype_ptr version_ptr=ams.info[i].version_ptr vendor_ptr=ams.info[i].vendor_ptr dir=self.getstring(ams.strings,dir_ptr) name=self.getstring(ams.strings,name_ptr) mimetype=self.getstring(ams.strings,mimetype_ptr) version=self.getstring(ams.strings,version_ptr) vendor=self.getstring(ams.strings,vendor_ptr) #downloaddomain_ptr=ams.info[i].downloaddomain_ptr print i, filetype, version, dir, vendor, name, mimetype #if downloaddomainptr_ptr: # print self.getstring(ams.strings,misc_ptr) print ams.info[i].num2, ams.info[i].num7, ams.info[i].num8, ams.info[i].num9, ams.info[i].num12, ams.info[i].num13, ams.info[i].num14, ams.info[i].num15, ams.info[i].num16, ams.info[i].num17 print " " # Todd's added info if filetype==12: #this will add the file extension if mimetype=="audio/vnd.qcelp": filetype='.qcp' elif mimetype=="audio/midi": filetype='.mid' elif mimetype=="application/x-pmd": filetype='.pmd' elif mimetype=="audio/mp3": filetype='.mp3' else: filetype='' rt[100+nrt]={'name':name+filetype,'location':'ams/'+dir,'origin':'ringers'} nrt+=1 elif filetype==13: if mimetype=="image/jpeg": filetype='.jpg' elif mimetype=="image/png": filetype='.png' elif mimetype=="image/gif": filetype='.gif' elif mimetype=="image/bmp": filetype='.bmp' else: filetype='' wp[100+nwp]={'name':name+filetype,'location':'ams/'+dir,'origin':'images'} nwp+=1 results['ringtone-index']=rt results['wallpaper-index']=wp
def getcalendar(self, result): res = {} # Read exceptions file first exceptions = self.getexceptions() # Now read schedule try: buf = prototypes.buffer(self.getfilecontents( self.calendarlocation)) if len(buf.getdata()) < 3: # file is empty, and hence same as non-existent raise com_brew.BrewNoSuchFileException() sc = self.protocolclass.schedulefile() sc.readfrombuffer(buf, logtitle="Calendar") for event in sc.events: # the vx8100 has a bad entry when the calender is empty # stop processing the calender when we hit this record if event.pos == 0: #invalid entry continue entry = bpcalendar.CalendarEntry() try: # delete events are still in the calender file but have garbage dates self.getcalendarcommon(entry, event) except ValueError: continue if self.protocolclass.CALENDAR_HAS_SEPARATE_END_TIME_AND_DATE: # MIC Unlike previous phones, the VX8300 passes the ringtone # via both the index, and a path. If the index is set to 100 # (0x64), then the ringtone information will be found in the # "ringpath", the last 256 bytes of the calendar packet. If # the index is between 0 and 15, inclusive, then it is using # one of the builtin ringers, and the ringpath is set to # null. try: if (event.ringtone == 100 ): # MIC Ringer is downloaded to phone or microSD entry.ringtone = common.basename(event.ringpath) else: # MIC Ringer is built-in entry.ringtone = self.builtinringtones[ event.ringtone] except: # hack, not having a phone makes it hard to figure out the best approach if entry.alarm == None: entry.ringtone = 'No Ring' else: entry.ringtone = 'Loud Beeps' else: entry.ringtone = result['ringtone-index'][ event.ringtone]['name'] # check for exceptions and remove them if event.repeat[3] and exceptions.has_key(event.pos): for year, month, day in exceptions[event.pos]: entry.suppress_repeat_entry(year, month, day) res[entry.id] = entry assert sc.numactiveitems == len(res) except com_brew.BrewNoSuchFileException: pass # do nothing if file doesn't exist result['calendar'] = res return result