ContactRestore.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/python3
  2. # coding=utf-8
  3. # Doc
  4. # Script to extract Contacts from Sailfish Contact SQLite DB located at
  5. #
  6. #
  7. # Links
  8. # FileFormatdescription: https://docs.fileformat.com/email/vcf/#vcf-30-example
  9. # Pytho vobject: http://eventable.github.io/vobject/
  10. # Version
  11. version=0.3
  12. # ChangeLog
  13. # 2021-08-03 - 0.1 - multiple E-Mails with different types are working correctly
  14. # 2021-08-09 - 0.2 - Phonenumbers with parameters, Addresses with parameters, E-Mail-Addresses with marameters
  15. # 2021-08-10 - 0.3 - load Avatars into VCards
  16. import sqlite3
  17. import vobject
  18. import uuid
  19. import argparse
  20. import os
  21. def DEBUG(debug,msg):
  22. if debug is True:
  23. print("..DEBUG: " + msg)
  24. parser = argparse.ArgumentParser(description='Restore SailfishOS 3 Contacts', epilog='This script was written to restore SailfishOS 3 contacts as VCF files. To see additional information, visit: https://wiki.siningsoft.de/doku.php?id=sailfishos:projects:sailfish_contacts_rescue' )
  25. parser.add_argument('--db','-d', required=True, help="Sqlite3 Database file usually /home/{nemo,defaultuser}/.local/share/system/Contacts/qtcontacts-sqlite/contacts.db")
  26. parser.add_argument('--output','-o',required=True, help="Output directory for vcf files")
  27. parser.add_argument('--avatars','-a',required=False, help='Avatar directory. If present otherwise we skip this block of avatars, means, no avatars at all')
  28. parser.add_argument('--debug',action="store_true",help="debugging output to identify problems")
  29. parser.add_argument('--version', action='version', version='%(prog)s ' + str(version))
  30. args = parser.parse_args()
  31. SQLconn = sqlite3.connect(args.db)
  32. try:
  33. SQLContCur = SQLconn.cursor()
  34. for row in SQLContCur.execute('SELECT * FROM Contacts'):
  35. # contactID abfragen
  36. contactID=row[0]
  37. familyN=row[6]
  38. givenN=row[4]
  39. fullN=row[1]
  40. cardfile=args.output + "/" + fullN.replace(" ","_") + ".vcf"
  41. # wir erstellen das Objekt
  42. vcf = vobject.vCard()
  43. vcf.add('uid').value = str(uuid.uuid4())
  44. #vcf.add('uid').value = "Testdaten"
  45. vcf.add('n').value = vobject.vcard.Name( family=familyN, given=givenN )
  46. vcf.add('fn').value =fullN
  47. print("exporting " + fullN + " to file " + cardfile)
  48. DEBUG(args.debug,"Contact " + fullN)
  49. # abfrage der Adressdaten
  50. SQLADRCur = SQLconn.cursor()
  51. for ADRrow in SQLADRCur.execute('SELECT * FROM Addresses JOIN Details on Details.detailId = Addresses.detailId where Addresses.contactId = ' + str(contactID)):
  52. if ADRrow[2] is not None:
  53. ADRstr=str(ADRrow[2])
  54. else:
  55. ADRstr=""
  56. if ADRrow[5] is not None:
  57. ADRcit=str(ADRrow[5])
  58. else:
  59. ADRcit=""
  60. if ADRrow[4] is not None:
  61. ADRreg=str(ADRrow[4])
  62. else:
  63. ADRreg=""
  64. if ADRrow[6] is not None:
  65. ADRcod=str(ADRrow[6])
  66. else:
  67. ADRcod=""
  68. if ADRrow[7] is not None:
  69. ADRcou=str(ADRrow[7])
  70. else:
  71. ADRcou=""
  72. DEBUG(args.debug,"Addressdata: street=" + ADRstr + " city=" + ADRcit + " region=" + ADRreg + " code=" + ADRcod + " country=" + ADRcou)
  73. adr = vcf.add('ADR').value = vobject.vcard.Address(street=ADRstr, city=ADRcit, region=ADRreg, code=ADRcod,country=ADRcou)
  74. ## Abfragen Organisation
  75. SQLORGCur = SQLconn.cursor()
  76. for ORGrow in SQLORGCur.execute('SELECT * from Organizations where contactId = ' + str(contactID)):
  77. org = vcf.add('ORG').value = [str(ORGrow[2]), str(ORGrow[6])]
  78. if ORGrow[4] is not None:
  79. title = vcf.add('TITLE').value = str(ORGrow[4])
  80. if ORGrow[3] is not None:
  81. role = vcf.add('ROLE').value = str(ORGrow[3])
  82. # Also parameters are possible. Could be read out
  83. # | columnID | column |
  84. # ----------------------------
  85. # | 0 | detailId |
  86. # | 1 | contactId |
  87. # | 2 | name |
  88. # | 3 | role |
  89. # | 4 | title |
  90. # | 5 | location |
  91. # | 6 | department |
  92. # | 7 | logoUrl |
  93. # | 8 | assistantName |
  94. ## Abfragen E-Mail-Adressen
  95. SQLEmailCur = SQLconn.cursor()
  96. for Emailrow in SQLEmailCur.execute('SELECT * from EmailAddresses JOIN Details on Details.detailId= EmailAddresses.detailId where EmailAddresses.contactId = ' + str(contactID)):
  97. # debug ausgabe
  98. DEBUG(args.debug,str(Emailrow[2]) + " at " + str(Emailrow[9]))
  99. email = vcf.add('email')
  100. email.value = str(Emailrow[2])
  101. # nur den Typ einpflegen, wenn das hier nicht none ist
  102. if Emailrow[9] != None:
  103. email.type_param = str(Emailrow[9])
  104. SQLPhoneCur = SQLconn.cursor()
  105. ## Abfragen Telefonnummer, Fax, SMS - Nummern kommen aus der gleichen Tabelle
  106. for Phonerow in SQLPhoneCur.execute('SELECT * from PhoneNumbers JOIN Details on Details.detailId = PhoneNumbers.detailId where PhoneNumbers.contactId = ' + str(contactID)):
  107. # wir müssen die SubTypen unterscheiden
  108. #Null voice
  109. #1 cell
  110. #2 fax
  111. #3 pager
  112. #6 video
  113. #10 Assistent
  114. # None is a normal phone Number
  115. if Phonerow[3] == "1":
  116. phcat='cell'
  117. elif Phonerow[3] == "2":
  118. phcat='fax'
  119. elif Phonerow[3] == "3":
  120. phcat='pager'
  121. elif Phonerow[3] == "6":
  122. phcat='video'
  123. elif Phonerow[3] == "10":
  124. phcat='assistent'
  125. elif Phonerow[3] is None:
  126. phcat='voice'
  127. # debug ausgabe
  128. DEBUG(args.debug,str(Phonerow[2]) + " at " + str(Phonerow[10]) + " as subtype=" + str(Phonerow[3]) + "=" + phcat)
  129. phone = vcf.add(phcat).value = str(Phonerow[2])
  130. # nur den Typ einpflegen, wenn das hier nicht none ist
  131. if Phonerow[10] != None:
  132. try:
  133. phone.type_param = str(Phonerow[10])
  134. except AttributeError:
  135. continue
  136. if args.avatars is not None:
  137. DEBUG(args.debug,"Avatar Argument given")
  138. SQLAVTRCur = SQLconn.cursor()
  139. ## get Avatar Filelink from DB
  140. for AVTRrow in SQLAVTRCur.execute('SELECT imageURL from Avatars where contactId = ' + str(contactID)):
  141. DEBUG(args.debug,"found PHOTO entry")
  142. if AVTRrow[0] is not None:
  143. avatarfile=os.path.split(AVTRrow[0])[1]
  144. # pre-checks
  145. # - is it a file
  146. # - is it jpg
  147. import mimetypes
  148. afile=args.avatars + "/" + avatarfile
  149. DEBUG(args.debug,"Avatar File: " + afile + " mimetype: " + str(mimetypes.guess_type(afile)))
  150. if os.path.isfile(afile) and mimetypes.guess_type(afile)[0] == "image/jpeg":
  151. DEBUG(args.debug,"found file " + afile)
  152. import base64
  153. # actions
  154. # - encode base24 to variable
  155. # - add to vcard
  156. fileopen=open(afile,'rb')
  157. bfile=base64.b64encode(fileopen.read())
  158. fileopen.close()
  159. # https://stackoverflow.com/a/61532783
  160. photo = vcf.add('PHOTO;ENCODING=b;TYPE=image/jpeg')
  161. photo.value = str(bfile.decode('utf-8'))
  162. else:
  163. print("file " + afile + " not found or no JPG")
  164. # Output to file
  165. f = open(cardfile,'w')
  166. f.write(vcf.serialize())
  167. f.close()
  168. # hier brauchen wir einige eception handles -> wie bekommen wir die einzelnen exceptions heruas ?
  169. #except:
  170. #print("Error in executing SQL")
  171. except AttributeError:
  172. print("Datatype mismatch")
  173. raise
  174. # das generöse Except am Ende
  175. except:
  176. print("unhandled error")
  177. raise