Skip to content

Instantly share code, notes, and snippets.

@felixbuenemann
Last active March 9, 2021 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save felixbuenemann/f2314b3b67cbe7d5e22c3c616cfef449 to your computer and use it in GitHub Desktop.
Save felixbuenemann/f2314b3b67cbe7d5e22c3c616cfef449 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# plexwatcher.py - parse watcher events to partially scan plex libraries
# relevant paths and sections are discovered directly from the plex database
#
# Author: Felix Buenemann - https://github.com/felixbuenemann
import os, sys, re, sqlite3, subprocess
from os.path import dirname
# reload(sys)
# sys.setdefaultencoding('utf8')
pms = '/usr/lib/plexmediaserver/Plex Media Scanner'
pdb = '/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db'
conn = sqlite3.connect(pdb)
c = conn.cursor()
c.execute('SELECT id, name FROM library_sections')
sections = dict(c.fetchall())
c.execute('SELECT library_section_id, root_path FROM section_locations')
dirs = c.fetchall()
# Log format for parsing https://github.com/radovskyb/watcher events:
log = re.compile(r'^(?P<type>[A-Z]+) "(?P<name>[^"]+)" (?P<action>[A-Z]+) \[(?P<path>.+)\]$')
os.environ['LD_LIBRARY_PATH'] = '/usr/lib/plexmediaserver/lib'
for line in sys.stdin:
m = log.match(line)
type = m.group('type')
name = m.group('name')
action = m.group('action')
paths = m.group('path').split(' -> ')
if (type in ('FILE', 'DIRECTORY') and action in ('CREATE', 'MOVE', 'REMOVE')):
for library_section_id, root_path in dirs:
for path in paths:
if path.startswith(root_path + '/'):
if type == 'DIRECTORY':
directory = path
else:
directory = dirname(path)
print(u'Update "%s" in section "%s"' % (directory, sections[library_section_id]))
subprocess.call([pms,
'--scan',
'--refresh',
'--no-thumbs',
'--section', str(library_section_id),
'--directory', directory
])
# /lib/systemd/system/plexwatcher.service
[Unit]
Description=Plex Library Updater
After=plexdrive.service
Requires=plexdrive.service
[Service]
User=plex
Group=plex
Type=simple
ExecStartPre=/bin/sh -c 'while [ ! -d /mnt/plexdrive/Media ]; do /bin/sleep 5; done'
TimeoutStartSec=60
TimeoutStopSec=60
# Environment=LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
# watcher is from https://github.com/radovskyb/watcher
ExecStart=/usr/local/bin/watcher -interval=60s -dotfiles=false -pipe=true "-cmd=/usr/bin/python3 /var/lib/plexmediaserver/plexwatcher.py" /mnt/plexdrive/Media
Restart=on-abort
[Install]
WantedBy=default.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment