main.py 4.8 KB

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