Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Plex Cleanup
// Gets the script properties
const script = PropertiesService.getScriptProperties(),
baseURL = script.getProperty("BASE_URL"),
token = script.getProperty("TOKEN"),
webhook = script.getProperty("IFTTT_WEBHOOK"),
section = 4;
// Main constructor method
function constructor() {
let response = UrlFetchApp.fetch(
`${baseURL}/library/sections/${section}/allLeaves`,
{ method: "GET", headers: { "X-Plex-Token": token } }
),
jsonObject = xmlToJson(response.getContentText()),
videoContainer = jsonObject.MediaContainer.Video;
if (videoContainer) {
let watchedVideos = [];
if (Array.isArray(videoContainer)) {
watchedVideos = videoContainer.filter((video) => video.viewCount == 1);
} else {
if (videoContainer.viewCount == 1) watchedVideos.push(videoContainer);
}
if (watchedVideos.length > 0) {
let watchedTitles = "";
watchedVideos.forEach((video, index) => {
Logger.log(video.key);
UrlFetchApp.fetch(baseURL + video.key, {
method: "DELETE",
headers: { "X-Plex-Token": token },
});
watchedTitles += `${video.grandparentTitle} - ${video.title}`;
watchedTitles += "\r\n";
if (index === watchedVideos.length - 1) {
Logger.log(watchedTitles);
Logger.log("Notification sent!");
let notification =
`${watchedVideos.length} watched episodes were removed!` +
"\r\n" +
watchedTitles;
let options = {
method: "POST",
contentType: "application/json",
payload: JSON.stringify({ value1: notification }),
};
UrlFetchApp.fetch(webhook, options);
}
});
}
} else {
Logger.log("No videos to delete!");
}
}
function xmlToJson(xml) {
let doc = XmlService.parse(xml),
result = {},
root = doc.getRootElement();
result[root.getName()] = elementToJson(root);
return result;
}
function elementToJson(element) {
let result = {};
// Attributes.
element.getAttributes().forEach(attribute => {
result[attribute.getName()] = attribute.getValue();
});
// Child elements.
element.getChildren().forEach(child => {
let key = child.getName(),
value = elementToJson(child);
if (result[key]) {
if (!(result[key] instanceof Array)) {
result[key] = [result[key]];
}
result[key].push(value);
} else {
result[key] = value;
}
});
// Text content.
if (element.getText()) {
result['Text'] = element.getText();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.