keys2db.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #!/usr/bin/env python3
  2. # -*- coding: utf8 -*-
  3. # libray - Libre Blu-Ray PS3 ISO Tool
  4. # Copyright © 2018 - 2024 Nichlas Severinsen
  5. #
  6. # This file is part of libray.
  7. #
  8. # libray is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # libray is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with libray. If not, see <https://www.gnu.org/licenses/>.
  20. # This script transforms Datfile.dat and keys/*.key keyfiles into a sqlite3 keys.db
  21. # Keys.db is then moved to libray/data/keys.db and packaged with libray in setup.py.
  22. # Libray checks if this file is bundled with it and has logic to identify the correct key.
  23. # TODO: In theory we could add the game-serials (BLUS-0000) and check that first.
  24. import bs4
  25. import csv
  26. import sys
  27. import shutil
  28. import sqlite3
  29. import pathlib
  30. import argparse
  31. import requests
  32. if __name__ == '__main__':
  33. parser = argparse.ArgumentParser()
  34. parser.add_argument('-d', '--database', type=pathlib.Path, default='keys.db', help='Path to keys.db')
  35. parser.add_argument('-k', '--keys', type=pathlib.Path, default='keys', help='Path to .key keys')
  36. parser.add_argument('--show-missing', action='store_true', help='Show titles missing keys')
  37. args = parser.parse_args()
  38. if args.database.exists():
  39. args.database.unlink()
  40. # Check if there's a mapping csv that maps the keynames to title IDs
  41. mapping = pathlib.Path('keys.csv')
  42. title_ids = {}
  43. if mapping.exists():
  44. with open(mapping, 'r') as infile:
  45. reader = csv.DictReader(infile, delimiter=',', quotechar='"', )
  46. for row in reader:
  47. title_ids[row['md5']] = {
  48. 'title_id': row['title_id'],
  49. 'filename': row['filename'],
  50. 'size': row['size'],
  51. 'crc32': row['crc32'],
  52. }
  53. db = sqlite3.connect(args.database)
  54. c = db.cursor()
  55. c.execute('CREATE TABLE games (title_id TEXT, name TEXT, size TEXT, crc32 TEXT, md5 TEXT, sha1 TEXT, key BLOB)')
  56. db.commit()
  57. cwd = pathlib.Path(__file__).resolve().parent
  58. keys_path = cwd / 'keys'
  59. if not keys_path.exists():
  60. print('Error: No keys/ folder. Place the .key files in a tools/keys/ folder')
  61. sys.exit()
  62. any_dats = [x for x in cwd.glob('*.dat')]
  63. if not any_dats:
  64. print('Error: No .dat file. Place the .dat file in the tools/ folder')
  65. sys.exit()
  66. datfile = any_dats[0]
  67. warnings = 0
  68. with open(datfile, 'r') as infile:
  69. soup = bs4.BeautifulSoup(infile.read(), features='html5lib')
  70. for game in soup.find_all('game'):
  71. name = game.find('description').text.strip()
  72. attrs = game.find('rom').attrs
  73. try:
  74. title_map = title_ids[attrs['md5']]
  75. assert title_map['size'] == attrs['size']
  76. assert title_map['crc32'] == attrs['crc']
  77. title_id = title_map['title_id']
  78. except (KeyError, AssertionError):
  79. title_id = None
  80. # Some of the records are spaces:
  81. if not title_id:
  82. title_id = None
  83. entry = [title_id, name, attrs['size'], attrs['crc'], attrs['md5'], attrs['sha1']]
  84. try:
  85. with open(cwd / ('keys/' + name + '.key'), 'rb') as keyfile:
  86. entry.append(keyfile.read())
  87. except FileNotFoundError:
  88. warnings += 1
  89. if args.show_missing:
  90. print('Warning: missing keyfile for %s [%s]' % (name, attrs['crc']))
  91. c.execute('INSERT INTO games (title_id, name, size, crc32, md5, sha1) VALUES (?, ?, ?, ?, ?, ?)', entry)
  92. continue
  93. c.execute('INSERT INTO games VALUES (?, ?, ?, ?, ?, ?, ?)', entry)
  94. db.commit()
  95. db.close()
  96. data_path = (cwd.parent / 'libray') / 'data/'
  97. if not data_path.exists():
  98. data_path.mkdir()
  99. shutil.copyfile(args.database, ((cwd.parent / 'libray') / 'data/') / args.database.name)
  100. print('Warning: no keyfiles for %s titles' % str(warnings))