Diff
checker
文本
文本
图像
文档
Excel
文件夹
Legal
Enterprise
桌面版
定价
登录
下载 Diffchecker 桌面版
比较文本
查找两个文本文件之间的差异
工具
历史
实时编辑器
隐藏空白更改
折叠未更改行
关闭换行
视图
拆分
统一
比对精度
智能
单词
字符
文本样式
更改外观
语法高亮
选择语法
忽略
文本转换
转到第一个差异
编辑输入
Diffchecker Desktop
运行Diffchecker最安全的方式。获取Diffchecker桌面应用:您的差异永远不会离开您的电脑!
获取桌面版
Untitled diff
创建于
11年前
差异永不过期
清除
导出
分享
解释
27 删除
行
总计
删除
字符
总计
删除
要继续使用此功能,请升级到
Diff
checker
Pro
查看价格
423 行
全部复制
119 添加
行
总计
添加
字符
总计
添加
要继续使用此功能,请升级到
Diff
checker
Pro
查看价格
498 行
全部复制
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
####################################################################################
####################################################################################
## INFORMATION
## INFORMATION
####################################################################################
####################################################################################
## Developed by: Steven Johnson (minor modifications by egretsareherons)
## Developed by: Steven Johnson (minor modifications by egretsareherons)
## (a minor modifications by aross01)
## (a minor modifications by aross01)
## (a minor modification by STEEVo)
## (a minor modification by STEEVo)
##
##
## Last Updated: 02/26/2014 5:05PM MST
## Last Updated: 02/26/2014 5:05PM MST
##
##
## Description: Auto-Delete Watched Items In Plex
## Description: Auto-Delete Watched Items In Plex
##
##
## Required Configurations:
## Required Configurations:
## - PC (Blank = AutoDetect | W = Windows | L = Linux/Unix/MAC)
## - PC (Blank = AutoDetect | W = Windows | L = Linux/Unix/MAC)
## - Host (Hostname or IP | Blank = 127.0.0.1)
## - Host (Hostname or IP | Blank = 127.0.0.1)
## - Port (Port | Blank = 32400)
## - Port (Port | Blank = 32400)
## - SectionList - A list of sections to operate on. If this is blank, the script
## - SectionList - A list of sections to operate on. If this is blank, the script
## will get a list of all sections from the server & operate on all, except
## will get a list of all sections from the server & operate on all, except
## for the sections listed in IgnoreSections
## for the sections listed in IgnoreSections
## - IgnoreSections - Only used if SectionList is blank. When SectionList is blank,
## - IgnoreSections - Only used if SectionList is blank. When SectionList is blank,
## the script will operate on all available sections of your install
## the script will operate on all available sections of your install
## except for the ones listed here.
## except for the ones listed here.
## - Delete (1 = Delete | Blank = 0 (For Testing or Review))
## - Delete (1 = Delete | Blank = 0 (For Testing or Review))
## - Move (1 = move files to DestinationDir, 0 = don't move)
## - Move (1 = move files to DestinationDir, 0 = don't move)
## - Copy (1 = copy files to DestinationDir, 0 = don't copy)
## - Copy (1 = copy files to DestinationDir, 0 = don't copy)
## - Shows ( ["Show1","Show2"]; = Kept Shows OR [""]; = DEL ALL SHOWS )
## - Shows ( ["Show1","Show2"]; = Kept Shows OR [""]; = DEL ALL SHOWS )
## - OnDeck ( 1 = Keep If On Deck | Blank = Delete Regardless if onDeck )
## - OnDeck ( 1 = Keep If On Deck | Blank = Delete Regardless if onDeck )
## - DestinationDir - the place to move or copy your watched files for later manual deletion
## - DestinationDir - the place to move or copy your watched files for later manual deletion
## - DestinationSection - if your destination dir is also a configured section, set the
## - DestinationSection - if your destination dir is also a configured section, set the
## number here so TriggerRescan knows to rescan that section when changes are made.
## number here so TriggerRescan knows to rescan that section when changes are made.
## only used if TriggerRescan is True;
## only used if TriggerRescan is True;
## - TriggerRescan - automatically trigger a deep rescan of changed sections. True or False.
## - TriggerRescan - automatically trigger a deep rescan of changed sections. True or False.
##
##
## - KeepMode (Blank = Disabled | W = "Watched" | A = "Added")
## - KeepMode (Blank = Disabled | W = "Watched" | A = "Added")
## Method used to keep items for X number of days (specified by DaysToKeep below.)
## Method used to keep items for X number of days (specified by DaysToKeep below.)
## You may choose to base the keep on the last "watched" or "added" date.
## You may choose to base the keep on the last "watched" or "added" date.
## - DaysToKeep ("30" = Keep items for 30 days following the KeepMode selected)
## - DaysToKeep ("30" = Keep items for 30 days following the KeepMode selected)
##
##
####################################################################################
####################################################################################
####################################################################################
####################################################################################
PC = "W"
PC = "W"
复制
已复制
复制
已复制
Host = "
127.0.0.1
"
Host = "
"
Port = ""
Port = ""
SectionList = [1,2,7]
SectionList = [1,2,7]
IgnoreSections = []
IgnoreSections = []
Delete = "1"
Delete = "1"
复制
已复制
复制
已复制
DeleteSimilar = "1"
Move = "0"
Move = "0"
Copy = "0"
Copy = "0"
Shows = []
Shows = []
OnDeck = "1"
OnDeck = "1"
复制
已复制
复制
已复制
DestinationDir = "
D:\!M
edia
\RecycleBin
"
DestinationDir = "
/m
edia
/delete
"
DestinationSection = ""
DestinationSection = ""
复制
已复制
复制
已复制
KeepMode = ""
DaysToKeep = 14
TriggerRescan = True
TriggerRescan = True
复制
已复制
复制
已复制
KeepMode
= ""
DaysToKeep
=
30
#Use Username/Password or Token.
Username
= ""
Password = ""
# or
Token
=
""
####################################################################################
####################################################################################
## NO NEED TO EDIT BELOW THIS LINE
## NO NEED TO EDIT BELOW THIS LINE
####################################################################################
####################################################################################
import os
import os
import xml.dom.minidom
import xml.dom.minidom
import platform
import platform
import re
import re
import shutil
import shutil
import datetime
import datetime
import glob
import glob
复制
已复制
复制
已复制
import sys
try:
try:
import urllib.request as urllib2
import urllib.request as urllib2
except:
except:
import urllib2
import urllib2
####################################################################################
####################################################################################
## Check On Deck
## Check On Deck
####################################################################################
####################################################################################
def CheckOnDeck( CheckDeckFile ):
def CheckOnDeck( CheckDeckFile ):
InTheDeck = 0
InTheDeck = 0
for DeckVideoNode in deck.getElementsByTagName("Video"):
for DeckVideoNode in deck.getElementsByTagName("Video"):
DeckMediaNode = DeckVideoNode.getElementsByTagName("Media")
DeckMediaNode = DeckVideoNode.getElementsByTagName("Media")
for DeckMedia in DeckMediaNode:
for DeckMedia in DeckMediaNode:
DeckPartNode = DeckMedia.getElementsByTagName("Part")
DeckPartNode = DeckMedia.getElementsByTagName("Part")
for DeckPart in DeckPartNode:
for DeckPart in DeckPartNode:
Deckfile = DeckPart.getAttribute("file")
Deckfile = DeckPart.getAttribute("file")
if CheckDeckFile==Deckfile:
if CheckDeckFile==Deckfile:
InTheDeck += 1
InTheDeck += 1
else:
else:
InTheDeck += 0
InTheDeck += 0
return InTheDeck
return InTheDeck
####################################################################################
####################################################################################
## Check Shows And Delete If Configured
## Check Shows And Delete If Configured
####################################################################################
####################################################################################
def CheckShows( CheckFile ):
def CheckShows( CheckFile ):
global FileCount
global FileCount
global DeleteCount
global DeleteCount
global MoveCount
global MoveCount
global CopyCount
global CopyCount
global FlaggedCount
global FlaggedCount
global OnDeckCount
global OnDeckCount
global ShowsCount
global ShowsCount
global DestinationDir
global DestinationDir
FileCount += 1
FileCount += 1
CantDelete = 0
CantDelete = 0
ShowFound = ""
ShowFound = ""
changed = 0
changed = 0
## -- CHECK SHOWS --
## -- CHECK SHOWS --
for Show in Shows:
for Show in Shows:
Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip()
Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip()
if Show=="":
if Show=="":
CantDelete = 0
CantDelete = 0
else:
else:
if (' ' in Show) == True:
if (' ' in Show) == True:
if all(str(Word) in CheckFile for Word in Show.split()):
if all(str(Word) in CheckFile for Word in Show.split()):
CantDelete += 1
CantDelete += 1
ShowFound = "[" + Show + "]"
ShowFound = "[" + Show + "]"
ShowsCount += 1
ShowsCount += 1
复制
已复制
复制
已复制
break
else:
else:
CantDelete += 0
CantDelete += 0
else:
else:
if Show in CheckFile:
if Show in CheckFile:
CantDelete += 1
CantDelete += 1
ShowFound = "[" + Show + "]"
ShowFound = "[" + Show + "]"
ShowsCount += 1
ShowsCount += 1
复制
已复制
复制
已复制
break
else:
else:
CantDelete += 0
CantDelete += 0
## -- Check OnDeck --
## -- Check OnDeck --
if OnDeck=="1":
if OnDeck=="1":
IsOnDeck = CheckOnDeck(CheckFile);
IsOnDeck = CheckOnDeck(CheckFile);
if IsOnDeck==0:
if IsOnDeck==0:
CantDelete += 0
CantDelete += 0
else:
else:
CantDelete += 1
CantDelete += 1
ShowFound = "[OnDeck]" + ShowFound
ShowFound = "[OnDeck]" + ShowFound
OnDeckCount += 1
OnDeckCount += 1
## -- Check if video older than days to keep [Viewed method] --
## -- Check if video older than days to keep [Viewed method] --
复制
已复制
复制
已复制
## and check if the file has been added for that time to keep from deleting reimported files
if KeepMode=="W":
if KeepMode=="W":
复制
已复制
复制
已复制
if
DaysToKeep > DaysSinceVideoLastViewed
:
if
(
DaysToKeep > DaysSinceVideoLastViewed
) or (DaysToKeep > DaysSinceVideoAdded)
:
CantDelete += 1
CantDelete += 1
ShowsCount += 1
ShowsCount += 1
# ShowFound = " | Days Since Viewed:" + str(DaysSinceVideoLastViewed) +" |" + ShowFound
# ShowFound = " | Days Since Viewed:" + str(DaysSinceVideoLastViewed) +" |" + ShowFound
## -- Check if video older than days to keep [Added method] --
## -- Check if video older than days to keep [Added method] --
if KeepMode=="A":
if KeepMode=="A":
if DaysToKeep > DaysSinceVideoAdded:
if DaysToKeep > DaysSinceVideoAdded:
复制
已复制
复制
已复制
CantDelete += 1
CantDelete += 1
ShowsCount += 1
ShowsCount += 1
# ShowFound = " | Days Since Added:" + str(DaysSinceVideoAdded) +" |" + ShowFound
# ShowFound = " | Days Since Added:" + str(DaysSinceVideoAdded) +" |" + ShowFound
复制
已复制
复制
已复制
## -- DELETE SHOWS --
## -- DELETE SHOWS --
if CantDelete == 0:
if CantDelete == 0:
if Delete=="1":
if Delete=="1":
#print("**[DELETED] " + CheckFile)
#print("**[DELETED] " + CheckFile)
复制
已复制
复制
已复制
simila
i
rFiles = os.path.splitext(
file
)[0] + "*"
if DeleteSimilar=="1":
print("Looking for " + simila
i
rFiles)
simila
rFiles = os.path.splitext(
CheckFile
)[0] + "*"
for deleteFile in glob.glob(simila
i
rFiles):
print("Looking for " + simila
rFiles)
try:
for deleteFile in glob.glob(simila
rFiles):
os.remove(deleteFile)
try:
print("**[DELETED] " + deleteFile)
os.remove(deleteFile)
changed = 1
print("**[DELETED] " + deleteFile)
DeleteCount += 1
changed = 1
except Exception as e:
DeleteCount += 1
print ("error deleting file: %s" % e)
except Exception as e:
print ("error deleting file: %s" % e)
else:
try:
os.remove(os.path.realpath(CheckFile))
print("**[DELETED] " + CheckFile)
changed = 1
DeleteCount += 1
except Exception as e:
print ("error deleting file: %s" % e)
elif Move == "1":
elif Move == "1":
try:
try:
os.utime(os.path.realpath(CheckFile), None)
os.utime(os.path.realpath(CheckFile), None)
shutil.move(os.path.realpath(CheckFile), DestinationDir)
shutil.move(os.path.realpath(CheckFile), DestinationDir)
print("**[MOVED] " + CheckFile)
print("**[MOVED] " + CheckFile)
changed = 1
changed = 1
except Exception as e:
except Exception as e:
print ("error moving file: %s" % e)
print ("error moving file: %s" % e)
if os.path.islink(CheckFile):
if os.path.islink(CheckFile):
os.unlink(CheckFile)
os.unlink(CheckFile)
MoveCount += 1
MoveCount += 1
elif Copy == "1":
elif Copy == "1":
try:
try:
shutil.copy(os.path.realpath(CheckFile), DestinationDir)
shutil.copy(os.path.realpath(CheckFile), DestinationDir)
changed = 1
changed = 1
except Exception as e:
except Exception as e:
print ("error copying file: %s" % e)
print ("error copying file: %s" % e)
print("**[COPIED] " + CheckFile)
print("**[COPIED] " + CheckFile)
CopyCount += 1
CopyCount += 1
else:
else:
print("**[FLAGGED] " + CheckFile)
print("**[FLAGGED] " + CheckFile)
FlaggedCount += 1
FlaggedCount += 1
else:
else:
print("[KEEPING]")
print("[KEEPING]")
return changed
return changed
####################################################################################
####################################################################################
## Checking URL
## Checking URL
####################################################################################
####################################################################################
if Host=="":
if Host=="":
Host="127.0.0.1"
Host="127.0.0.1"
if Port=="":
if Port=="":
Port="32400"
Port="32400"
复制
已复制
复制
已复制
#parse arguments
if len(sys.argv) > 1:
if sys.argv[1].lower() in ("-test", "--test"):
print("Running in Test Mode")
Delete = 0
Move = 0
Copy = 0
else:
print("Invalid Argument! - Use -test or --test for testing")
sys.exit(2)
login = False
#Use Token by default, but if not found then use myPlex Login to get a Token
#Modified from dane22 on the PlexForums
if Token=="":
if not Username=="":
import base64
import json
encode = base64.encodestring('%s:%s' % (Username,Password)).replace('\n','')
URL = ("https://plex.tv/users/sign_in.json")
headers= {}
headers['X-Plex-Device-Name'] = "Python"
headers['X-Plex-Platform'] = platform.system()
headers['X-Plex-Device'] = platform.system()
headers['X-Plex-Platform-Version'] = platform.release()
headers['X-Plex-Provides'] = "Python"
headers['X-Plex-Product'] = "Auto Delete Watched"
headers['X-Plex-Client-Identifier'] = "10101010101010"
headers['X-Plex-Version'] = platform.python_version()
headers['Authorization'] = 'Basic ' + encode
req = urllib2.Request(URL,"None",headers)
#req.get_method = lambda: 'POST'
try:
Token = json.load(urllib2.urlopen(req))['user']['authentication_token']
except:
Token=""
#print(Token)
login = True
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print(" Detected Settings")
print(" Detected Settings")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print("Host: " + Host)
print("Host: " + Host)
print("Port: " + Port)
print("Port: " + Port)
#print("Section: " + Section)
#print("Section: " + Section)
#print("URL: " + URL)
#print("URL: " + URL)
#print("OnDeck URL: " + OnDeckURL)
#print("OnDeck URL: " + OnDeckURL)
复制
已复制
复制
已复制
if login:
print("Logged in as: " + Username)
elif not Token=="":
print("Using Token for login")
else:
print("No Login specified")
if KeepMode=="W":
if KeepMode=="W":
print("Keep Mode: Keeping for " + str(DaysToKeep) + " days following the date last viewed")
print("Keep Mode: Keeping for " + str(DaysToKeep) + " days following the date last viewed")
elif KeepMode=="A":
elif KeepMode=="A":
print("Keep Mode: Keeping viewed items that were added to the library less than " + str(DaysToKeep) + " days ago")
print("Keep Mode: Keeping viewed items that were added to the library less than " + str(DaysToKeep) + " days ago")
else:
else:
print("Keep Mode: DISABLED")
print("Keep Mode: DISABLED")
####################################################################################
####################################################################################
## Checking Shows
## Checking Shows
####################################################################################
####################################################################################
NoDelete = " | "
NoDelete = " | "
ShowCount = len(Shows)
ShowCount = len(Shows)
print("Show Count: " + str(ShowCount))
print("Show Count: " + str(ShowCount))
for Show in Shows:
for Show in Shows:
Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip()
Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip()
if Show=="":
if Show=="":
NoDelete += "(None Listed) | "
NoDelete += "(None Listed) | "
ShowCount -= 1
ShowCount -= 1
else:
else:
NoDelete += Show + " | "
NoDelete += Show + " | "
print("Number of Shows Detected For Keeping: " + str(ShowCount))
print("Number of Shows Detected For Keeping: " + str(ShowCount))
print ("Shows to Keep:" + NoDelete)
print ("Shows to Keep:" + NoDelete)
###################################################################################
###################################################################################
## Checking Delete
## Checking Delete
####################################################################################
####################################################################################
if Delete=="1":
if Delete=="1":
print("Delete: ***Enabled***")
print("Delete: ***Enabled***")
else:
else:
print("Delete: Disabled - Flagging Only")
print("Delete: Disabled - Flagging Only")
if OnDeck=="1":
if OnDeck=="1":
print("Delete OnDeck: No")
print("Delete OnDeck: No")
else:
else:
print("Delete OnDeck: Yes")
print("Delete OnDeck: Yes")
####################################################################################
####################################################################################
## Checking OS
## Checking OS
####################################################################################
####################################################################################
AD = ""
AD = ""
if PC=="":
if PC=="":
AD = "(Auto Detected)"
AD = "(Auto Detected)"
if platform.system()=="Windows":
if platform.system()=="Windows":
PC = "W"
PC = "W"
elif platform.system()=="Linux":
elif platform.system()=="Linux":
PC = "L"
PC = "L"
elif platform.system()=="Darwin":
elif platform.system()=="Darwin":
PC = "L"
PC = "L"
FileCount = 0
FileCount = 0
DeleteCount = 0
DeleteCount = 0
MoveCount = 0
MoveCount = 0
CopyCount = 0
CopyCount = 0
FlaggedCount = 0
FlaggedCount = 0
OnDeckCount = 0
OnDeckCount = 0
ShowsCount = 0
ShowsCount = 0
复制
已复制
复制
已复制
TriggerRescan = False
RescannedSections = []
RescannedSections = []
####################################################################################
####################################################################################
## Get list of sections
## Get list of sections
####################################################################################
####################################################################################
if PC=="L":
if PC=="L":
print("Operating System: Linux " + AD)
print("Operating System: Linux " + AD)
复制
已复制
复制
已复制
import urllib2
#
import urllib2
elif PC=="W":
elif PC=="W":
print("Operating System: Windows " + AD)
print("Operating System: Windows " + AD)
复制
已复制
复制
已复制
import urllib.request
#
import urllib.request
else:
else:
print("Operating System: ** Not Configured ** (" + platform.system() + ") is not recognized.")
print("Operating System: ** Not Configured ** (" + platform.system() + ") is not recognized.")
exit()
exit()
if not SectionList:
if not SectionList:
URL = ("http://" + Host + ":" + Port + "/library/sections/")
URL = ("http://" + Host + ":" + Port + "/library/sections/")
复制
已复制
复制
已复制
doc = xml.dom.minidom.parse(urllib2.urlopen(
URL
))
req = urllib2.Request(URL,None,{"X-Plex-Token":Token})
doc = xml.dom.minidom.parse(urllib2.urlopen(
req
))
for Section in doc.getElementsByTagName("Directory"):
for Section in doc.getElementsByTagName("Directory"):
if Section.getAttribute("key") not in IgnoreSections:
if Section.getAttribute("key") not in IgnoreSections:
SectionList.append(Section.getAttribute("key"))
SectionList.append(Section.getAttribute("key"))
SectionList.sort(key=int)
SectionList.sort(key=int)
print ("Section List Mode: Auto")
print ("Section List Mode: Auto")
print ("Operating on sections: " + ','.join(str(x) for x in SectionList))
print ("Operating on sections: " + ','.join(str(x) for x in SectionList))
print ("Skipping Sections: " + ','.join(str(x) for x in IgnoreSections))
print ("Skipping Sections: " + ','.join(str(x) for x in IgnoreSections))
else:
else:
print ("Section List Mode: User-defined")
print ("Section List Mode: User-defined")
print ("Operating on user-defined sections: " + ','.join(str(x) for x in SectionList))
print ("Operating on user-defined sections: " + ','.join(str(x) for x in SectionList))
####################################################################################
####################################################################################
## Loop on sections
## Loop on sections
####################################################################################
####################################################################################
rescan_destination = False
rescan_destination = False
for Section in SectionList:
for Section in SectionList:
Section = str(Section)
Section = str(Section)
URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/recentlyViewed")
URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/recentlyViewed")
OnDeckURL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/onDeck")
OnDeckURL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/onDeck")
####################################################################################
####################################################################################
## Setting OS Based Variables
## Setting OS Based Variables
####################################################################################
####################################################################################
if PC=="L":
if PC=="L":
复制
已复制
复制
已复制
doc = xml.dom.minidom.parse(urllib2.urlopen(
URL
))
req = urllib2.Request(URL,None,{"X-Plex-Token":Token})
deck = xml.dom.minidom.parse(urllib2.urlopen(
OnDeckURL
))
doc = xml.dom.minidom.parse(urllib2.urlopen(
req
))
req = urllib2.Request(OnDeckURL,None,{"X-Plex-Token":Token})
deck = xml.dom.minidom.parse(urllib2.urlopen(
req
))
elif PC=="W":
elif PC=="W":
复制
已复制
复制
已复制
doc = xml.dom.minidom.parse(urllib.request.urlopen(
URL
))
req = urllib2.Request(URL,None,{"X-Plex-Token":Token})
deck = xml.dom.minidom.parse(urllib.request.urlopen(
OnDeckURL
))
doc = xml.dom.minidom.parse(urllib.request.urlopen(
req
))
req = urllib2.Request(OnDeckURL,None,{"X-Plex-Token":Token})
deck = xml.dom.minidom.parse(urllib.request.urlopen(
req
))
SectionName = doc.getElementsByTagName("MediaContainer")[0].getAttribute("title1")
SectionName = doc.getElementsByTagName("MediaContainer")[0].getAttribute("title1")
print("")
print("")
print("--------- Section "+ Section +": " + SectionName + " -----------------------------------")
print("--------- Section "+ Section +": " + SectionName + " -----------------------------------")
####################################################################################
####################################################################################
## Get Files for Watched Shows
## Get Files for Watched Shows
####################################################################################
####################################################################################
changed = 0
changed = 0
for VideoNode in doc.getElementsByTagName("Video"):
for VideoNode in doc.getElementsByTagName("Video"):
view = VideoNode.getAttribute("viewCount")
view = VideoNode.getAttribute("viewCount")
if view == '':
if view == '':
view = 0
view = 0
view = int(view)
view = int(view)
################################################################
################################################################
###Find number of days between date video was viewed and today
###Find number of days between date video was viewed and today
lastViewedAt = VideoNode.getAttribute("lastViewedAt")
lastViewedAt = VideoNode.getAttribute("lastViewedAt")
d1 = datetime.datetime.today()
d1 = datetime.datetime.today()
d2 = datetime.datetime.fromtimestamp(float(lastViewedAt))
d2 = datetime.datetime.fromtimestamp(float(lastViewedAt))
DaysSinceVideoLastViewed = (d1 - d2).days
DaysSinceVideoLastViewed = (d1 - d2).days
################################################################
################################################################
################################################################
################################################################
###Find number of days between date video was added and today
###Find number of days between date video was added and today
addedAt = VideoNode.getAttribute("addedAt")
addedAt = VideoNode.getAttribute("addedAt")
d1 = datetime.datetime.today()
d1 = datetime.datetime.today()
da2 = datetime.datetime.fromtimestamp(float(addedAt))
da2 = datetime.datetime.fromtimestamp(float(addedAt))
DaysSinceVideoAdded = (d1 - da2).days
DaysSinceVideoAdded = (d1 - da2).days
################################################################
################################################################
MediaNode = VideoNode.getElementsByTagName("Media")
MediaNode = VideoNode.getElementsByTagName("Media")
for Media in MediaNode:
for Media in MediaNode:
PartNode = Media.getElementsByTagName("Part")
PartNode = Media.getElementsByTagName("Part")
for Part in PartNode:
for Part in PartNode:
file = Part.getAttribute("file")
file = Part.getAttribute("file")
#NEW (Removed by Mustang):
#NEW (Removed by Mustang):
复制
已复制
复制
已复制
#
if
PC == 'L
':
if
sys.version < '3
':
#
file = urllib2.unquote(file.encode('utf
-
8')).decode('utf
-
8')
file = urllib2.unquote(file.encode('utf
_
8')).decode('utf
_
8')
#
else:
else:
#
import urllib
import urllib
#
file = urllib.parse.unquote(file
.encode('utf-8')).decode('utf-8'
)
file = urllib.parse.unquote(file
)
if str(view)!="0":
if str(view)!="0":
print(" ")
print(" ")
if KeepMode=="W":
if KeepMode=="W":
if str(view)!="0":
if str(view)!="0":
print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " | " + file)
print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " | " + file)
if view > 0:
if view > 0:
if os.path.isfile(file):
if os.path.isfile(file):
changed += CheckShows(file);
changed += CheckShows(file);
else:
else:
print("##[NOT FOUND] " + file)
print("##[NOT FOUND] " + file)
if KeepMode=="A":
if KeepMode=="A":
if str(view)!="0":
if str(view)!="0":
print ("Viewed:" + str(view) + "x | Days Since Added: " + str(DaysSinceVideoAdded) + " | " + file)
print ("Viewed:" + str(view) + "x | Days Since Added: " + str(DaysSinceVideoAdded) + " | " + file)
if view > 0:
if view > 0:
if os.path.isfile(file):
if os.path.isfile(file):
changed += CheckShows(file);
changed += CheckShows(file);
else:
else:
print("##[NOT FOUND] " + file)
print("##[NOT FOUND] " + file)
if KeepMode=="":
if KeepMode=="":
if str(view)!="0":
if str(view)!="0":
print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " Added: " + str(DaysSinceVideoAdded) + " | " + file)
print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " Added: " + str(DaysSinceVideoAdded) + " | " + file)
if view > 0:
if view > 0:
if os.path.isfile(file):
if os.path.isfile(file):
changed += CheckShows(file);
changed += CheckShows(file);
else:
else:
print("##[NOT FOUND] " + file)
print("##[NOT FOUND] " + file)
# rescan this section if necessary
# rescan this section if necessary
if TriggerRescan and changed:
if TriggerRescan and changed:
URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/refresh?deep=1")
URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/refresh?deep=1")
复制
已复制
复制
已复制
blah = urllib2.urlopen(URL
)
#
blah = urllib2.urlopen(URL
,data
)
RescannedSections.append(SectionName + '(' + Section + ')')
RescannedSections.append(SectionName + '(' + Section + ')')
rescan_destination = True
rescan_destination = True
# rescan destination section if necessary
# rescan destination section if necessary
if TriggerRescan and DestinationSection and rescan_destination:
if TriggerRescan and DestinationSection and rescan_destination:
URL = ("http://" + Host + ":" + Port + "/library/sections/" + str(DestinationSection) + "/refresh?deep=1")
URL = ("http://" + Host + ":" + Port + "/library/sections/" + str(DestinationSection) + "/refresh?deep=1")
复制
已复制
复制
已复制
blah = urllib2.urlopen(URL
)
#
blah = urllib2.urlopen(URL
,data
)
RescannedSections.append('[destination dir]' + '(' + str(DestinationSection) + ')')
RescannedSections.append('[destination dir]' + '(' + str(DestinationSection) + ')')
print("")
print("")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print(" Summary -- Script Completed Successfully")
print(" Summary -- Script Completed Successfully")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
print("")
print("")
print(" Total File Count " + str(FileCount))
print(" Total File Count " + str(FileCount))
print(" Kept Show Files " + str(ShowsCount))
print(" Kept Show Files " + str(ShowsCount))
print(" On Deck Files " + str(OnDeckCount))
print(" On Deck Files " + str(OnDeckCount))
print(" Deleted Files " + str(DeleteCount))
print(" Deleted Files " + str(DeleteCount))
print(" Moved Files " + str(MoveCount))
print(" Moved Files " + str(MoveCount))
print(" Copied Files " + str(CopyCount))
print(" Copied Files " + str(CopyCount))
print(" Flagged Files " + str(FlaggedCount))
print(" Flagged Files " + str(FlaggedCount))
复制
已复制
复制
已复制
print(" Rescanned Sections " + ', '.join(str(x) for x in RescannedSections) )
if TriggerRescan:
print(" Rescanned Sections " + ', '.join(str(x) for x in RescannedSections) )
print("")
print("")
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
复制
已复制
复制
已复制
print("----------------------------------------------------------------------------")
print("----------------------------------------------------------------------------")
input()
input()
已保存差异
原始文本
打开文件
#!/usr/bin/python # -*- coding: utf-8 -*- #################################################################################### ## INFORMATION #################################################################################### ## Developed by: Steven Johnson (minor modifications by egretsareherons) ## (a minor modifications by aross01) ## (a minor modification by STEEVo) ## ## Last Updated: 02/26/2014 5:05PM MST ## ## Description: Auto-Delete Watched Items In Plex ## ## Required Configurations: ## - PC (Blank = AutoDetect | W = Windows | L = Linux/Unix/MAC) ## - Host (Hostname or IP | Blank = 127.0.0.1) ## - Port (Port | Blank = 32400) ## - SectionList - A list of sections to operate on. If this is blank, the script ## will get a list of all sections from the server & operate on all, except ## for the sections listed in IgnoreSections ## - IgnoreSections - Only used if SectionList is blank. When SectionList is blank, ## the script will operate on all available sections of your install ## except for the ones listed here. ## - Delete (1 = Delete | Blank = 0 (For Testing or Review)) ## - Move (1 = move files to DestinationDir, 0 = don't move) ## - Copy (1 = copy files to DestinationDir, 0 = don't copy) ## - Shows ( ["Show1","Show2"]; = Kept Shows OR [""]; = DEL ALL SHOWS ) ## - OnDeck ( 1 = Keep If On Deck | Blank = Delete Regardless if onDeck ) ## - DestinationDir - the place to move or copy your watched files for later manual deletion ## - DestinationSection - if your destination dir is also a configured section, set the ## number here so TriggerRescan knows to rescan that section when changes are made. ## only used if TriggerRescan is True; ## - TriggerRescan - automatically trigger a deep rescan of changed sections. True or False. ## ## - KeepMode (Blank = Disabled | W = "Watched" | A = "Added") ## Method used to keep items for X number of days (specified by DaysToKeep below.) ## You may choose to base the keep on the last "watched" or "added" date. ## - DaysToKeep ("30" = Keep items for 30 days following the KeepMode selected) ## #################################################################################### #################################################################################### PC = "W" Host = "127.0.0.1" Port = "" SectionList = [1,2,7] IgnoreSections = [] Delete = "1" Move = "0" Copy = "0" Shows = [] OnDeck = "1" DestinationDir = "D:\!Media\RecycleBin" DestinationSection = "" TriggerRescan = True KeepMode = "" DaysToKeep = 30 #################################################################################### ## NO NEED TO EDIT BELOW THIS LINE #################################################################################### import os import xml.dom.minidom import platform import re import shutil import datetime import glob try: import urllib.request as urllib2 except: import urllib2 #################################################################################### ## Check On Deck #################################################################################### def CheckOnDeck( CheckDeckFile ): InTheDeck = 0 for DeckVideoNode in deck.getElementsByTagName("Video"): DeckMediaNode = DeckVideoNode.getElementsByTagName("Media") for DeckMedia in DeckMediaNode: DeckPartNode = DeckMedia.getElementsByTagName("Part") for DeckPart in DeckPartNode: Deckfile = DeckPart.getAttribute("file") if CheckDeckFile==Deckfile: InTheDeck += 1 else: InTheDeck += 0 return InTheDeck #################################################################################### ## Check Shows And Delete If Configured #################################################################################### def CheckShows( CheckFile ): global FileCount global DeleteCount global MoveCount global CopyCount global FlaggedCount global OnDeckCount global ShowsCount global DestinationDir FileCount += 1 CantDelete = 0 ShowFound = "" changed = 0 ## -- CHECK SHOWS -- for Show in Shows: Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip() if Show=="": CantDelete = 0 else: if (' ' in Show) == True: if all(str(Word) in CheckFile for Word in Show.split()): CantDelete += 1 ShowFound = "[" + Show + "]" ShowsCount += 1 else: CantDelete += 0 else: if Show in CheckFile: CantDelete += 1 ShowFound = "[" + Show + "]" ShowsCount += 1 else: CantDelete += 0 ## -- Check OnDeck -- if OnDeck=="1": IsOnDeck = CheckOnDeck(CheckFile); if IsOnDeck==0: CantDelete += 0 else: CantDelete += 1 ShowFound = "[OnDeck]" + ShowFound OnDeckCount += 1 ## -- Check if video older than days to keep [Viewed method] -- if KeepMode=="W": if DaysToKeep > DaysSinceVideoLastViewed: CantDelete += 1 ShowsCount += 1 # ShowFound = " | Days Since Viewed:" + str(DaysSinceVideoLastViewed) +" |" + ShowFound ## -- Check if video older than days to keep [Added method] -- if KeepMode=="A": if DaysToKeep > DaysSinceVideoAdded: CantDelete += 1 ShowsCount += 1 # ShowFound = " | Days Since Added:" + str(DaysSinceVideoAdded) +" |" + ShowFound ## -- DELETE SHOWS -- if CantDelete == 0: if Delete=="1": #print("**[DELETED] " + CheckFile) similairFiles = os.path.splitext(file)[0] + "*" print("Looking for " + similairFiles) for deleteFile in glob.glob(similairFiles): try: os.remove(deleteFile) print("**[DELETED] " + deleteFile) changed = 1 DeleteCount += 1 except Exception as e: print ("error deleting file: %s" % e) elif Move == "1": try: os.utime(os.path.realpath(CheckFile), None) shutil.move(os.path.realpath(CheckFile), DestinationDir) print("**[MOVED] " + CheckFile) changed = 1 except Exception as e: print ("error moving file: %s" % e) if os.path.islink(CheckFile): os.unlink(CheckFile) MoveCount += 1 elif Copy == "1": try: shutil.copy(os.path.realpath(CheckFile), DestinationDir) changed = 1 except Exception as e: print ("error copying file: %s" % e) print("**[COPIED] " + CheckFile) CopyCount += 1 else: print("**[FLAGGED] " + CheckFile) FlaggedCount += 1 else: print("[KEEPING]") return changed #################################################################################### ## Checking URL #################################################################################### if Host=="": Host="127.0.0.1" if Port=="": Port="32400" print("----------------------------------------------------------------------------") print(" Detected Settings") print("----------------------------------------------------------------------------") print("Host: " + Host) print("Port: " + Port) #print("Section: " + Section) #print("URL: " + URL) #print("OnDeck URL: " + OnDeckURL) if KeepMode=="W": print("Keep Mode: Keeping for " + str(DaysToKeep) + " days following the date last viewed") elif KeepMode=="A": print("Keep Mode: Keeping viewed items that were added to the library less than " + str(DaysToKeep) + " days ago") else: print("Keep Mode: DISABLED") #################################################################################### ## Checking Shows #################################################################################### NoDelete = " | " ShowCount = len(Shows) print("Show Count: " + str(ShowCount)) for Show in Shows: Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip() if Show=="": NoDelete += "(None Listed) | " ShowCount -= 1 else: NoDelete += Show + " | " print("Number of Shows Detected For Keeping: " + str(ShowCount)) print ("Shows to Keep:" + NoDelete) ################################################################################### ## Checking Delete #################################################################################### if Delete=="1": print("Delete: ***Enabled***") else: print("Delete: Disabled - Flagging Only") if OnDeck=="1": print("Delete OnDeck: No") else: print("Delete OnDeck: Yes") #################################################################################### ## Checking OS #################################################################################### AD = "" if PC=="": AD = "(Auto Detected)" if platform.system()=="Windows": PC = "W" elif platform.system()=="Linux": PC = "L" elif platform.system()=="Darwin": PC = "L" FileCount = 0 DeleteCount = 0 MoveCount = 0 CopyCount = 0 FlaggedCount = 0 OnDeckCount = 0 ShowsCount = 0 RescannedSections = [] #################################################################################### ## Get list of sections #################################################################################### if PC=="L": print("Operating System: Linux " + AD) import urllib2 elif PC=="W": print("Operating System: Windows " + AD) import urllib.request else: print("Operating System: ** Not Configured ** (" + platform.system() + ") is not recognized.") exit() if not SectionList: URL = ("http://" + Host + ":" + Port + "/library/sections/") doc = xml.dom.minidom.parse(urllib2.urlopen(URL)) for Section in doc.getElementsByTagName("Directory"): if Section.getAttribute("key") not in IgnoreSections: SectionList.append(Section.getAttribute("key")) SectionList.sort(key=int) print ("Section List Mode: Auto") print ("Operating on sections: " + ','.join(str(x) for x in SectionList)) print ("Skipping Sections: " + ','.join(str(x) for x in IgnoreSections)) else: print ("Section List Mode: User-defined") print ("Operating on user-defined sections: " + ','.join(str(x) for x in SectionList)) #################################################################################### ## Loop on sections #################################################################################### rescan_destination = False for Section in SectionList: Section = str(Section) URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/recentlyViewed") OnDeckURL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/onDeck") #################################################################################### ## Setting OS Based Variables #################################################################################### if PC=="L": doc = xml.dom.minidom.parse(urllib2.urlopen(URL)) deck = xml.dom.minidom.parse(urllib2.urlopen(OnDeckURL)) elif PC=="W": doc = xml.dom.minidom.parse(urllib.request.urlopen(URL)) deck = xml.dom.minidom.parse(urllib.request.urlopen(OnDeckURL)) SectionName = doc.getElementsByTagName("MediaContainer")[0].getAttribute("title1") print("") print("--------- Section "+ Section +": " + SectionName + " -----------------------------------") #################################################################################### ## Get Files for Watched Shows #################################################################################### changed = 0 for VideoNode in doc.getElementsByTagName("Video"): view = VideoNode.getAttribute("viewCount") if view == '': view = 0 view = int(view) ################################################################ ###Find number of days between date video was viewed and today lastViewedAt = VideoNode.getAttribute("lastViewedAt") d1 = datetime.datetime.today() d2 = datetime.datetime.fromtimestamp(float(lastViewedAt)) DaysSinceVideoLastViewed = (d1 - d2).days ################################################################ ################################################################ ###Find number of days between date video was added and today addedAt = VideoNode.getAttribute("addedAt") d1 = datetime.datetime.today() da2 = datetime.datetime.fromtimestamp(float(addedAt)) DaysSinceVideoAdded = (d1 - da2).days ################################################################ MediaNode = VideoNode.getElementsByTagName("Media") for Media in MediaNode: PartNode = Media.getElementsByTagName("Part") for Part in PartNode: file = Part.getAttribute("file") #NEW (Removed by Mustang): #if PC == 'L': #file = urllib2.unquote(file.encode('utf-8')).decode('utf-8') #else: #import urllib #file = urllib.parse.unquote(file.encode('utf-8')).decode('utf-8') if str(view)!="0": print(" ") if KeepMode=="W": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) if KeepMode=="A": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Added: " + str(DaysSinceVideoAdded) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) if KeepMode=="": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " Added: " + str(DaysSinceVideoAdded) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) # rescan this section if necessary if TriggerRescan and changed: URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/refresh?deep=1") blah = urllib2.urlopen(URL) RescannedSections.append(SectionName + '(' + Section + ')') rescan_destination = True # rescan destination section if necessary if TriggerRescan and DestinationSection and rescan_destination: URL = ("http://" + Host + ":" + Port + "/library/sections/" + str(DestinationSection) + "/refresh?deep=1") blah = urllib2.urlopen(URL) RescannedSections.append('[destination dir]' + '(' + str(DestinationSection) + ')') print("") print("----------------------------------------------------------------------------") print("----------------------------------------------------------------------------") print(" Summary -- Script Completed Successfully") print("----------------------------------------------------------------------------") print("") print(" Total File Count " + str(FileCount)) print(" Kept Show Files " + str(ShowsCount)) print(" On Deck Files " + str(OnDeckCount)) print(" Deleted Files " + str(DeleteCount)) print(" Moved Files " + str(MoveCount)) print(" Copied Files " + str(CopyCount)) print(" Flagged Files " + str(FlaggedCount)) print(" Rescanned Sections " + ', '.join(str(x) for x in RescannedSections) ) print("") print("----------------------------------------------------------------------------") print("----------------------------------------------------------------------------") input()
更改后文本
打开文件
#!/usr/bin/python # -*- coding: utf-8 -*- #################################################################################### ## INFORMATION #################################################################################### ## Developed by: Steven Johnson (minor modifications by egretsareherons) ## (a minor modifications by aross01) ## (a minor modification by STEEVo) ## ## Last Updated: 02/26/2014 5:05PM MST ## ## Description: Auto-Delete Watched Items In Plex ## ## Required Configurations: ## - PC (Blank = AutoDetect | W = Windows | L = Linux/Unix/MAC) ## - Host (Hostname or IP | Blank = 127.0.0.1) ## - Port (Port | Blank = 32400) ## - SectionList - A list of sections to operate on. If this is blank, the script ## will get a list of all sections from the server & operate on all, except ## for the sections listed in IgnoreSections ## - IgnoreSections - Only used if SectionList is blank. When SectionList is blank, ## the script will operate on all available sections of your install ## except for the ones listed here. ## - Delete (1 = Delete | Blank = 0 (For Testing or Review)) ## - Move (1 = move files to DestinationDir, 0 = don't move) ## - Copy (1 = copy files to DestinationDir, 0 = don't copy) ## - Shows ( ["Show1","Show2"]; = Kept Shows OR [""]; = DEL ALL SHOWS ) ## - OnDeck ( 1 = Keep If On Deck | Blank = Delete Regardless if onDeck ) ## - DestinationDir - the place to move or copy your watched files for later manual deletion ## - DestinationSection - if your destination dir is also a configured section, set the ## number here so TriggerRescan knows to rescan that section when changes are made. ## only used if TriggerRescan is True; ## - TriggerRescan - automatically trigger a deep rescan of changed sections. True or False. ## ## - KeepMode (Blank = Disabled | W = "Watched" | A = "Added") ## Method used to keep items for X number of days (specified by DaysToKeep below.) ## You may choose to base the keep on the last "watched" or "added" date. ## - DaysToKeep ("30" = Keep items for 30 days following the KeepMode selected) ## #################################################################################### #################################################################################### PC = "W" Host = "" Port = "" SectionList = [1,2,7] IgnoreSections = [] Delete = "1" DeleteSimilar = "1" Move = "0" Copy = "0" Shows = [] OnDeck = "1" DestinationDir = "/media/delete" DestinationSection = "" KeepMode = "" DaysToKeep = 14 TriggerRescan = True #Use Username/Password or Token. Username = "" Password = "" # or Token = "" #################################################################################### ## NO NEED TO EDIT BELOW THIS LINE #################################################################################### import os import xml.dom.minidom import platform import re import shutil import datetime import glob import sys try: import urllib.request as urllib2 except: import urllib2 #################################################################################### ## Check On Deck #################################################################################### def CheckOnDeck( CheckDeckFile ): InTheDeck = 0 for DeckVideoNode in deck.getElementsByTagName("Video"): DeckMediaNode = DeckVideoNode.getElementsByTagName("Media") for DeckMedia in DeckMediaNode: DeckPartNode = DeckMedia.getElementsByTagName("Part") for DeckPart in DeckPartNode: Deckfile = DeckPart.getAttribute("file") if CheckDeckFile==Deckfile: InTheDeck += 1 else: InTheDeck += 0 return InTheDeck #################################################################################### ## Check Shows And Delete If Configured #################################################################################### def CheckShows( CheckFile ): global FileCount global DeleteCount global MoveCount global CopyCount global FlaggedCount global OnDeckCount global ShowsCount global DestinationDir FileCount += 1 CantDelete = 0 ShowFound = "" changed = 0 ## -- CHECK SHOWS -- for Show in Shows: Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip() if Show=="": CantDelete = 0 else: if (' ' in Show) == True: if all(str(Word) in CheckFile for Word in Show.split()): CantDelete += 1 ShowFound = "[" + Show + "]" ShowsCount += 1 break else: CantDelete += 0 else: if Show in CheckFile: CantDelete += 1 ShowFound = "[" + Show + "]" ShowsCount += 1 break else: CantDelete += 0 ## -- Check OnDeck -- if OnDeck=="1": IsOnDeck = CheckOnDeck(CheckFile); if IsOnDeck==0: CantDelete += 0 else: CantDelete += 1 ShowFound = "[OnDeck]" + ShowFound OnDeckCount += 1 ## -- Check if video older than days to keep [Viewed method] -- ## and check if the file has been added for that time to keep from deleting reimported files if KeepMode=="W": if (DaysToKeep > DaysSinceVideoLastViewed) or (DaysToKeep > DaysSinceVideoAdded): CantDelete += 1 ShowsCount += 1 # ShowFound = " | Days Since Viewed:" + str(DaysSinceVideoLastViewed) +" |" + ShowFound ## -- Check if video older than days to keep [Added method] -- if KeepMode=="A": if DaysToKeep > DaysSinceVideoAdded: CantDelete += 1 ShowsCount += 1 # ShowFound = " | Days Since Added:" + str(DaysSinceVideoAdded) +" |" + ShowFound ## -- DELETE SHOWS -- if CantDelete == 0: if Delete=="1": #print("**[DELETED] " + CheckFile) if DeleteSimilar=="1": similarFiles = os.path.splitext(CheckFile)[0] + "*" print("Looking for " + similarFiles) for deleteFile in glob.glob(similarFiles): try: os.remove(deleteFile) print("**[DELETED] " + deleteFile) changed = 1 DeleteCount += 1 except Exception as e: print ("error deleting file: %s" % e) else: try: os.remove(os.path.realpath(CheckFile)) print("**[DELETED] " + CheckFile) changed = 1 DeleteCount += 1 except Exception as e: print ("error deleting file: %s" % e) elif Move == "1": try: os.utime(os.path.realpath(CheckFile), None) shutil.move(os.path.realpath(CheckFile), DestinationDir) print("**[MOVED] " + CheckFile) changed = 1 except Exception as e: print ("error moving file: %s" % e) if os.path.islink(CheckFile): os.unlink(CheckFile) MoveCount += 1 elif Copy == "1": try: shutil.copy(os.path.realpath(CheckFile), DestinationDir) changed = 1 except Exception as e: print ("error copying file: %s" % e) print("**[COPIED] " + CheckFile) CopyCount += 1 else: print("**[FLAGGED] " + CheckFile) FlaggedCount += 1 else: print("[KEEPING]") return changed #################################################################################### ## Checking URL #################################################################################### if Host=="": Host="127.0.0.1" if Port=="": Port="32400" #parse arguments if len(sys.argv) > 1: if sys.argv[1].lower() in ("-test", "--test"): print("Running in Test Mode") Delete = 0 Move = 0 Copy = 0 else: print("Invalid Argument! - Use -test or --test for testing") sys.exit(2) login = False #Use Token by default, but if not found then use myPlex Login to get a Token #Modified from dane22 on the PlexForums if Token=="": if not Username=="": import base64 import json encode = base64.encodestring('%s:%s' % (Username,Password)).replace('\n','') URL = ("https://plex.tv/users/sign_in.json") headers= {} headers['X-Plex-Device-Name'] = "Python" headers['X-Plex-Platform'] = platform.system() headers['X-Plex-Device'] = platform.system() headers['X-Plex-Platform-Version'] = platform.release() headers['X-Plex-Provides'] = "Python" headers['X-Plex-Product'] = "Auto Delete Watched" headers['X-Plex-Client-Identifier'] = "10101010101010" headers['X-Plex-Version'] = platform.python_version() headers['Authorization'] = 'Basic ' + encode req = urllib2.Request(URL,"None",headers) #req.get_method = lambda: 'POST' try: Token = json.load(urllib2.urlopen(req))['user']['authentication_token'] except: Token="" #print(Token) login = True print("----------------------------------------------------------------------------") print(" Detected Settings") print("----------------------------------------------------------------------------") print("Host: " + Host) print("Port: " + Port) #print("Section: " + Section) #print("URL: " + URL) #print("OnDeck URL: " + OnDeckURL) if login: print("Logged in as: " + Username) elif not Token=="": print("Using Token for login") else: print("No Login specified") if KeepMode=="W": print("Keep Mode: Keeping for " + str(DaysToKeep) + " days following the date last viewed") elif KeepMode=="A": print("Keep Mode: Keeping viewed items that were added to the library less than " + str(DaysToKeep) + " days ago") else: print("Keep Mode: DISABLED") #################################################################################### ## Checking Shows #################################################################################### NoDelete = " | " ShowCount = len(Shows) print("Show Count: " + str(ShowCount)) for Show in Shows: Show = re.sub('[^A-Za-z0-9 ]+', '', Show).strip() if Show=="": NoDelete += "(None Listed) | " ShowCount -= 1 else: NoDelete += Show + " | " print("Number of Shows Detected For Keeping: " + str(ShowCount)) print ("Shows to Keep:" + NoDelete) ################################################################################### ## Checking Delete #################################################################################### if Delete=="1": print("Delete: ***Enabled***") else: print("Delete: Disabled - Flagging Only") if OnDeck=="1": print("Delete OnDeck: No") else: print("Delete OnDeck: Yes") #################################################################################### ## Checking OS #################################################################################### AD = "" if PC=="": AD = "(Auto Detected)" if platform.system()=="Windows": PC = "W" elif platform.system()=="Linux": PC = "L" elif platform.system()=="Darwin": PC = "L" FileCount = 0 DeleteCount = 0 MoveCount = 0 CopyCount = 0 FlaggedCount = 0 OnDeckCount = 0 ShowsCount = 0 TriggerRescan = False RescannedSections = [] #################################################################################### ## Get list of sections #################################################################################### if PC=="L": print("Operating System: Linux " + AD) #import urllib2 elif PC=="W": print("Operating System: Windows " + AD) #import urllib.request else: print("Operating System: ** Not Configured ** (" + platform.system() + ") is not recognized.") exit() if not SectionList: URL = ("http://" + Host + ":" + Port + "/library/sections/") req = urllib2.Request(URL,None,{"X-Plex-Token":Token}) doc = xml.dom.minidom.parse(urllib2.urlopen(req)) for Section in doc.getElementsByTagName("Directory"): if Section.getAttribute("key") not in IgnoreSections: SectionList.append(Section.getAttribute("key")) SectionList.sort(key=int) print ("Section List Mode: Auto") print ("Operating on sections: " + ','.join(str(x) for x in SectionList)) print ("Skipping Sections: " + ','.join(str(x) for x in IgnoreSections)) else: print ("Section List Mode: User-defined") print ("Operating on user-defined sections: " + ','.join(str(x) for x in SectionList)) #################################################################################### ## Loop on sections #################################################################################### rescan_destination = False for Section in SectionList: Section = str(Section) URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/recentlyViewed") OnDeckURL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/onDeck") #################################################################################### ## Setting OS Based Variables #################################################################################### if PC=="L": req = urllib2.Request(URL,None,{"X-Plex-Token":Token}) doc = xml.dom.minidom.parse(urllib2.urlopen(req)) req = urllib2.Request(OnDeckURL,None,{"X-Plex-Token":Token}) deck = xml.dom.minidom.parse(urllib2.urlopen(req)) elif PC=="W": req = urllib2.Request(URL,None,{"X-Plex-Token":Token}) doc = xml.dom.minidom.parse(urllib.request.urlopen(req)) req = urllib2.Request(OnDeckURL,None,{"X-Plex-Token":Token}) deck = xml.dom.minidom.parse(urllib.request.urlopen(req)) SectionName = doc.getElementsByTagName("MediaContainer")[0].getAttribute("title1") print("") print("--------- Section "+ Section +": " + SectionName + " -----------------------------------") #################################################################################### ## Get Files for Watched Shows #################################################################################### changed = 0 for VideoNode in doc.getElementsByTagName("Video"): view = VideoNode.getAttribute("viewCount") if view == '': view = 0 view = int(view) ################################################################ ###Find number of days between date video was viewed and today lastViewedAt = VideoNode.getAttribute("lastViewedAt") d1 = datetime.datetime.today() d2 = datetime.datetime.fromtimestamp(float(lastViewedAt)) DaysSinceVideoLastViewed = (d1 - d2).days ################################################################ ################################################################ ###Find number of days between date video was added and today addedAt = VideoNode.getAttribute("addedAt") d1 = datetime.datetime.today() da2 = datetime.datetime.fromtimestamp(float(addedAt)) DaysSinceVideoAdded = (d1 - da2).days ################################################################ MediaNode = VideoNode.getElementsByTagName("Media") for Media in MediaNode: PartNode = Media.getElementsByTagName("Part") for Part in PartNode: file = Part.getAttribute("file") #NEW (Removed by Mustang): if sys.version < '3': file = urllib2.unquote(file.encode('utf_8')).decode('utf_8') else: import urllib file = urllib.parse.unquote(file) if str(view)!="0": print(" ") if KeepMode=="W": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) if KeepMode=="A": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Added: " + str(DaysSinceVideoAdded) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) if KeepMode=="": if str(view)!="0": print ("Viewed:" + str(view) + "x | Days Since Viewed: " + str(DaysSinceVideoLastViewed) + " Added: " + str(DaysSinceVideoAdded) + " | " + file) if view > 0: if os.path.isfile(file): changed += CheckShows(file); else: print("##[NOT FOUND] " + file) # rescan this section if necessary if TriggerRescan and changed: URL = ("http://" + Host + ":" + Port + "/library/sections/" + Section + "/refresh?deep=1") #blah = urllib2.urlopen(URL,data) RescannedSections.append(SectionName + '(' + Section + ')') rescan_destination = True # rescan destination section if necessary if TriggerRescan and DestinationSection and rescan_destination: URL = ("http://" + Host + ":" + Port + "/library/sections/" + str(DestinationSection) + "/refresh?deep=1") #blah = urllib2.urlopen(URL,data) RescannedSections.append('[destination dir]' + '(' + str(DestinationSection) + ')') print("") print("----------------------------------------------------------------------------") print("----------------------------------------------------------------------------") print(" Summary -- Script Completed Successfully") print("----------------------------------------------------------------------------") print("") print(" Total File Count " + str(FileCount)) print(" Kept Show Files " + str(ShowsCount)) print(" On Deck Files " + str(OnDeckCount)) print(" Deleted Files " + str(DeleteCount)) print(" Moved Files " + str(MoveCount)) print(" Copied Files " + str(CopyCount)) print(" Flagged Files " + str(FlaggedCount)) if TriggerRescan: print(" Rescanned Sections " + ', '.join(str(x) for x in RescannedSections) ) print("") print("----------------------------------------------------------------------------") print("----------------------------------------------------------------------------") input()
查找差异