@jjdenhertog/plex-music-search
Version:
Library to find tracks in your Plex Library
415 lines (414 loc) • 24.6 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlexMusicSearch = void 0;
var music_search_1 = __importStar(require("@jjdenhertog/music-search"));
var getAlbumTracks_1 = __importDefault(require("./actions/getAlbumTracks"));
var getMetadata_1 = require("./actions/getMetadata");
var hubSearchToPlexTrack_1 = __importDefault(require("./utils/searching/hubSearchToPlexTrack"));
var searchForAlbum_1 = require("./utils/searching/searchForAlbum");
var searchForAlbumTracks_1 = require("./utils/searching/searchForAlbumTracks");
var searchForTrack_1 = require("./utils/searching/searchForTrack");
var searchResultToTracks_1 = __importDefault(require("./utils/searching/searchResultToTracks"));
var PlexMusicSearch = /** @class */ (function () {
function PlexMusicSearch(config) {
this._cache = [];
this._config = config;
}
PlexMusicSearch.prototype.search = function (tracks) {
return __awaiter(this, void 0, void 0, function () {
var _a, approaches, musicSearch, result, i, trackResult;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = this._config.searchApproaches, approaches = _a === void 0 ? [
{ id: 'normal', filtered: false, trim: false },
{ id: 'filtered', filtered: true, trim: false, removeQuotes: true },
{ id: 'trimmed', filtered: false, trim: true },
{ id: 'filtered_trimmed', filtered: true, trim: true, removeQuotes: true }
] : _a;
musicSearch = music_search_1.default.getInstance();
musicSearch.config = this._config;
// Reset cache
this._cache = [];
result = [];
i = 0;
_b.label = 1;
case 1:
if (!(i < tracks.length)) return [3 /*break*/, 4];
return [4 /*yield*/, this._newTrackSearch(approaches, tracks[i], false)];
case 2:
trackResult = _b.sent();
result.push(trackResult);
_b.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, result];
}
});
});
};
PlexMusicSearch.prototype.analyze = function (track) {
return __awaiter(this, void 0, void 0, function () {
var _a, approaches, musicSearch;
return __generator(this, function (_b) {
_a = this._config.searchApproaches, approaches = _a === void 0 ? [
{ id: 'normal', filtered: false, trim: false },
{ id: 'filtered', filtered: true, trim: false, removeQuotes: true },
{ id: 'trimmed', filtered: false, trim: true },
{ id: 'filtered_trimmed', filtered: true, trim: true, removeQuotes: true }
] : _a;
// Reset cache
this._cache = [];
musicSearch = music_search_1.default.getInstance();
musicSearch.config = this._config;
return [2 /*return*/, this._newTrackSearch(approaches, track, true)];
});
});
};
PlexMusicSearch.prototype.searchAlbum = function (tracks) {
return __awaiter(this, void 0, void 0, function () {
var firstValidAlbum, album, artists, musicSearch, getMusicSearchResult, _loop_1, this_1, j, state_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
firstValidAlbum = tracks.find(function (item) { return !!item.album; });
if (!firstValidAlbum)
return [2 /*return*/, tracks.map(function (item) { return ({ id: item.id, title: item.title, artist: item.artists[0], album: item.album || "", result: [] }); })];
album = firstValidAlbum.album, artists = firstValidAlbum.artists;
if (!album)
return [2 /*return*/, tracks.map(function (item) { return ({ id: item.id, title: item.title, artist: item.artists[0], album: item.album || "", result: [] }); })
// Initialize music search with config
];
musicSearch = music_search_1.default.getInstance();
getMusicSearchResult = function (find, tracks) {
var id = find.id, title = find.title, album = find.album;
for (var i = 0; i < find.artists.length; i++) {
var artist = find.artists[i];
var result = musicSearch.search({ id: id, title: title, album: album, artist: artist }, tracks);
if (result.length > 0)
return result;
}
return [];
};
_loop_1 = function (j) {
var artist, foundAlbums, album_1, albumTracks_1, _e_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
artist = artists[j];
_b.label = 1;
case 1:
_b.trys.push([1, 5, , 6]);
return [4 /*yield*/, (0, searchForAlbum_1.searchForAlbum)(this_1._config.uri, this_1._config.token, artist, album)];
case 2:
foundAlbums = _b.sent();
if (!(foundAlbums.length > 0)) return [3 /*break*/, 4];
album_1 = foundAlbums[0];
return [4 /*yield*/, (0, getAlbumTracks_1.default)(this_1._config.uri, this_1._config.token, album_1.id)];
case 3:
albumTracks_1 = _b.sent();
return [2 /*return*/, { value: tracks.map(function (item) {
var result = getMusicSearchResult(item, (0, searchResultToTracks_1.default)(albumTracks_1));
var plexTracks = result
.map(function (item) { return albumTracks_1
.find(function (track) { return track.id == item.id; }); })
.filter(function (item) { return !!item; })
.map(function (item) { return (0, hubSearchToPlexTrack_1.default)(item); });
return __assign(__assign({}, item), { artist: artists[0], album: album_1.title, result: plexTracks });
}) }];
case 4: return [3 /*break*/, 6];
case 5:
_e_1 = _b.sent();
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
};
this_1 = this;
j = 0;
_a.label = 1;
case 1:
if (!(j < artists.length)) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1(j)];
case 2:
state_1 = _a.sent();
if (typeof state_1 === "object")
return [2 /*return*/, state_1.value];
_a.label = 3;
case 3:
j++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, tracks.map(function (item) { return ({ id: item.id, title: item.title, artist: item.artists[0], album: item.album || "", result: [] }); })];
}
});
});
};
PlexMusicSearch.prototype.getMetaData = function (key) {
return (0, getMetadata_1.getMetadata)(this._config.uri, this._config.token, key);
};
PlexMusicSearch.prototype.getById = function (key) {
return __awaiter(this, void 0, void 0, function () {
var metaData, item, src;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, getMetadata_1.getMetadata)(this._config.uri, this._config.token, key)];
case 1:
metaData = _a.sent();
item = metaData[0];
src = '';
try {
src = item.Media[0].Part[0].file;
}
catch (_e) {
}
return [2 /*return*/, {
id: item.key,
guid: item.guid,
image: item.thumb,
title: item.title,
src: src,
album: {
guid: item.parentGuid,
id: item.parentKey,
title: item.parentTitle,
image: item.parentThumb,
},
artist: {
guid: item.grandparentGuid,
id: item.grandparentKey,
title: (0, music_search_1.removeFeaturing)(item.originalTitle || item.grandparentTitle),
image: item.grandparentThumb,
}
}];
}
});
});
};
PlexMusicSearch.prototype._newTrackSearch = function (approaches, searchTrack, includeMatching) {
return __awaiter(this, void 0, void 0, function () {
var id, artists, title, album, queries, j, artist, result, _e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
id = searchTrack.id, artists = searchTrack.artists, title = searchTrack.title, album = searchTrack.album;
queries = [];
j = 0;
_a.label = 1;
case 1:
if (!(j < artists.length)) return [3 /*break*/, 6];
artist = artists[j];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, this._findTrack(approaches, { id: id, artist: artist, title: title, album: album }, includeMatching)];
case 3:
result = _a.sent();
queries = queries.concat(result.queries);
if (result && result.result.length > 0)
return [2 /*return*/, result];
return [3 /*break*/, 5];
case 4:
_e_2 = _a.sent();
return [3 /*break*/, 5];
case 5:
j++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/, { id: id, artist: artists[0], title: title, album: album || "", queries: queries, result: [] }];
}
});
});
};
PlexMusicSearch.prototype._findTrack = function (approaches, find, includeMatching) {
return __awaiter(this, void 0, void 0, function () {
var searchResult, id, artist, title, _a, album, queries, musicSearch, performSearch, searchApproachIndex, approach, approachId, trim, filtered, removeQuotes, searchArtist, searchAlbum, searchTrack, altSearchArtist, altSearchTrack, _e_3;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
searchResult = [];
id = find.id, artist = find.artist, title = find.title, _a = find.album, album = _a === void 0 ? '' : _a;
queries = [];
musicSearch = music_search_1.default.getInstance();
performSearch = function (approach_1, artist_1, title_1, album_2) {
var args_1 = [];
for (var _i = 4; _i < arguments.length; _i++) {
args_1[_i - 4] = arguments[_i];
}
return __awaiter(_this, __spreadArray([approach_1, artist_1, title_1, album_2], args_1, true), void 0, function (approach, artist, title, album, searchAlbumTracks) {
var cacheId, foundCache, searchHandler, searchResults, musicSearchResult, plexTracks, approachId;
if (searchAlbumTracks === void 0) { searchAlbumTracks = false; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cacheId = "".concat(searchAlbumTracks ? 'album-' : '').concat(artist, "-").concat(title, "-").concat(album);
foundCache = this._cache.find(function (item) { return item.id == cacheId; });
if (foundCache)
return [2 /*return*/, foundCache.result];
searchHandler = searchAlbumTracks ? searchForAlbumTracks_1.searchForAlbumTracks : searchForTrack_1.searchForTrack;
return [4 /*yield*/, searchHandler(this._config.uri, this._config.token, artist, title, album)];
case 1:
searchResults = _a.sent();
musicSearchResult = musicSearch.search(find, (0, searchResultToTracks_1.default)(searchResults), includeMatching);
plexTracks = musicSearchResult
.map(function (item) {
var searchResult = searchResults.find(function (track) { return track.id == item.id; });
if (!searchResult)
return null;
return __assign(__assign({}, searchResult), { reason: item.reason, matching: item.matching });
})
.filter(function (item) { return !!item; })
.map(function (item) { return (__assign(__assign({}, (0, hubSearchToPlexTrack_1.default)(item)), { matching: item.matching, reason: item.reason })); });
this._cache.push({ id: cacheId, result: plexTracks });
approachId = searchAlbumTracks ? "".concat(approach, "-album") : approach;
queries.push({ approach: approachId, artist: artist, title: title, album: album });
return [2 /*return*/, plexTracks];
}
});
});
};
searchApproachIndex = 0;
_b.label = 1;
case 1:
if (!approaches[searchApproachIndex]) return [3 /*break*/, 10];
approach = approaches[searchApproachIndex];
if (searchResult.length > 0) {
searchApproachIndex++;
return [3 /*break*/, 1];
}
approachId = approach.id, trim = approach.trim, filtered = approach.filtered, removeQuotes = approach.ignoreQuotes;
searchArtist = (0, music_search_1.filterOutWords)(artist.toLowerCase(), filtered, trim, removeQuotes);
searchAlbum = (0, music_search_1.filterOutWords)(album.toLowerCase(), filtered, trim, removeQuotes);
searchTrack = (0, music_search_1.filterOutWords)(title.toLowerCase(), filtered, trim, removeQuotes);
_b.label = 2;
case 2:
_b.trys.push([2, 8, , 9]);
return [4 /*yield*/, performSearch(approachId, searchArtist, searchTrack, searchAlbum)
////////////////////////////////////////
// Rewrite "&"" to "and"
////////////////////////////////////////
];
case 3:
// Find and cache result
searchResult = _b.sent();
if (!(searchResult.length == 0 && (searchArtist.indexOf("&") || searchTrack.indexOf("&") > -1))) return [3 /*break*/, 5];
altSearchArtist = searchArtist.split('&').join('and');
altSearchTrack = searchTrack.split('&').join('and');
return [4 /*yield*/, performSearch(approachId, altSearchArtist, altSearchTrack, searchAlbum)];
case 4:
searchResult = _b.sent();
_b.label = 5;
case 5:
if (!(searchResult.length == 0)) return [3 /*break*/, 7];
return [4 /*yield*/, performSearch(approachId, searchArtist, searchTrack, searchAlbum, true)];
case 6:
searchResult = _b.sent();
_b.label = 7;
case 7: return [3 /*break*/, 9];
case 8:
_e_3 = _b.sent();
return [3 /*break*/, 9];
case 9:
searchApproachIndex++;
return [3 /*break*/, 1];
case 10: return [2 /*return*/, {
id: id,
artist: artist,
album: album,
title: title,
queries: queries,
result: searchResult
}];
}
});
});
};
return PlexMusicSearch;
}());
exports.PlexMusicSearch = PlexMusicSearch;
__exportStar(require("./types"), exports);