|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Plex-AutoDelete is a useful to delete all but the last X episodes of a show. |
| 5 | +This comes in handy when you have a show you keep downloaded, but do not |
| 6 | +religiously keep every single episode that is downloaded. |
| 7 | +
|
| 8 | +Usage: |
| 9 | +Intended usage is to add one of the tags keep5', keep10, keep15, to any show |
| 10 | +you want to have this behaviour. Then simply add this script to run on a schedule |
| 11 | +and you should be all set. |
| 12 | +
|
| 13 | +Example Crontab: |
| 14 | +*/5 * * * * /home/atodd/plex-autodelete.py >> /home/atodd/plex-autodelete.log 2>&1 |
| 15 | +""" |
| 16 | +import os |
| 17 | +from datetime import datetime |
| 18 | +from plexapi.server import PlexServer |
| 19 | + |
| 20 | +TAGS = {'keep5':5, 'keep10':10, 'keep15':15} |
| 21 | +datestr = lambda: datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| 22 | + |
| 23 | + |
| 24 | +def delete_episode(episode): |
| 25 | + for media in episode.media: |
| 26 | + for mediapart in media.parts: |
| 27 | + try: |
| 28 | + filepath = mediapart.file |
| 29 | + print('%s Deleting %s.' % (datestr(), filepath)) |
| 30 | + os.unlink(filepath) |
| 31 | + # Check the parent directory is empty |
| 32 | + dirname = os.path.dirname(filepath) |
| 33 | + if not os.listdir(dirname): |
| 34 | + print('%s Removing empty directory %s.' % (datestr(), dirname)) |
| 35 | + os.rmdir(dirname) |
| 36 | + except Exception as err: |
| 37 | + print('%s Error deleting %s; %s' % (datestr(), filepath, err)) |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == '__main__': |
| 41 | + print('%s Starting plex-markwatched script..' % datestr()) |
| 42 | + plex = PlexServer() |
| 43 | + for section in plex.library.sections(): |
| 44 | + if section.type in ('show',): |
| 45 | + episodes_deleted = 0 |
| 46 | + for tag, keep in TAGS.items(): |
| 47 | + for show in section.search(collection=tag): |
| 48 | + print('%s Cleaning %s to %s items.' % (datestr(), show.title, keep)) |
| 49 | + items = sorted(show.episodes(), key=lambda x:x.originallyAvailableAt or x.addedAt, reverse=True) |
| 50 | + for episode in items[keep:]: |
| 51 | + delete_episode(episode) |
| 52 | + episodes_deleted += 1 |
| 53 | + if episodes_deleted: |
| 54 | + section.update() |
0 commit comments