Skip to content

Instantly share code, notes, and snippets.

@blacktwin
Last active October 17, 2019 04:13
Show Gist options
  • Save blacktwin/14d400a0f442da465389164fa046647a to your computer and use it in GitHub Desktop.
Save blacktwin/14d400a0f442da465389164fa046647a to your computer and use it in GitHub Desktop.
Kill Plex paused video transcoding streams using PlexPy.
"""
Kill Plex paused video transcoding streams.
PlexPy > Settings > Notification Agents > Scripts > Bell icon:
[X] Notify on playback pause
PlexPy > Settings > Notification Agents > Scripts > Gear icon:
Playback Pause: new_kill_trans_pause.py
"""
import requests
import platform
from uuid import getnode
## EDIT THESE SETTINGS ##
PLEX_HOST = ''
PLEX_PORT = 32400
PLEX_SSL = '' # s or ''
PLEX_TOKEN = 'xxxxx'
MESSAGE = 'This stream has ended due to being paused and transcoding.'
USER_IGNORE = ('') # ('Username','User2')
##
def fetch(path, t='GET'):
url = 'http%s://%s:%s/' % (PLEX_SSL, PLEX_HOST, PLEX_PORT)
headers = {'X-Plex-Token': PLEX_TOKEN,
'Accept': 'application/json',
'X-Plex-Provides': 'controller',
'X-Plex-Platform': platform.uname()[0],
'X-Plex-Platform-Version': platform.uname()[2],
'X-Plex-Product': 'Plexpy script',
'X-Plex-Version': '0.9.5',
'X-Plex-Device': platform.platform(),
'X-Plex-Client-Identifier': str(hex(getnode()))
}
try:
if t == 'GET':
r = requests.get(url + path, headers=headers, verify=False)
elif t == 'POST':
r = requests.post(url + path, headers=headers, verify=False)
elif t == 'DELETE':
r = requests.delete(url + path, headers=headers, verify=False)
if r and len(r.content): # incase it dont return anything
return r.json()
else:
return r.content
except Exception as e:
print e
def kill_stream(sessionId, message):
headers = {'X-Plex-Token': PLEX_TOKEN}
params = {'sessionId': sessionId,
'reason': message}
requests.get('http://{}:{}/status/sessions/terminate'.format(PLEX_HOST, PLEX_PORT),
headers=headers, params=params)
if __name__ == '__main__':
response = fetch('status/sessions')
for s in response['MediaContainer']['Video']:
try:
if s['TranscodeSession']['videoDecision'] == 'transcode' and s['User']['title'] not in USER_IGNORE \
and s['Player']['state'] == 'paused':
print("Killing {}'s stream for pausing a transcode stream of {}".format(s['User']['title'], s['title']))
kill_stream(s['Session']['id'], MESSAGE)
except Exception:
pass
@Dukko
Copy link

Dukko commented Jun 6, 2017

Hi, I'm getting an error on line 67.

PlexPy Notifiers :: Script error: 
    Traceback (most recent call last): 
        File "C:\ProgramData\PlexPy\scripts\new_kill_trans_pause.py", line 67, in 
            for s in response['MediaContainer']['Video']: 
    TypeError: 'NoneType' object has no attribute '__getitem__'

I'm not super sure what's the issue though. Any idea? Thanks!

@jrizz43
Copy link

jrizz43 commented Jun 6, 2017

I am a super noob at python but I feel like kill_stream(s['Session']['id'] in line 72 should be kill_streams(s['sessionId']

Worth a shot. Otherwise i got nothing

@Dukko
Copy link

Dukko commented Jun 6, 2017

Thanks jrizz43 but that didn't work :(

Any idea @blacktwin?

@SkiTheSlicer
Copy link

If you are using a Linux PMS, you can check to see if your transcode is appearing as expected.

Replace your values in the following:
curl --header 'X-Plex-Token: <PLEX_TOKEN>' --header 'Accept: application/json' 'http://<PLEX_HOST>:<PLEX_PORT>/status/sessions'

I'm using HTTPS, so an example (piped to python to pretty-print):
curl -k --header 'X-Plex-Token: <REDACTED>' --header 'Accept: application/json' 'https://localhost:32400/status/sessions' | python -m json.tool

My response trimmed down to just the expected fields:

{
    "MediaContainer": {
        "Video": [
            {
                "Media": {
                    "Part": {
                        "Stream": {
                            "decision": "transcode"
                        },
                        "decision": "transcode"
                    },
                },
                "Player": {
                    "state": "paused"
                },
                "Session": {
                    "id": "2f1ed94df7a63aa0-com-plexapp-android"
                },
                "TranscodeSession": {
                    "videoDecision": "transcode"
                },
                "User": {
                    "title": "<REDACTED USERNAME>"
                }
            }
        ]
    }
}

@blacktwin
Copy link
Author

@Dukko you got this resolved on /r/plex. Problem was incorrect settings.

@justinglock40
Copy link

Is there anyway to make a time delay instead as soon as it's paused kill the stream?

@csy7550
Copy link

csy7550 commented Jun 10, 2017

Would love a new version of the script with delay

@blacktwin
Copy link
Author

@csy7550
Copy link

csy7550 commented Jun 12, 2017

@blacktwin Thanks! I will try, but I was really looking for a script to kill transcoded sessions only. The one you linked kills all paused sessions regardless, right?

Direct play and direct stream sessions isn't really a problem for me, but I've set max PMS transcodes to 6 and that creates a problem when users pause for hours and days hogging a spot

@csy7550
Copy link

csy7550 commented Jun 12, 2017

@blacktwin just tried the script you linked. Plexpy log says script launched with the session_key argument, but no new script file is created in the script directory.

@blacktwin
Copy link
Author

blacktwin commented Jun 13, 2017

@csy7550 I modified this one to target transcode streams. Try this script. Are you using Windows or Linux? Also please comment in the gist you're having problem with.

@Comfubar
Copy link

im getting an error on line 11 with this

@blacktwin
Copy link
Author

@Comfubar Sounds like you need to install requests. Here is how to install.

@Rizzz85
Copy link

Rizzz85 commented Nov 3, 2017

How do i figure out my Plex SSL?

@TheFreshPrinceOfBel-Air

@blacktwin any chance a script like this exists that will kill streams that are stuck buffering? Been having an issue lately with long running streams (1 day+, separate tv episodes played on a loop and repeat).

@blacktwin
Copy link
Author

@TheFreshPrinceOfBel-Air checkout my repo for plex related scripts. I've added all my gists there for easier searching and so people can create issues for errors or requests.

@GuzzyUK
Copy link

GuzzyUK commented Jan 14, 2018

I would love to be able to use this script but have a clue what I change and where I get the information from to fill the blanks in. Any help would be much appreciated thank everyone

@GuzzyUK
Copy link

GuzzyUK commented Jan 16, 2018

ok ive got this script running on my QNAP TS215+ but I'm getting this error.
PlexPy Notifiers :: Script error:
Traceback (most recent call last):
File "/share/CACHEDEV1_DATA/Public/PLEX Script/new_kill_trans_pausenew.py", line 11, in
import requests
ImportError: No module named requests

Please help.....

@benplace
Copy link

benplace commented Aug 1, 2018

I am trying to get this working, when I run the script I get the following error:
Traceback (most recent call last):
File "new_Kill_Trans_Pause.py", line 69, in
for s in response['MediaContainer']['Video']:
KeyError: 'Video'

Any idea?

@blacktwin
Copy link
Author

@benplace use the repo instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment