Skip to content

Instantly share code, notes, and snippets.

@jesopo
Last active March 24, 2016 17:17
Show Gist options
  • Save jesopo/3164421509868f3f8e04 to your computer and use it in GitHub Desktop.
Save jesopo/3164421509868f3f8e04 to your computer and use it in GitHub Desktop.
Python3 Plex Media Server last.fm scrobbling script, requires BeautifulSoup4 and PyLast for Python3.
#!/usr/bin/env python3
import re, select, time, urllib.request
import bs4, pylast
FILE_LOG = "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Logs/Plex Media Server.log"
REGEX_STARTED = re.compile("reporting timeline state playing, progress of (\d+)/\d+ms", re.I)
REGEX_RATINGKEY = re.compile("metadataId=(\d+)", re.I)
URL_PLEX = "http://localhost:32400/status/sessions"
API_KEY = "627f33b81993f32254cd60d5736fcebd"
API_SECRET = "00dcb2b827a6ad78af316766f9ebd9f5"
MY_PASSWORD = "password_here"
MY_USERNAME = "username_here"
def get_file():
log_file = open(FILE_LOG)
log_file.seek(0, 2)
return log_file
def watch_file():
log_file = get_file()
last_read = 0
last_media = None
while True:
try:
line = log_file.readline().strip()
except:
continue
if line:
match = re.search(REGEX_STARTED, line)
if match and not match.group(1) == "0":
print(line)
media_id = re.search(REGEX_RATINGKEY, line).group(1)
if last_media and media_id == last_media:
continue
response = urllib.request.urlopen(URL_PLEX)
soup = bs4.BeautifulSoup(response.read(), "lxml")
tracks = soup.findAll("track")
track = None
for _track in tracks:
if _track and _track.find("user").get("id") == "1" and _track.get("ratingkey") == media_id:
track = _track
if not track:
continue
print("scrobble")
last_media = media_id
artist = track.get("grandparenttitle")
album = track.get("parenttitle")
track_title = track.get("title")
track_number = track.get("index")
track_length = int(track.find("media").get("duration"))/1000
timestamp = int(time.time())
pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=MY_USERNAME,
password_hash=pylast.md5(MY_PASSWORD)).scrobble(artist, track_title,
timestamp, None, None, track_number, track_length)
last_read = time.time()
else:
if last_read and time.time()-last_read > 10:
log_file = get_file()
time.sleep(1)
watch_file()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment