pkkid / python-plexapi

Python bindings for the Plex API.
BSD 3-Clause "New" or "Revised" License
1.13k stars 196 forks source link

Ability to Add items to Playlist #49

Closed pkkid closed 8 years ago

pkkid commented 8 years ago

We need the ability to add items to a playlist. Right now it's read only.

beville commented 8 years ago

Hey there, I just came across this project when trying to create a little specialized utility for generating playlists. What you've got so far looks great, but of course, no playlist manipulations yet.

While, I've been able to use the REST API to view playlists, I haven't been able to track down any API description for creating, deleting, or adding/removing items to playlists. Do you have any reference that you can share? I'm not afraid to dig through source code of any kind if that's what it takes!

Thanks!

pkkid commented 8 years ago

I should have playlist support within a week or two. In version two, I plan to have all enhancements closed.

Anyway, what I have been doing to figure out the API is open chrome dev tools in the Plex Web interface. Then perform the actions I wanted to know and check out the URL that it is calling.

pkkid commented 8 years ago

Just started messing with this today. Here is what I found:

def addItem(self, item):
    # PUT /playlists/29988/items?uri=library%3A%2F%2F32268d7c-3e8c-4ab5-98ad-bad8a3b78c63%2Fitem%2F%252Flibrary%252Fmetadata%252F801
    pass

def removeItem(self, item):
    # DELETE /playlists/29988/items/4866
    pass

def moveItem(self, item, after):
    # PUT /playlists/29988/items/4556/move?after=4445
    # PUT /playlists/29988/items/4556/move  (to first item)
    pass

def edit(self, title=None, summary=None):
    # PUT /library/metadata/29988?title=You%20Look%20Like%20Gollum2&summary=foobar
    pass

def delete(self):
    # DELETE /playlists/29988
    pass

@classmethod
def create(self, server):
    # POST /playlists?type=video&title=TESTING&smart=0&uri=library%3A%2F%2F32268d7c-3e8c-4ab5-98ad-bad8a3b78c63%2Fitem%2F%252Flibrary%252Fmetadata%252F801
    # RESPONSE: <Playlist ratingKey="53596" key="/playlists/53596/items" guid="com.plexapp.agents.none://ea4b8781-1605-4127-bea0-651d48f8ad18" type="playlist" title="TESTING" summary="" smart="0" playlistType="video" composite="/playlists/53596/composite/1460261551" ratingCount="0" duration="5348000" leafCount="1" addedAt="1460261551" updatedAt="1460261551" durationInSeconds="1"></Playlist>
    pass
beville commented 8 years ago

This is a great start, thanks! Of course, now that I know you're on the case, I may just let you finish and reap the rewards of your hard work ;-)

beville commented 8 years ago

Not content to wait, and since I need only a very small-subset of your API, I followed your technique of use chrome dev tools to spy on the Plex web UI. I put together a small wrapper that serves my specific needs, which I'll paste in here. The specific things I found were that you can add multiple items at once when creating a playlist, and that the UUID pass when creating a playlist seems to be for the content section. Thanks for your help! I'll probably switch over to your API when it's solidifed.

import sys
import os
import requests
import json
from pprint import pprint 
import random

class PlexServer(object):
    def __init__(self, host='localhost',port=32400):
        self.base_url = "http://{}:{}".format(host,port)

    def query(self, path, request_func):
        url = self.base_url + path
        headers = dict()
        headers['Accept'] = 'application/json'
        r = request_func(url, headers=headers, allow_redirects=True)
        try:
            response = json.loads( r.content )
            return response
        except:
            return None

    def get(self, path):
        #print "GET", path
        return self.query(path, requests.get)
    def post(self, path):
        #print "POST", path
        return self.query(path, requests.post)
    def delete(self, path):
        #print "DELETE", path
        return self.query(path, requests.delete)

    def getSections(self):
        path = "/library/sections"
        response = self.get(path)
        return response['_children']        

    def getAlbums(self, section):
        path = "/library/sections/{}/albums".format(section)
        response = self.get(path)
        albums = response['_children']

        for a in albums:
            # massage the genres info:
            genre_list = []
            for c in a['_children']:
                if c['_elementType'] == 'Genre':
                    genre_list.append(c['tag'])
            a['genres'] = genre_list

        return albums      

    def getPlaylists(self):
        path = "/playlists"
        response = self.get(path)
        return response['_children']        

    # takes a dict item as returned from getPlaylists
    def deletePlaylist(self, playlist):
        playlist_key = playlist['key']
        path = playlist_key.replace("/items", "")
        return self.delete(path)        

    # takes a list of album dict items as returned from getAlbums
    def createPlaylistOfAlbums(self, title, album_list, guid):
        key_list = []
        for a in album_list:
            key_num = a['key'].replace("/children","").replace("/library/metadata/", "")
            key_list.append(key_num) 

        path = "/playlists"
        path += "?type=audio"
        path += "&title={}".format(title)
        path += "&smart=0"
        path += "&uri=library://{}/directory//library/metadata/".format(guid)
        path += ",".join(key_list)            
        return self.post(path)      
pkkid commented 8 years ago

Awesome, glad you got it working. I suspected you may be able to add multiple items, but didn't really look into it too closely. Thanks for the example.

pkkid commented 8 years ago

@beville Did you ever figure out what guid is and where is comes from?

beville commented 8 years ago

As far as I could tell, the guid matches the UUID for the section of the content that you're adding the playlist for. (/library/sections)

When creating the playlist, it didn't seem to matter what I used, but I was trying to match the network trace from the Web UI as close as I could. So when I added a music album, it seemed to use the uuid of the only music section I have.

pkkid commented 8 years ago

Thanks. I added support for most things in this change as well as a few tests to help prevent regressions in the future. I did not fix the UUID thing mentioned above. In the next few days I'll cleanup the edges a bit more. I still want to do the following:

commit 3138ad1087418820c83e59c2bead584b66bdf239 Author: Michael Shepanski mjs7231@gmail.com Date: Sun Apr 10 23:49:23 2016 -0400 Added playlist support

pkkid commented 8 years ago

commit 748fc68406a753e622378bfce270a978e2308692 Author: Michael Shepanski mjs7231@gmail.com Date: Mon Apr 11 22:43:21 2016 -0400 Cleanup playlist support; Fix UUID on URLs; Better method to store listTypes; Cache section IDs in library