Ejemplo n.º 1
0
 def savephonebook(self, data):
     # brute force, it is faster, otherwise we would have to
     # examine each entry to see if it was there and then decide what
     # to do with it, deleting and re-writing is faster and what the user
     # seleted with "OVERWRITE"
     self.log("New phonebook\n" + common.prettyprintdict(data['phonebook']))
     pb = data['phonebook']
     keys = pb.keys()
     keys.sort()
     keys = keys[:self.protocolclass.NUMSLOTS]
     self.enable_data_transfer()
     try:
         # delete the old phonebook
         self.rmfile("D/APL/SWAP/DIAG_APSWP_MEMORY")
         for i in range(self.protocolclass.NUMSLOTS):
             self.deletepbentry(i)
         # create the new phonebook
         for i in range(len(keys)):
             slot = keys[i]
             entry = self.makephonebookentry(pb[slot])
             self.progress(i, len(keys), "Writing " + entry.name)
             self.log('Writing entry ' + ` slot ` + " - " + entry.name)
             self.sendpbentrytophone(entry)
     except Exception, e:
         # must disable this to prevent phone problems
         self.disable_data_transfer()
         raise Exception, e
Ejemplo n.º 2
0
    def savephonebook(self, data):
        self.log("Saving group information")

        for gid in range(
                1, self.protocolclass._NUMGROUPS):  # do not save group 0 - All
            name = data['groups'].get(gid, {'name': ''})['name']
            req = self.protocolclass.writegroupentryrequest()
            req.number = gid
            req.anothernumber = gid
            req.name = name
            req.nummembers = data['groups'].get(gid, {'members': 0})['members']
            self.log("Group #%d %s - %d members" %
                     (gid, ` name `, req.nummembers))
            self.sendpbcommand(req, self.protocolclass.writegroupentryresponse)

        self.log("New phonebook\n" + common.prettyprintdict(data['phonebook']))

        # in theory we should offline the phone and wait two seconds first ...

        pb = data['phonebook']
        keys = pb.keys()
        keys.sort()
        keys = keys[:self.protocolclass._NUMSLOTS]
        # work out the bitmap.
        slots = []
        for i in range(self.protocolclass._NUMSLOTS):
            if i not in keys:
                slots.append(0)
                continue
            bmp = 0
            e = pb[i]
            if len(e['mobile']): bmp |= 1
            if len(e['home']): bmp |= 2
            if len(e['office']): bmp |= 4
            if len(e['pager']): bmp |= 8
            if len(e['fax']): bmp |= 16
            if len(e['email']): bmp |= 32
            if len(e['wireless']): bmp |= 64
            slots.append(bmp)
        slots = "".join([chr(x) for x in slots])
        req = self.protocolclass.writepbslotsrequest()
        req.present = slots
        self.sendpbcommand(req, self.protocolclass.writepbslotsresponse)
        # now write out each slot
        for i in range(len(keys)):
            slot = keys[i]
            req = self.protocolclass.writepbentryrequest()
            req.slotnumber = slot
            req.entry = self.makephonebookentry(pb[slot])
            self.log('Writing entry ' + ` slot ` + " - " + req.entry.name)
            self.progress(i, len(keys), "Writing " + req.entry.name)
            self.sendpbcommand(req, self.protocolclass.writepbentryresponse)
        self.progress(
            len(keys) + 1,
            len(keys) + 1,
            "Phone book write completed - phone will be rebooted")
        data['rebootphone'] = True
        return data
Ejemplo n.º 3
0
    def savephonebook(self, data):
        self.log("Saving group information")

        for gid in range(1, self.protocolclass._NUMGROUPS): # do not save group 0 - All
            name=data['groups'].get(gid, {'name': ''})['name']
            req=self.protocolclass.writegroupentryrequest()
            req.number=gid
            req.anothernumber=gid
            req.name=name
            req.nummembers=data['groups'].get(gid, {'members': 0})['members']
            self.log("Group #%d %s - %d members" % (gid, `name`, req.nummembers))
            self.sendpbcommand(req, self.protocolclass.writegroupentryresponse)

        
        self.log("New phonebook\n"+common.prettyprintdict(data['phonebook']))
    
        # in theory we should offline the phone and wait two seconds first ...

        pb=data['phonebook']
        keys=pb.keys()
        keys.sort()
        keys=keys[:self.protocolclass._NUMSLOTS]
        # work out the bitmap.
        slots=[]
        for i in range(self.protocolclass._NUMSLOTS):
            if i not in keys:
                slots.append(0)
                continue
            bmp=0
            e=pb[i]
            if len(e['mobile']): bmp|=1
            if len(e['home']):   bmp|=2
            if len(e['office']): bmp|=4
            if len(e['pager']):   bmp|=8
            if len(e['fax']):   bmp|=16
            if len(e['email']):   bmp|=32
            if len(e['wireless']):   bmp|=64
            slots.append(bmp)
        slots="".join([chr(x) for x in slots])
        req=self.protocolclass.writepbslotsrequest()
        req.present=slots
        self.sendpbcommand(req, self.protocolclass.writepbslotsresponse)
        # now write out each slot
        for i in range(len(keys)):
            slot=keys[i]
            req=self.protocolclass.writepbentryrequest()
            req.slotnumber=slot
            req.entry=self.makephonebookentry(pb[slot])
            self.log('Writing entry '+`slot`+" - "+req.entry.name)
            self.progress(i, len(keys), "Writing "+req.entry.name)
            self.sendpbcommand(req, self.protocolclass.writepbentryresponse)
        self.progress(len(keys)+1, len(keys)+1, "Phone book write completed - phone will be rebooted")
        data['rebootphone']=True
        return data
	def __repr__(self):

        str="Version: %s\n" % (`self.version()`)

        str+="Origin: %s\n" % (`self.origin()`)

        str+=common.prettyprintdict(self._data)

        return str+"\n"

	"A single vcard"
 def savephonebook(self, data):
     self.log("New phonebook\n"+common.prettyprintdict(data['phonebook']))
     pb=data['phonebook']
     keys=pb.keys()
     keys.sort()
     keys=keys[:self.protocolclass.NUMSLOTS]
     self.enable_data_transfer()
     try:
         self.rmfile("D/APL/SWAP/DIAG_APSWP_MEMORY")
         for i in range(self.protocolclass.NUMSLOTS):
             self.deletepbentry(i)
         for i in range(len(keys)):
             slot=keys[i]
             entry=self.makephonebookentry(pb[slot])
             self.progress(i, len(keys), "Writing "+entry.name)
             self.log('Writing entry '+`slot`+" - "+entry.name)
             self.sendpbentrytophone(entry)
     except Exception, e:
         self.disable_data_transfer()
         raise Exception, e 
	def getcontactspbformat(self):

        "returns contacts in a format suitable for the BitPim phonebook importer"

        for c in self.getcontacts():

            res={}

            res['Name']=c['fn']

            res['First Name']=c['n_given']

            res['Middle Name']=c['n_middle']

            res['Last Name']=c['n_family']

            res['UniqueSerial-id']=c['id']

            res['UniqueSerial-sourcetype']='egroupware'

            for t,prefix in ("business", "adr_one"), ("home", "adr_two"):

                a={}

                for p2,k in ("_street", "street"), ("_locality", "city"), ("_region", "state"), \
                        ("_postalcode", "postalcode"), ("_countryname", "country"):

                    if len(c.get(prefix+p2,"")): a[k]=c[prefix+p2]

                if t=="business" and len(c.get("org_name", "")): a['company']=c["org_name"]

                if len(a):

                    a['type']=t

                    aa="Address"

                    if aa in res:

                        aa+="2"

                        assert aa not in res

                    res[aa]=a

            cats=[]

            ccats=c.get("cat_id", "")

            if len(ccats): 

                for cat in ccats:

                    cats.append(ccats[cat])

                if len(cats):

                    res["Categories"]=cats

            suf=""

            if len(c.get("email","")):

                res["Email Address"]={'email': c['email'], 'type': 'business'}

                suf="2"

            if len(c.get("email_home", "")):

                res["Email Address"+suf]={'email': c['email_home'], 'type': 'home'}

            res["Home Phone"]=c['tel_home']

            res["Mobile Phone"]=c['tel_cell'] 

            res["Business Fax"]=c['tel_fax']

            res["Pager"]=c['tel_pager'] 

            res["Business Phone"]=c['tel_work']

            res['Notes']=c['note']

            res['Business Web Page']=c['url']

            res=dict([(k,v) for k,v in res.items() if len(v)])

            yield res

	def getcategories(self):

        "Get the list of categories"

        return [v for k,v in self.sp.addressbook.boaddressbook.categories(True).items()]


if __name__=='__main__':

    import sys

    import common

    s=getsession(*sys.argv[1:])

    for v in s.getcategories():

        print common.prettyprintdict(v)


if __name__=='__main__':

    import sys

    import common

    s=getsession(*sys.argv[1:])

    for v in s.getcategories():

        print common.prettyprintdict(v)
Ejemplo n.º 7
0
            res["Business Fax"]=c['tel_fax']
            res["Pager"]=c['tel_pager'] # nb: in eGroupware this is business pager
            res["Business Phone"]=c['tel_work']
            # various other fields
            res['Notes']=c['note']
            res['Business Web Page']=c['url']

            # filter out empty fields
            res=dict([(k,v) for k,v in res.items() if len(v)])
            yield res

    def getcategories(self):
        "Get the list of categories"
        # egroupware returns a dict with each key being an asciized integer
        # id.  The same field is present in the dict value, so we just return
        # the values
        return [v for k,v in self.sp.addressbook.boaddressbook.categories(True).items()]
    
            
if __name__=='__main__':
    import sys
    import common
    s=getsession(*sys.argv[1:])
    for v in s.getcategories():
        print common.prettyprintdict(v)
    #for n,i in enumerate(s.getcontacts()):
    #    print n,common.prettyprintdict(i)
        
        #print n,i.get('id',""),i.get('n_given', ""),i.get('n_family', "")
    
Ejemplo n.º 8
0
 def __repr__(self):
     str = "Version: %s\n" % ( ` self.version() `)
     str += "Origin: %s\n" % ( ` self.origin() `)
     str += common.prettyprintdict(self._data)
     # str+=`self.lines`
     return str + "\n"
Ejemplo n.º 9
0
 def __repr__(self):
     str="Version: %s\n" % (`self.version()`)
     str+="Origin: %s\n" % (`self.origin()`)
     str+=common.prettyprintdict(self._data)
     # str+=`self.lines`
     return str+"\n"
Ejemplo n.º 10
0
            res["Business Fax"]=c['tel_fax']
            res["Pager"]=c['tel_pager'] # nb: in eGroupware this is business pager
            res["Business Phone"]=c['tel_work']
            # various other fields
            res['Notes']=c['note']
            res['Business Web Page']=c['url']

            # filter out empty fields
            res=dict([(k,v) for k,v in res.items() if len(v)])
            yield res

    def getcategories(self):
        "Get the list of categories"
        # egroupware returns a dict with each key being an asciized integer
        # id.  The same field is present in the dict value, so we just return
        # the values
        return [v for k,v in self.sp.addressbook.boaddressbook.categories(True).items()]
    
            
if __name__=='__main__':
    import sys
    import common
    s=getsession(*sys.argv[1:])
    for v in s.getcategories():
        print common.prettyprintdict(v)
    #for n,i in enumerate(s.getcontacts()):
    #    print n,common.prettyprintdict(i)
        
        #print n,i.get('id',""),i.get('n_given', ""),i.get('n_family', "")
    
	def savephonebook(self, data):

        self.log("Saving group information")

        for gid in range(1, self.protocolclass._NUMGROUPS): 

            name=data['groups'].get(gid, {'name': ''})['name']

            req=self.protocolclass.writegroupentryrequest()

            req.number=gid

            req.anothernumber=gid

            req.name=name

            req.nummembers=data['groups'].get(gid, {'members': 0})['members']

            self.log("Group #%d %s - %d members" % (gid, `name`, req.nummembers))

            self.sendpbcommand(req, self.protocolclass.writegroupentryresponse)

        self.log("New phonebook\n"+common.prettyprintdict(data['phonebook']))

        pb=data['phonebook']

        keys=pb.keys()

        keys.sort()

        keys=keys[:self.protocolclass._NUMSLOTS]

        slots=[]

        for i in range(self.protocolclass._NUMSLOTS):

            if i not in keys:

                slots.append(0)

                continue

            bmp=0

            e=pb[i]

            if len(e['mobile']): bmp|=1

            if len(e['home']):   bmp|=2

            if len(e['office']): bmp|=4

            if len(e['pager']):   bmp|=8

            if len(e['fax']):   bmp|=16

            if len(e['email']):   bmp|=32

            if len(e['wireless']):   bmp|=64

            slots.append(bmp)

        slots="".join([chr(x) for x in slots])

        req=self.protocolclass.writepbslotsrequest()

        req.present=slots

        self.sendpbcommand(req, self.protocolclass.writepbslotsresponse)

        for i in range(len(keys)):

            slot=keys[i]

            req=self.protocolclass.writepbentryrequest()

            req.slotnumber=slot

            req.entry=self.makephonebookentry(pb[slot])

            self.log('Writing entry '+`slot`+" - "+req.entry.name)

            self.progress(i, len(keys), "Writing "+req.entry.name)

            self.sendpbcommand(req, self.protocolclass.writepbentryresponse)

        self.progress(len(keys)+1, len(keys)+1, "Phone book write completed - phone will be rebooted")

        data['rebootphone']=True

        return data

	def sendpbcommand(self, request, responseclass):

        self.setmode(self.MODEBREW)

        buffer=prototypes.buffer()

        request.writetobuffer(buffer)

        data=buffer.getvalue()

        self.logdata("audiovox cdm8900 phonebook request", data, request)

        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

        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:]

        data=common.pppunescape(data)

        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:]

        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)

        self.logdata("Audiovox phonebook response", data, responseclass)

        buffer=prototypes.buffer(data)

        res=responseclass()

        res.readfrombuffer(buffer)

        return res

	"Talk to Audiovox CDM 8900 cell phone"

class  Profile (com_phone.Profile) :
	protocolclass=Phone.protocolclass
	    serialsname=Phone.serialsname
	    WALLPAPER_WIDTH=128
	    WALLPAPER_HEIGHT=145
	    WALLPAPER_CONVERT_FORMAT="jpg"
	    MAX_WALLPAPER_BASENAME_LENGTH=16
	    WALLPAPER_FILENAME_CHARS="abcdefghijklmnopqrstuvwxyz0123456789 ."
	    MAX_RINGTONE_BASENAME_LENGTH=16
	    RINGTONE_FILENAME_CHARS="abcdefghijklmnopqrstuvwxyz0123456789 ."
	    usbids=( (0x106c, 0x2101, 1), 
        )
	    deviceclasses=("modem",)
	    _supportedsyncs=(
        ('phonebook', 'read', None),         
        ('phonebook', 'write', 'OVERWRITE'), 
        )
	    def _getgroup(self, name, groups):

        for key in groups:

            if groups[key]['name']==name:

                return key,groups[key]

        return None,None

	def normalisegroups(self, helper, data):

        "Assigns groups based on category data"

        keys=data['groups'].keys()

        keys.sort()

        pad=[data['groups'][k]['name'] for k in keys if k] 

        groups=helper.getmostpopularcategories(self.protocolclass._NUMGROUPS, data['phonebook'], ["All", "Business", "Personal", "Etc."],
                                               self.protocolclass._MAXGROUPLEN, pad)

        groups.sort()

        newgroups={}

        newgroups[0]={'name': 'All', 'members': 0}

        for name in groups:

            if name=="All": continue

            key,value=self._getgroup(name, data['groups'])

            if key is not None and key!=0:

                newgroups[key]=value

                newgroups[key]['members']=0

        for name in groups:

            key,value=self._getgroup(name, newgroups)

            if key is None:

                for key in range(1,10000):

                    if key not in newgroups:

                        newgroups[key]={'name': name, 'members': 0}

                        break

        data['groups']=newgroups

	def convertphonebooktophone(self, helper, data):

        """Converts the data to what will be used by the phone
        @param data: contains the dict returned by getfundamentals
                 as well as where the results go"""

        self.normalisegroups(helper, data)

        results={}

        pb=data['phonebook']

        slots=[ (helper.getserial(pb[pbentry].get("serials", []), self.serialsname, data['uniqueserial'], "slot", None), pbentry)
                for pbentry in pb]

        slots.sort() 

        newones=[(pbentry,slot) for slot,pbentry in slots if slot is None]

        existing=[(pbentry,slot) for slot,pbentry in slots if slot is not None]

        for pbentry,slot in newones+existing:

            if len(results)==self.protocolclass._NUMSLOTS:

                break

            try:

                e={} 

                entry=data['phonebook'][pbentry]

                e['mobile']=self.phonize(helper.getnumber(entry.get('numbers', []), 'cell'))

                e['home']=self.phonize(helper.getnumber(entry.get('numbers', []), 'home'))

                e['office']=self.phonize(helper.getnumber(entry.get('numbers', []), 'office'))

                e['pager']=self.phonize(helper.getnumber(entry.get('numbers', []), 'pager'))

                e['fax']=self.phonize(helper.getnumber(entry.get('numbers', []), 'fax'))

                emails=helper.getemails(entry.get('emails', []), 0, 2, self.protocolclass._MAXEMAILLEN)

                e['email']=""

                e['wireless']=""

                if len(emails)>=1:

                    e['email']=emails[0]

                    if len(emails)>=2:

                        e['wireless']=emails[1]

                if max([len(e[field]) for field in e])==0:

                    continue

                e['name']=helper.getfullname(entry.get('names', [ {'full': ''}]), 1, 1, self.protocolclass._MAXNAMELEN)[0]

                e['memo']=helper.getmemos(entry.get('memos', [{'memo': ''}]), 1,1, self.protocolclass._MAXMEMOLEN)[0]

                rt=helper.getringtone(entry.get('ringtones', []), 'call', "")

                if rt.startswith("avox "):

                    e['ringtone']=int(rt[5:])

                rt=helper.getringtone(entry.get('ringtones', []), 'message', "")

                if rt.startswith("avox "):

                    e['msgringtone']=int(rt[5:])

                wp=helper.getwallpaper(entry.get('wallpapers', []), 'call', "")

                if wp.startswith("avox "):

                    e['wallpaper']=int(wp[5:])

                e['secret']=helper.getflag(entry.get('flags',[]), 'secret', False)

                group=helper.getcategory(entry.get('categories', [{'category': 'Etc.'}]),1,1,self.protocolclass._MAXGROUPLEN)[0]

                gid,_=self._getgroup(group, data['groups'])

                if gid is None or gid==0:

                    gid,_=self._getgroup("Etc.", data['groups'])

                assert gid!=0

                e['group']=gid

                data['groups'][gid]['members']+=1

                if slot is None or slot<0 or slot>=self.protocolclass._NUMSLOTS or slot in results:

                    for i in range(100000):

                        if i not in results:

                            slot=i

                            break

                results[slot]=e

            except helper.ConversionFailed:

                continue

        data['phonebook']=results

        return data

	def phonize(self, str):

        """Convert the phone number into something the phone understands
        All digits, P, T, *, #  are kept, everything else is removed.
        In theory the phone can store a dash in the phonebook, but that
        is not normal."""

        return re.sub("[^0-9PT#*]", "", str)[:self.protocolclass._MAXPHONENUMBERLEN]