ContactRestore.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. # Projects Page: https://wiki.siningsoft.de/doku.php?id=sailfishos:projects:sailfish_contacts_rescue
  9. # FileFormatdescription: https://docs.fileformat.com/email/vcf/#vcf-30-example
  10. # Pytho vobject: http://eventable.github.io/vobject/
  11. # Version
  12. version=0.7
  13. # ChangeLog
  14. # 2021-08-03 - 0.1 - multiple E-Mails with different types are working correctly
  15. # 2021-08-09 - 0.2 - Phonenumbers with parameters, Addresses with parameters, E-Mail-Addresses with marameters
  16. # 2021-08-10 - 0.3 - load Avatars into VCards
  17. # 2021-08-28 - 0.4 - bugfixing after full exporting my contacts
  18. # - Address export fixing
  19. # 2021-09-18 - 0.5 - bugfixing wrong table column mapping
  20. # 2021-09-21 - 0.6 - changing table mapping, adding fix for phonenumber categories
  21. # 2021-10-14 - 0.7 - output to one file
  22. import sqlite3
  23. import vobject
  24. import uuid
  25. import argparse
  26. import os
  27. #class vobject2(vobject):
  28. def DEBUG(debug,msg):
  29. if debug is True:
  30. print("..DEBUG: " + msg)
  31. # will return a default value, when var is None
  32. def setDefault(var, default):
  33. if var is None:
  34. return default
  35. else:
  36. return var
  37. 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' )
  38. parser.add_argument('--db','-d', required=True, help="Sqlite3 Database file usually /home/{nemo,defaultuser}/.local/share/system/Contacts/qtcontacts-sqlite/contacts.db")
  39. parser.add_argument('--output','-o',required=True, help="Output directory for vcf files.'")
  40. parser.add_argument('--outsinglefile','-f',required=False,help="If specefied, a file with that name is created under specified path, contianing all VCard entrie. E.G. your address book")
  41. parser.add_argument('--avatars','-a',required=False, help='Avatar directory. If present otherwise we skip this block of avatars, means, no avatars at all')
  42. parser.add_argument('--debug',action="store_true",help="debugging output to identify problems")
  43. parser.add_argument('--version', action='version', version='%(prog)s ' + str(version))
  44. args = parser.parse_args()
  45. try:
  46. SQLconn = sqlite3.connect(args.db)
  47. SQLconn.row_factory = sqlite3.Row #das macht den Unterschied und liefert die Werte
  48. # only this, when fullfile is specified:
  49. if args.outsinglefile is not None:
  50. outfile=args.outsinglefile.replace(" ","_").replace("(","").replace(")","").replace(",","")
  51. ofile = open(outfile,'w')
  52. osf=True
  53. else:
  54. osf=False
  55. SQLContCur = SQLconn.cursor()
  56. SQLContCur.execute('SELECT * FROM Contacts')
  57. rows = SQLContCur.fetchall()
  58. for row in rows:
  59. # contactID abfragen
  60. contactID=setDefault(row['contactId'],"NA")
  61. familyN=setDefault(row['lastName'],"NA")
  62. givenN=setDefault(row['firstName'],"NA")
  63. FullLabel=setDefault(row['displayLabel'],"NA")
  64. if (familyN == "NA" and givenN == "NA") and FullLabel != "NA":
  65. fullN = FullLabel
  66. else:
  67. fullN = givenN + " " + familyN
  68. #fullN=setDefault(row['displayLabel'],"NA")
  69. cardfile=args.output + "/" + fullN.replace(" ","_").replace("(","").replace(")","").replace(".","").replace(",","") + ".vcf"
  70. # wir erstellen das Objekt
  71. vcf = vobject.vCard()
  72. vcf.add('uid').value = str(uuid.uuid4())
  73. #vcf.add('uid').value = "Testdaten"
  74. vcf.add('n').value = vobject.vcard.Name( family=familyN, given=givenN )
  75. vcf.add('fn').value =fullN
  76. print("exporting " + fullN + " to file " + cardfile)
  77. DEBUG(args.debug,"Contact " + str(fullN) + " family-name=" + str(familyN) + " given-name=" + str(givenN) + " displayLabel=" + str(FullLabel))
  78. # abfrage der Adressdaten
  79. SQLADRCur = SQLconn.cursor()
  80. SQLADRCur.execute('SELECT * FROM Addresses JOIN Details on Addresses.detailId = Details.detailId where Addresses.contactId = ' + str(contactID))
  81. ADRrows = SQLADRCur.fetchall()
  82. for ADRrow in ADRrows:
  83. if ADRrow['street'] is not None:
  84. ADRstr=str(ADRrow['street'])
  85. else:
  86. ADRstr="NA"
  87. if ADRrow['locality'] is not None:
  88. ADRcit=str(ADRrow['locality'])
  89. else:
  90. ADRcit="NA"
  91. if ADRrow['region'] is not None:
  92. ADRreg=str(ADRrow['region'])
  93. else:
  94. ADRreg="NA"
  95. if ADRrow['postCode'] is not None:
  96. ADRcod=str(ADRrow['postCode'])
  97. else:
  98. ADRcod="NA"
  99. if ADRrow['country'] is not None:
  100. ADRcou=str(ADRrow['country'])
  101. else:
  102. ADRcou="NA"
  103. # we need to know the context we've read here
  104. # 2021-09-19 - it figured out, that this might cause a call of AddressBehaviour for Address.replace(***)
  105. #if ADRrow[14] is not None:
  106. # addADR="ADR;TYPE="+str(ADRrow[14])
  107. #else:
  108. # addADR="ADR"
  109. vcf.add("ADR").value = vobject.vcard.Address(street=ADRstr, city=ADRcit, region=ADRreg, code=ADRcod,country=ADRcou)
  110. #adr = vcf.add(addADR).value = vobject.vcard.Address()
  111. DEBUG(args.debug,"Addressdata: street=" + ADRstr + " city=" + ADRcit + " region=" + ADRreg + " code=" + ADRcod + " country=" + ADRcou + " context=" + str(ADRrow[14]))
  112. ## Abfragen Organisation
  113. SQLORGCur = SQLconn.cursor()
  114. SQLORGCur.execute('SELECT * from Organizations where contactId = ' + str(contactID))
  115. ORGrows = SQLContCur.fetchall()
  116. for ORGrow in ORGrows:
  117. org = vcf.add('ORG').value = [str(ORGrow['name']), str(ORGrow['department'])]
  118. if ORGrow[4] is not None:
  119. title = vcf.add('TITLE').value = str(ORGrow['title'])
  120. if ORGrow[3] is not None:
  121. role = vcf.add('ROLE').value = str(ORGrow['role'])
  122. # Also parameters are possible. Could be read out
  123. # | columnID | column |
  124. # ----------------------------
  125. # | 0 | detailId |
  126. # | 1 | contactId |
  127. # | 2 | name |
  128. # | 3 | role |
  129. # | 4 | title |
  130. # | 5 | location |
  131. # | 6 | department |
  132. # | 7 | logoUrl |
  133. # | 8 | assistantName |
  134. ## Abfragen E-Mail-Adressen
  135. SQLEmailCur = SQLconn.cursor()
  136. SQLEmailCur.execute('SELECT * from EmailAddresses JOIN Details on Details.detailId= EmailAddresses.detailId where EmailAddresses.contactId = ' + str(contactID))
  137. Emailrows = SQLEmailCur.fetchall()
  138. for Emailrow in Emailrows:
  139. # debug ausgabe
  140. DEBUG(args.debug,str(Emailrow[2]) + " at " + str(Emailrow[9]))
  141. email = vcf.add('email')
  142. email.value = str(Emailrow['emailAddress'])
  143. # nur den Typ einpflegen, wenn das hier nicht none ist
  144. if Emailrow['contexts'] != None:
  145. email.type_param = str(Emailrow['contexts'])
  146. SQLPhoneCur = SQLconn.cursor()
  147. SQLPhoneCur.execute('SELECT * from PhoneNumbers JOIN Details on Details.detailId = PhoneNumbers.detailId where PhoneNumbers.contactId = ' + str(contactID))
  148. Phonerows = SQLPhoneCur.fetchall()
  149. ## Abfragen Telefonnummer, Fax, SMS - Nummern kommen aus der gleichen Tabelle
  150. for Phonerow in Phonerows:
  151. # wir müssen die SubTypen unterscheiden
  152. #Null voice
  153. #1 cell
  154. #2 fax
  155. #3 pager
  156. #6 video
  157. #10 Assistent
  158. # None is a normal phone Number
  159. if Phonerow['subTypes'] == "1":
  160. phcat='cell'
  161. elif Phonerow['subTypes'] == "2":
  162. phcat='fax'
  163. elif Phonerow['subTypes'] == "3":
  164. phcat='pager'
  165. elif Phonerow['subTypes'] == "6":
  166. phcat='video'
  167. elif Phonerow['subTypes'] == "10":
  168. phcat='assistent'
  169. elif Phonerow['subTypes'] is None:
  170. phcat='voice'
  171. # debug ausgabe
  172. DEBUG(args.debug,str(Phonerow['phoneNumber']) + " at " + str(Phonerow['contexts']) + " as subtype=" + str(Phonerow['subTypes']) + "=" + phcat)
  173. phaddcat = 'TEL;TYPE='+phcat;
  174. # nur den Typ einpflegen, wenn das hier nicht none ist
  175. if Phonerow['contexts'] != None:
  176. phaddcat = phaddcat + "," + Phonerow['contexts']
  177. phone = vcf.add(phaddcat).value = str(Phonerow['phoneNumber'])
  178. # nur den Typ einpflegen, wenn das hier nicht none ist
  179. if Phonerow['contexts'] != None:
  180. try:
  181. phone.type_param = str(Phonerow['contexts'])
  182. except AttributeError:
  183. continue
  184. if args.avatars is not None:
  185. DEBUG(args.debug,"Avatar Argument given")
  186. SQLAVTRCur = SQLconn.cursor()
  187. SQLAVTRCur.execute('SELECT imageURL from Avatars where contactId = ' + str(contactID))
  188. AVTRrows = SQLAVTRCur.fetchall()
  189. ## get Avatar Filelink from DB
  190. for AVTRrow in AVTRrows:
  191. DEBUG(args.debug,"found PHOTO entry")
  192. if AVTRrow[0] is not None:
  193. avatarfile=os.path.split(AVTRrow[0])[1]
  194. # pre-checks
  195. # - is it a file
  196. # - is it jpg
  197. import mimetypes
  198. afile=args.avatars + "/" + avatarfile
  199. DEBUG(args.debug,"Avatar File: " + afile + " mimetype: " + str(mimetypes.guess_type(afile)))
  200. if os.path.isfile(afile) and mimetypes.guess_type(afile)[0] == "image/jpeg":
  201. DEBUG(args.debug,"found file " + afile)
  202. import base64
  203. # actions
  204. # - encode base24 to variable
  205. # - add to vcard
  206. fileopen=open(afile,'rb')
  207. bfile=base64.b64encode(fileopen.read())
  208. fileopen.close()
  209. # https://stackoverflow.com/a/61532783
  210. photo = vcf.add('PHOTO;ENCODING=b;TYPE=image/jpeg')
  211. photo.value = str(bfile.decode('utf-8'))
  212. else:
  213. print("file " + afile + " not found or no JPG")
  214. # Output to file
  215. f = open(cardfile,'w')
  216. f.write(vcf.serialize())
  217. f.close()
  218. if osf:
  219. ofile.write(vcf.serialize())
  220. # finally we close the general file
  221. if osf:
  222. ofile.close()
  223. # hier brauchen wir einige eception handles -> wie bekommen wir die einzelnen exceptions heruas ?
  224. #except:
  225. #print("Error in executing SQL")
  226. except AttributeError:
  227. print("Datatype mismatch")
  228. raise
  229. # das generöse Except am Ende
  230. except:
  231. print("unhandled error")
  232. raise