Auto Delete Shows After Watching

I know it’s been done repeatedly but I figured I’d throw in my simple little one.
If there’s interest I might add features. But this python script is just a down and dirty little thing that deletes the video files after they are marked watched.

You’ll need the plexapi library.
pip install plexapi

from plexapi.server import PlexServer
import os, datetime
plex = PlexServer()

keep = []
kept=0
deleted=0

print '-----------------------------------------------'
print 'Running Plex Cleaner on '+datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
print ''

for entry in plex.library.section('TV Shows').recentlyViewed():
	if entry.grandparentTitle not in keep:
		print 'Deleting '+entry.title+' '+entry.media[0].parts[0].file
		deleted += 1
		os.remove(entry.media[0].parts[0].file)
		
	else:
		print 'Keeping '+entry.title+' '+entry.media[0].parts[0].file
		kept += 1

print ''
print str(kept) +' Episodes Kept'
print str(deleted) +' Episodes Deleted'

Hi,

This is a great initiative, however, can this be done with Plex Home in mind?
I would like the possibility to have an option that content gets deleted after all plex home members have watched it.
After a grace period etc.

Do you know of the existence of such a script?

I’m trying to figure out how this part here works.

if entry.grandparentTitle not in keep:
I see the Keep Object at the top it but I’m not sure how its being used.
But otherwise I this script looks very useful to me.

Hey guys… This may be a little dead, but it’s a damn cool feature to have in here.

I’m relatively new to python, but I think I have waded my way through this pretty easily.

if entry.grandparentTitle not in keep:

entry.grandparentTitle is the physical name of the episode from the DB, and keep is defined above that line on line 5. If you define a “list” of shows that you want to keep in the list on line 5, the script will skip any of those in the list. The if statement says if it’s NOT in the list, then proceed…

Here’s an example of the list with data in it:
keep = ['The Walking Dead', 'The Big Bang Theory', Fear the Walking Dead', 'Breaking Bad']
From what I gather, it’s very much case sensitive as well as spelling dependent. It has to match whatever the name of the show is in Plex.

Are there any features you guys would like added to this? I think I am going to write in a “Confirm Delete” feature to ask before deleting each file unless passed an override. Also considering a log in MongoDB maybe? The last thought was a web interface or possibly plugin hooked into the web interface, though that is MUCH harder to do. So… Any requests?

I changed the script a little. I’ve changed keep to remove and I changed the condition to this
if entry.grandparentTitle in remove:
This way it only deletes the shows I don’t want to keep, which I have very few of.

I was also getting errors with the encoding some of the show names in the print statement so I also add .encode(“utf-8”) to it. Here’s my edited version:

from plexapi.server import PlexServer
import os, datetime
plex = PlexServer()
remove = []
kept=0
deleted=0
print '-----------------------------------------------'
print 'Running Plex Cleaner on '+datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
print ''
for entry in plex.library.section('TV Shows').recentlyViewed():
    if entry.grandparentTitle in remove:
        print 'Deleting '+entry.title.encode("utf-8")+' '+entry.media[0].parts[0].file.encode("utf-8")
        deleted += 1
        os.remove(entry.media[0].parts[0].file)
    else:
        print 'Keeping '+entry.title.encode("utf-8")+' '+entry.media[0].parts[0].file.encode("utf-8")
        kept += 
print ''
print str(kept) +' Episodes Kept'
print str(deleted) +' Episodes Deleted'

Made another update. I added a OSD notification when the script is run. To use it, I installed the json-rpc library
To install json-rpc run this
pip install json-rpc
and here’s the updated code:

from plexapi.server import PlexServer
import os, datetime
import requests
import json
plex = PlexServer()
remove = []
kept=0
deleted=0
print '-----------------------------------------------'
print 'Running Plex Cleaner on '+datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')
print ''
for entry in plex.library.section('TV Shows').recentlyViewed():
    if entry.grandparentTitle in remove:
        if os.path.exists(entry.media[0].parts[0].file):
            print 'Deleting '+entry.title.encode("utf-8")+' '+entry.media[0].parts[0].file.encode("utf-8")
            deleted += 1
            os.remove(entry.media[0].parts[0].file)
    else:
        print 'Keeping '+entry.title.encode("utf-8")+' '+entry.media[0].parts[0].file.encode("utf-8")
        kept += 1
print ''
print str(kept) +' Episodes Kept'
delete_message = str(deleted) +' Episodes Deleted'
print delete_message
if deleted > 0:
    url = "http://localhost:3005/jsonrpc"
    headers = {'content-type': 'application/json', 'Accept': 'application/json'}
    payload = {"id":1,"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"Auto Delete","message":delete_message}}
    response = requests.post(url, data=json.dumps(payload), headers=headers).json()

they announced pre transcode feature yesterday, would be cool if this can on work on that

deletes just the pre transcoded copy

Hi!

I just made my own changes to delete the Subtitle Files too…

Just fill in the array subTypes with the subtitles with the language flag of it. Since my Subtitle downloader is automated and downloads subtitles from a bunch of different websites, I never know which lang flag it will use, so, I had to make on this way :slight_smile:

import os, datetime from plexapi.server import PlexServer plex = PlexServer() keep = ['Seinfeld', 'Firefly', 'Battlestar Galactica'] subTypes = ['.srt', '.por.srt', '.pb.srt', '.pob.srt', '.pt-BR.srt', '.PortugueseBR.srt', '.en.srt', '.eng.srt', '.en-US.srt'] kept=0 deleted=0 print '-----------------------------------------------' print 'Running Plex Cleaner on '+datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S') print '' for entry in plex.library.section('TV Shows').recentlyViewed(): movieFile = entry.media[0].parts[0].file if entry.grandparentTitle not in keep: print 'Deleting '+entry.title+' ::: '+movieFile deleted += 1 os.remove(movieFile) for sub in subTypes: subFile = os.path.splitext(movieFile)[0]+sub if os.path.isfile(subFile): print '::: Deleting it\'s Subtitle too ::: '+subFile os.remove(subFile) else: # print 'Keeping '+entry.title+' ::: '+movieFile kept += 1 print '' print str(kept) + ' Episodes Kept' print str(deleted) + ' Episodes Deleted'

Made some subtle changes and modified based on existing changes in this thread.

  • Similar file array to remove similarly named files based off of show file name

  • Added check so files on deck (in progress) do not get deleted

    import os, datetime
    from plexapi.server import PlexServer
    plex = PlexServer()
    keep = []
    simFiles = [’.srt’, ‘.nfo’, ‘.tbn’, ‘.nzb’, ‘.nfo-orig’, ‘.sfv’, ‘.srr’, ‘.jpg’, ‘.png’, ‘.jpeg’, ‘.txt’]
    kept=0
    deleted=0
    print ‘-----------------------------------------------’
    print ‘Running Plex Cleaner on ‘+datetime.datetime.now().strftime(’%m/%d/%Y %H:%M:%S’)
    print ‘’
    for entry in plex.library.section(‘TV Shows’).recentlyViewed():
    tvFile = entry.media[0].parts[0].file
    if entry.grandparentTitle not in keep:
    if entry not in plex.library.onDeck():
    print 'Deleting ‘+entry.title+’ ::: '+tvFile
    deleted += 1
    os.remove(tvFile)
    for sim in simFiles:
    simFile = os.path.splitext(tvFile)[0]+sim
    if os.path.isfile(simFile):
    print ‘::: Deleting it’s similar file too ::: ‘+simFile
    os.remove(simFile)
    else:
    kept += 1
    print ‘’
    print str(kept) + ’ Episodes Kept’
    print str(deleted) + ’ Episodes Deleted’

i’d like to set this to run automatically, however is it possible to set a threshold based on the “lastViewedAt” parameter as well? So here’s my logic, sorry not a programmer:

IF viewCount >= 1 AND lastViewedAt >= Now + X days THEN delete episode

Ok I figured it out. Here is my version. I removed the similar files piece as I already have another process doing that.

import os, datetime from datetime import timedelta from plexapi.server import PlexServer plex = PlexServer() keep = [] kept=0 deleted=0 daystoKeep=1 print '-----------------------------------------------' print 'Running Plex Cleaner on '+datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S') for entry in plex.library.section('TV Shows').recentlyViewed(): print '' tvFile = entry.media[0].parts[0].file if entry.grandparentTitle not in keep: if entry not in plex.library.onDeck(): print 'Reviewing: '+tvFile print 'Last Viewed at: '+entry.lastViewedAt.strftime('%m/%d/%Y %H:%M:%S') if entry.lastViewedAt+datetime.timedelta(days=daystoKeep) <= datetime.datetime.today(): print 'Deleting Episode' deleted += 1 os.remove(tvFile) else: kept += 1 print '' print str(kept) + ' Episodes Kept' print str(deleted) + ' Episodes Deleted'

I think it will positive to open a GitHub Depo for this project, that has evolved beyond its original purpose to a more versatile tool to recycle tvshows and ancillary files automatically according to the specs of the “Plex administrator”.

Having the source code on GitHub (or any other collaborative code versioning platform) allows the documentation, testing, debugging, releasing, tracing of any versions and branches of the development, while retaining enough control to consolidate everyone’s contributions to build a release that should be capable to address most of the requirements of “Plex administrators”.

Good idea: https://github.com/Shadow00Caster/PlexAutoFileManager

Can you share a video about the install and how it works?
It appear onteresting but I don’t know if it can be useful for me.
Thanks for the development

There is a script in Github by user ngovil21 that does almost everything and it’s nearly fully user configurable, go and check it, Plex-Cleaner.
I have been using it lately and it works as advertised.

It seems plexapi has changed and the scripts above will no longer work. For example, recentlyViewed() has been removed. Anyone got a working version with the latest plexapi?

Yeah, I stopped messing with it when I found this:

github.com/ngovil21/Plex-Cleaner