apollo/services/trackers/plex-tracker.js

61 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-12-04 23:18:35 -05:00
const axios = require("axios");
const Song = require("../../models/song");
class PlexTracker {
2024-12-05 03:26:31 -05:00
#config = null;
#cache = [];
2024-12-04 23:18:35 -05:00
constructor(config) {
2024-12-05 03:26:31 -05:00
this.#config = config;
2024-12-04 23:18:35 -05:00
}
async poll(useCache = false) {
2024-12-05 03:26:31 -05:00
if (!this.#config.token || !this.#config.url)
2024-12-04 23:18:35 -05:00
return [];
if (useCache)
2024-12-05 03:26:31 -05:00
return this.#cache;
2024-12-04 23:18:35 -05:00
2024-12-05 03:26:31 -05:00
const response = await axios.get(this.#config.url + "/status/sessions", {
2024-12-04 23:18:35 -05:00
headers: {
"Accept": "application/json",
2024-12-05 03:26:31 -05:00
"X-Plex-Token": this.#config.token
2024-12-04 23:18:35 -05:00
}
});
if (!response.data.MediaContainer?.Metadata) {
2024-12-05 03:26:31 -05:00
this.#cache = [];
return this.#cache;
2024-12-04 23:18:35 -05:00
}
const filtered = response.data.MediaContainer?.Metadata.filter(m => this.#filter(m));
2024-12-05 03:26:31 -05:00
this.#cache = filtered.map(m => this.#transform(m));
return this.#cache;
2024-12-04 23:18:35 -05:00
}
#filter(data) {
2024-12-05 03:26:31 -05:00
if (!this.#config.filters || this.#config.filters.length == 0)
2024-12-04 23:18:35 -05:00
return true;
2024-12-05 03:26:31 -05:00
for (let filter of this.#config.filters) {
2024-12-04 23:18:35 -05:00
if (filter.library && !filter.library.some(l => l == data.librarySectionTitle))
continue;
if (filter.ip && !filter.ip.some(l => l == data.address))
continue;
if (filter.deviceId && !filter.deviceId.some(l => l == data.machineIdentifier))
continue;
if (filter.platform && !filter.platform.some(l => l == data.Player.platform))
continue;
if (filter.product && !filter.product.some(l => l == data.Player.product))
continue;
return true;
}
return false;
}
#transform(data) {
const id = data.guid.substring(data.guid.lastIndexOf('/') + 1);
return new Song(id, data.title, data.parentTitle, data.grandparentTitle, data.parentYear, data.duration, data.viewOffset, data.sessionKey, data.Player.state, "plex");
}
}
module.exports = PlexTracker;