main.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Imports
  2. import re
  3. import os
  4. import pathlib
  5. import argparse
  6. from datetime import datetime
  7. import tvdb_v4_official
  8. # Default config
  9. default_apikey = os.path.expanduser('~/.tvdb_apikey')
  10. default_lang = 'eng'
  11. # Local helpers
  12. def readConfigLine(file):
  13. value = None
  14. try:
  15. with open(file, 'r') as f:
  16. for line in f:
  17. if re.match('^\s*#', line):
  18. continue
  19. else:
  20. value = line.strip()
  21. break
  22. except Exception as error:
  23. print('Unable to read config: {e}'.format(e=error))
  24. return value
  25. # CLI config
  26. parser = argparse.ArgumentParser('TVDB Renamer')
  27. parser.add_argument('--api', default=default_apikey, help='Path to a file containing the TVDB API key')
  28. parser.add_argument('--verbose', '-v', action='store_true', help='Display missing and unexpected episodes')
  29. parser.add_argument('--lang', '-l', default=default_lang, help='TVDB language code')
  30. parser.add_argument('path', type=pathlib.Path, help='The directory containing files to be renamed')
  31. cli = parser.parse_args()
  32. if not os.path.isfile(cli.api):
  33. print('Invalid API key file path: {path}'.format(path=cli.api))
  34. exit(1)
  35. if not os.path.isdir(cli.path):
  36. print('Invalid path: {path}'.format(path=cli.path))
  37. exit(1)
  38. if cli.lang == 'None' or cli.lang == '':
  39. cli.lang = None
  40. if cli.verbose:
  41. print('Path: {p}'.format(p=cli.path))
  42. print('Language: {l}'.format(l=cli.lang))
  43. # Move to keep the file paths flat
  44. try:
  45. os.chdir(cli.path)
  46. except Exception as error:
  47. print('Unable to move to target directory: {e}'.format(e=error))
  48. exit(1)
  49. # Read the local directory
  50. seasons = {}
  51. try:
  52. dirfiles = os.listdir('.')
  53. except Exception as error:
  54. print('Unable to read to target directory: {e}'.format(e=error))
  55. exit(1)
  56. for file in dirfiles:
  57. f = {}
  58. f['file'] = file
  59. try:
  60. split = os.path.splitext(file)
  61. f['base'] = split[0]
  62. f['extension'] = split[1]
  63. se = re.search('S(\d+)E(\d+)', file, flags=re.IGNORECASE)
  64. if se is None:
  65. # Does not contain a season/episode block
  66. continue
  67. f['season'] = int(se.group(1))
  68. f['number'] = int(se.group(2))
  69. if not f['season'] in seasons:
  70. seasons[ f['season'] ] = {}
  71. if not f['number'] in seasons[ f['season'] ]:
  72. seasons[ f['season'] ][ f['number'] ] = []
  73. seasons[ f['season'] ][ f['number'] ].append(f)
  74. except Exception as error:
  75. print('Unable to parse filename "{f}": {e}'.format(e=error, f=file))
  76. continue
  77. # Fetch the TVDB episode list
  78. try:
  79. apikey = readConfigLine(cli.api)
  80. series_id = readConfigLine('.tvdb')
  81. if cli.verbose:
  82. print('Series: {id}'.format(id=series_id))
  83. if apikey is None or series_id is None:
  84. print('Invalid TVDB parameters')
  85. exit(1)
  86. tvdb = tvdb_v4_official.TVDB(apikey)
  87. if cli.lang is None:
  88. series = tvdb.get_series(id=series_id)
  89. else:
  90. series = tvdb.get_series_translation(id=series_id, lang=cli.lang)
  91. data = tvdb.get_series_episodes(id=series_id, lang=cli.lang)
  92. del tvdb
  93. del series_id
  94. del apikey
  95. except Exception as error:
  96. print(
  97. "Unable to fetch series {id}: {e}\nSeries:\n{s}\nEpisodes:\n{ep}".format(
  98. id=series_id, e=error, s=series, ep=data
  99. )
  100. )
  101. exit(1)
  102. # Parse and clean the data we need
  103. episodes = []
  104. try:
  105. series_name = series['name'].strip()
  106. if cli.verbose:
  107. print('Series: {name}'.format(name=series_name))
  108. for episode in data['episodes']:
  109. e = {}
  110. e['series'] = series_name
  111. e['season'] = int(episode['seasonNumber'])
  112. e['number'] = int(episode['number'])
  113. e['name'] = episode['name'].strip()
  114. e['date'] = None if episode['aired'] is None else datetime.strptime(episode['aired'], '%Y-%m-%d')
  115. e['description'] = '' if episode['overview'] is None else episode['overview'].strip()
  116. e['filename'] = '{series} - S{season:02d}E{number:02d} - {name}'.format(
  117. series=e['series'], season=e['season'], number=e['number'], name=e['name']
  118. )
  119. e['filename'] = e['filename'].replace(':', ' -').replace('/', ' - ').replace(' ', ' ')
  120. episodes.append(e)
  121. except Exception as error:
  122. print('Unable to parse episode data: {e}'.format(e=error))
  123. exit(1)
  124. # Find unexpected episodes
  125. if cli.verbose:
  126. db_seasons = {}
  127. for e in episodes:
  128. if not e['season'] in db_seasons:
  129. db_seasons[ e['season'] ] = {}
  130. if not e['number'] in db_seasons[ e['season'] ]:
  131. db_seasons[ e['season'] ][ e['number'] ] = True
  132. for snum, s in seasons.items():
  133. for enum, elist in s.items():
  134. for e in elist:
  135. if (
  136. not e['season'] in db_seasons or
  137. not e['number'] in db_seasons[ e['season'] ]
  138. ):
  139. print('Unexpected: {f}'.format(f=e['file']))
  140. del db_seasons
  141. # Rename matched files
  142. for e in episodes:
  143. if (
  144. not e['season'] in seasons or
  145. not e['number'] in seasons[ e['season'] ]
  146. ):
  147. if cli.verbose:
  148. if e['date'] is None or e['date'] <= datetime.today():
  149. print('Missing: {m}'.format(m=e['filename']))
  150. continue
  151. files = seasons[ e['season'] ][ e['number'] ]
  152. for file in files:
  153. if file['base'] != e['filename']:
  154. src = file['file']
  155. dest = e['filename'] + file['extension']
  156. print('Rename\n\t{s}\n\t{d}'.format(s=src, d=dest))
  157. if (
  158. os.path.exists(dest) and
  159. file['base'].casefold() != e['filename'].casefold()
  160. ):
  161. print('Target exists: {d}'.format(d=dest))
  162. continue
  163. try:
  164. os.rename(src, dest)
  165. except Exception as error:
  166. print('Unable to rename {s}: {e}'.format(s=src, e=error))
  167. continue
  168. else:
  169. if cli.verbose:
  170. print('Found: {m}'.format(m=e['filename']))