main.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # Imports
  2. import re
  3. import os
  4. import argparse
  5. from datetime import datetime
  6. import tvdb_v4_official
  7. # Default config
  8. default_apikey = os.path.expanduser('~/.tvdb_apikey')
  9. # Local helpers
  10. def readConfigLine(file):
  11. value = None
  12. try:
  13. with open(file, 'r') as f:
  14. for line in f:
  15. if re.match('^\s*#', line):
  16. continue
  17. else:
  18. value = line.strip()
  19. break
  20. except Exception as error:
  21. print('Unable to read config: {e}'.format(e=error))
  22. return value
  23. # CLI config
  24. parser = argparse.ArgumentParser('TVDB Renamer')
  25. parser.add_argument('path', help='The directory containing files to be renamed')
  26. parser.add_argument('--api', default=default_apikey, required=False, help='Path to a file containing the TVDB API key')
  27. cli = parser.parse_args()
  28. if not os.path.isfile(cli.api):
  29. print('Invalid API key file path: {path}'.format(path=cli.api))
  30. exit(1)
  31. if not os.path.isdir(cli.path):
  32. print('Invalid path: {path}'.format(path=cli.path))
  33. exit(1)
  34. # Move to keep the file paths flat
  35. try:
  36. os.chdir(cli.path)
  37. except Exception as error:
  38. print('Unable to move to target directory: {e}'.format(e=error))
  39. exit(1)
  40. # Read the local directory
  41. seasons = {}
  42. try:
  43. dirfiles = os.listdir('.')
  44. except Exception as error:
  45. print('Unable to read to target directory: {e}'.format(e=error))
  46. exit(1)
  47. for file in dirfiles:
  48. f = {}
  49. f['file'] = file
  50. try:
  51. split = os.path.splitext(file)
  52. f['base'] = split[0]
  53. f['extension'] = split[1]
  54. se = re.search('S(\d+)E(\d+)', file, flags=re.IGNORECASE)
  55. if se is None:
  56. # Does not contain a season/episode block
  57. continue
  58. f['season'] = int(se.group(1))
  59. f['number'] = int(se.group(2))
  60. if not f['season'] in seasons:
  61. seasons[ f['season'] ] = {}
  62. if not f['number'] in seasons[ f['season'] ]:
  63. seasons[ f['season'] ][ f['number'] ] = []
  64. seasons[ f['season'] ][ f['number'] ].append(f)
  65. except Exception as error:
  66. print('Unable to parse filename "{f}": {e}'.format(e=error, f=file))
  67. continue
  68. # Fetch the TVDB episode list
  69. try:
  70. apikey = readConfigLine(cli.api)
  71. series = readConfigLine('.tvdb')
  72. if apikey is None or series is None:
  73. print('Invalid TVDB parameters')
  74. exit(1)
  75. tvdb = tvdb_v4_official.TVDB(apikey)
  76. data = tvdb.get_series_episodes(series)
  77. del tvdb
  78. del series
  79. del apikey
  80. except Exception as error:
  81. print('Unable to fetch series {id}: {e}'.format(id=series, e=error))
  82. exit(1)
  83. # Parse and clean the data we need
  84. episodes = []
  85. try:
  86. seriesName = data['series']['name'].strip()
  87. for episode in data['episodes']:
  88. e = {}
  89. e['series'] = seriesName
  90. e['season'] = int(episode['seasonNumber'])
  91. e['number'] = int(episode['number'])
  92. e['name'] = episode['name'].strip()
  93. e['date'] = None if episode['aired'] is None else datetime.strptime(episode['aired'], '%Y-%m-%d')
  94. e['description'] = '' if episode['overview'] is None else episode['overview'].strip()
  95. e['filename'] = '{series} - S{season:02d}E{number:02d} - {name}'.format(
  96. series=e['series'], season=e['season'], number=e['number'], name=e['name']
  97. )
  98. e['filename'] = e['filename'].replace(':', ' -').replace('/', ' - ').replace(' ', ' ')
  99. episodes.append(e)
  100. except Exception as error:
  101. print('Unable to parse episode data: {e}'.format(e=error))
  102. exit(1)
  103. # Rename matched files
  104. for e in episodes:
  105. if (
  106. not e['season'] in seasons or
  107. not e['number'] in seasons[ e['season'] ]
  108. ):
  109. print('Missing: {m}'.format(m=e['filename']))
  110. continue
  111. files = seasons[ e['season'] ][ e['number'] ]
  112. for file in files:
  113. if file['base'] != e['filename']:
  114. src = file['file']
  115. dest = e['filename'] + file['extension']
  116. print('Rename\n\t{s}\n\t{d}'.format(s=src, d=dest))
  117. if (
  118. os.path.exists(dest) and
  119. file['base'].casefold() != e['filename'].casefold()
  120. ):
  121. print('Target exists: {d}'.format(d=dest))
  122. continue
  123. try:
  124. os.rename(src, dest)
  125. except Exception as error:
  126. print('Unable to rename {s}: {e}'.format(s=src, e=error))
  127. continue