def dump_dir(c, src_path, dest_path): src_path = src_path.strip("/") # since some people may still be holding back progress with Python 2, I'll support # them for now and not use the Python 3 exists_ok option :( try: os.makedirs(dest_path) except OSError as e: pass # Access the list of vcards in the directory hdrs, cards = c.get(src_path, header_list=[headers.Type(b'x-bt/MAP-msg-listing')]) # Parse the XML response to the previous request. # Extract a list of file names in the directory names = [] try: root = ElementTree.fromstring(cards) except ElementTree.ParseError: root = ElementTree.fromstring(escape_ampersands(cards)) dump_xml(root, "/".join([dest_path, "mlisting.xml"])) for card in root.findall("msg"): names.append(card.attrib["handle"]) c.setpath(src_path) # get all the files for name in names: get_file(c, name, "/".join([dest_path, name]), folder_name=src_path) # return to the root directory depth = len([f for f in src_path.split("/") if len(f)]) for i in range(depth): c.setpath(to_parent=True)
def capability(self): """capability(self) Returns a capability object from the server. An exception will pass through if there is an error. """ hdrs, data = self.get(header_list=[headers.Type(b"x-obex/capability")]) return data
def get_file(c, src_path, dest_path, folder_name=None, book=True): if book: mimetype = b'x-bt/phonebook' else: mimetype = b'x-bt/vcard' try: hdrs, card = c.get(src_path, header_list=[headers.Type(mimetype)]) write_file(dest_path, card) logging.info('%s save!' % dest_path) return card except Exception as e: logging.exception('Exception in get data!: %s' % e) return False
def get_file(c, src_path, dest_path, verbose=True, folder_name=None): if verbose: if folder_name is not None: print("Fetching %s/%s" % (folder_name, src_path)) else: print("Fetching %s" % src_path) # include attachments, use UTF-8 encoding req_hdrs = [ headers.Type(b'x-bt/message'), headers.App_Parameters(b'\x0A\x01\x01\x14\x01\x01') ] hdrs, card = c.get(src_path, header_list=req_hdrs) with open(dest_path, 'wb') as f: f.write(card)
def get_file(c, src_path, dest_path, verbose=True, folder_name=None, book=False): if verbose: if folder_name is not None: print("Fetching %s/%s" % (folder_name, src_path)) else: print("Fetching %s" % src_path) if book: mimetype = b'x-bt/phonebook' else: mimetype = b'x-bt/vcard' hdrs, card = c.get(src_path, header_list=[headers.Type(mimetype)]) with open(dest_path, 'wb') as f: f.write(card)
def dump_dir(c, src_path, dest_path): src_path = src_path.strip("/") # since some people may still be holding back progress with Python 2, I'll support # them for now and not use the Python 3 exist_ok option :( try: os.makedirs(dest_path) except OSError as e: pass # Access the list of vcards in the directory hdrs, cards = c.get(src_path, header_list=[headers.Type(b'x-bt/vcard-listing')]) if len(cards) == 0: print("WARNING: %s is empty, skipping", src_path) return # Parse the XML response to the previous request. # Extract a list of file names in the directory names = [] root = parse_xml(cards) dump_xml(root, "/".join([dest_path, "listing.xml"])) for card in root.findall("card"): names.append(card.attrib["handle"]) c.setpath(src_path) # get all the files for name in names: fname = "/".join([dest_path, name]) try: get_file(c, name, fname, folder_name=src_path) except OBEXError as e: print("Failed to fetch", fname, e) # return to the root directory depth = len([f for f in src_path.split("/") if len(f)]) for i in range(depth): c.setpath(to_parent=True)
def listdir(self, name="", xml=False): """listdir(self, name = "") Requests information about the contents of the directory with the specified name relative to the current directory for the session. If the name is omitted or an empty string is supplied, the contents of the current directory are typically listed by the server. If successful, the server will provide an XML folder listing. If the xml argument is true, the XML listing will be returned directly. Else, this function will parse the XML and return a tuple of two lists, the first list being the folder names, and the second list being file names. """ hdrs, data = self.get( name, header_list=[headers.Type(b"x-obex/folder-listing", False)]) if xml: return data tree = parse_xml(data) folders = [] files = [] for e in tree: if e.tag == "folder": folders.append(e.attrib["name"]) elif e.tag == "file": files.append(e.attrib["name"]) elif e.tag == "parent-folder": pass # ignore it else: sys.stderr.write("Unknown listing element %s\n" % e.tag) return folders, files
def loadPhonebook(self): device_address=self.getConnectedDevice() encoding = locale.getdefaultlocale()[1] service = self.findService("Phonebook") if service: port = find_service("pbap", device_address) c = client.Client(device_address, port) uuid = b"\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66" c.connect(header_list=[headers.Target(uuid)]) prefix = "" database="/media/pi/pyCar/Phone/Phonebooks/" + device_address.replace(":", "_") + ".db" ### delete database ### if os.path.exists(database): os.remove(database) ### create the database ### conn = sqlite3.connect(database) cursor = conn.cursor() cursor.execute("""CREATE TABLE names (uid text, first_name text, surname text)""") cursor.execute("""CREATE TABLE numbers (uid text, number text, type text)""") cursor = conn.cursor() # Access the list of vcards in the phone's internal phone book. hdrs, cards = c.get(prefix+"telecom/pb", header_list=[headers.Type(b"x-bt/vcard-listing")]) # Parse the XML response to the previous request. root = ElementTree.fromstring(cards) # Examine each XML element, storing the file names we find in a list, and # printing out the file names and their corresponding contact names. names = [] for card in root.findall("card"): try: names.append(card.attrib["handle"]) except: pass # Request all the file names obtained earlier. c.setpath(prefix + "telecom/pb") uid=1 for name in names: hdrs, card = c.get(name, header_list=[headers.Type(b"x-bt/vcard")]) #print(card) parsed=self.parse(card) gotNumber=False if len(parsed["phone"])>0: for value in parsed["phone"]: try: number=parsed["phone"][value]["number"] cursor.execute("INSERT INTO numbers VALUES ('" + str(uid) +"', '"+ number +"', '"+ parsed["phone"][value]["type"] +"')") conn.commit() if number[:1]=="0": number="+49"+number[1:] cursor.execute("INSERT INTO numbers VALUES ('" + str(uid) +"', '"+ number +"', '"+ parsed["phone"][value]["type"] +"')") conn.commit() gotNumber=True except: pass if(gotNumber): print("INSERT INTO names VALUES ('" + str(uid) +"', '"+ parsed["first_name"] +"', '"+ parsed["surname"] +"')") cursor.execute("INSERT INTO names VALUES ('" + str(uid) +"', '"+ parsed["first_name"] +"', '"+ parsed["surname"] +"')") conn.commit() uid+=1 c.disconnect()
sys.exit(1) port = d[0]["port"] # Use the generic Client class to connect to the phone. c = client.Client(device_address, port) uuid = b"\x79\x61\x35\xf0\xf0\xc5\x11\xd8\x09\x66\x08\x00\x20\x0c\x9a\x66" result = c.connect(header_list=[headers.Target(uuid)]) if not isinstance(result, responses.ConnectSuccess): sys.stderr.write("Failed to connect to phone.\n") sys.exit(1) # Access the list of vcards in the phone's internal phone book. hdrs, cards = c.get(prefix + "telecom/pb", header_list=[headers.Type(b"x-bt/vcard-listing")]) # Parse the XML response to the previous request. root = ElementTree.fromstring(cards) print("\nAvailable cards in %stelecom/pb\n" % prefix) # Examine each XML element, storing the file names we find in a list, and # printing out the file names and their corresponding contact names. names = [] for card in root.findall("card"): print("%s: %s" % (card.attrib["handle"], card.attrib["name"])) names.append(card.attrib["handle"]) print("\nCards in %stelecom/pb\n" % prefix)