not ready for the BS that is typescript

This commit is contained in:
luke-hagar-sp
2022-07-26 18:53:58 -05:00
parent 08aaaf87ae
commit 533aa20ff8
6 changed files with 1354 additions and 382 deletions

1329
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,10 +2,10 @@
"name": "plex-api-oauth",
"version": "1.0.128",
"description": "An NPM Module designed to make Plex Media Server and plex.tv API calls easier to implement in JavaScript and React projects",
"main": "index.mjs",
"main": "index.mts",
"type": "module",
"scripts": {
"test": "mocha index.test.js"
"test": "mocha ./test/index.test.js"
},
"author": "Luke Hagar",
"license": "MIT",
@@ -13,9 +13,15 @@
"axios": "^0.27.2",
"plex-oauth": "^2.0.2",
"qs": "^6.11.0",
"ts-mocha": "^10.0.0",
"typescript": "^4.7.4",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/expect": "^24.3.0",
"@types/mocha": "^9.1.1",
"@types/qs": "^6.9.7",
"@types/uuid": "^8.3.4",
"mocha": "^10.0.0",
"request": "^2.88.2"
}

View File

@@ -2,18 +2,32 @@ import { PlexOauth } from "plex-oauth";
import { v4 } from "uuid";
import axios from "axios";
import qs from "qs";
export class PlexAPIOAuth {
plexClientInformation;
clientId;
product;
device;
version;
forwardUrl;
platform;
plexTVAuthToken;
plexTVUserData;
plexServers;
selectedPlexServer;
plexDevices;
constructor(
clientId,
clientId = "",
product = "Plex-API-OAuth",
device = "Web-Client",
version = "1",
forwardUrl = "",
platform = "Web",
plexTVAuthToken,
plexTVUserData,
plexTVAuthToken = "",
plexTVUserData = {},
plexServers = [],
plexDevices = []
plexDevices = [],
selectedPlexServer = {}
) {
this.clientId = clientId;
this.product = product;
@@ -26,9 +40,10 @@ export class PlexAPIOAuth {
this.plexTVUserData = plexTVUserData;
this.plexServers = plexServers;
this.plexDevices = plexDevices;
this.selectedPlexServer = selectedPlexServer;
this.plexClientInformation = {
clientId: this.clientId, // This is a unique identifier used to identify your app with Plex. - If none is provided a new one is generated and saved locally
clientIdentifier: this.clientId, // This is a unique identifier used to identify your app with Plex. - If none is provided a new one is generated and saved locally
product: this.product, // Name of your application - Defaults to Plex-API-OAuth
device: this.device, // The type of device your application is running on - Defaults to "Web Client"
version: this.version, // Version of your application - Defaults to 1
@@ -38,21 +53,20 @@ export class PlexAPIOAuth {
}
SetPlexSession({
clientId,
clientId = "",
product = "Plex-API-OAuth",
device = "Web-Client",
version = "1",
forwardUrl = "",
platform = "Web",
plexTVAuthToken,
plexTVUserData,
plexTVAuthToken = "",
plexTVUserData = {},
plexServers = [],
plexDevices = [],
selectedPlexServer,
selectedPlexServer = {},
}) {
this.plexTVAuthToken = plexTVAuthToken;
this.plexTVUserData = plexTVUserData;
this.selectedPlexServer = selectedPlexServer;
this.clientId = clientId;
this.product = product;
this.device = device;
@@ -61,9 +75,10 @@ export class PlexAPIOAuth {
this.platform = platform;
this.plexServers = plexServers;
this.plexDevices = plexDevices;
this.selectedPlexServer = selectedPlexServer;
this.plexClientInformation = {
clientId: this.clientId, // This is a unique identifier used to identify your app with Plex. - If none is provided a new one is generated and saved locally
clientIdentifier: this.clientId, // This is a unique identifier used to identify your app with Plex. - If none is provided a new one is generated and saved locally
product: this.product, // Name of your application - Defaults to Plex-API-OAuth
device: this.device, // The type of device your application is running on - Defaults to "Web Client"
version: this.version, // Version of your application - Defaults to 1
@@ -74,10 +89,9 @@ export class PlexAPIOAuth {
SavePlexSession() {
console.log("Saving State:");
console.log({
let sessionData = {
plexTVAuthToken: this.plexTVAuthToken,
plexTVUserData: this.plexTVUserData,
selectedPlexServer: this.selectedPlexServer,
clientId: this.clientId,
product: this.product,
device: this.device,
@@ -86,50 +100,32 @@ export class PlexAPIOAuth {
platform: this.platform,
plexServers: this.plexServers,
plexDevices: this.plexDevices,
selectedPlexServer: this.selectedPlexServer,
plexClientInformation: this.plexClientInformation,
});
window.localStorage.setItem(
"plexSessionData",
JSON.stringify({
plexTVAuthToken: this.plexTVAuthToken,
plexTVUserData: this.plexTVUserData,
selectedPlexServer: this.selectedPlexServer,
clientId: this.clientId,
product: this.product,
device: this.device,
version: this.version,
forwardUrl: this.forwardUrl,
platform: this.platform,
plexServers: this.plexServers,
plexDevices: this.plexDevices,
plexLibraries: this.plexLibraries,
plexMovieLibraries: this.plexMovieLibraries,
plexMusicLibraries: this.plexMusicLibraries,
plexTVShowLibraries: this.plexTVShowLibraries,
plexMovies: this.plexMovies,
plexMusic: this.plexMusic,
plexTVShows: this.plexTVShows,
plexClientInformation: this.plexClientInformation,
})
);
};
console.log(sessionData);
window.localStorage.setItem("plexSessionData", JSON.stringify(sessionData));
}
LoadPlexSession() {
console.log("Loading State:");
this.SetPlexSession(
JSON.parse(window.localStorage.getItem("plexSessionData"))
let sessionData = JSON.parse(
window.localStorage?.getItem("plexSessionData") || "{}"
);
console.log(JSON.parse(window.localStorage.getItem("plexSessionData")));
this.SetPlexSession(sessionData);
console.log(sessionData);
}
GenerateClientId() {
this.clientId = v4();
this.plexClientInformation.clientId = this.clientId;
console.log("Generated ClientId");
this.plexClientInformation.clientIdentifier = this.clientId;
}
async PlexLogin() {
if (this.ClientId === null || this.clientId === undefined) {
if (
this.clientId == null ||
this.plexClientInformation.clientIdentifier == null
) {
this.GenerateClientId();
}
var plexOauth = new PlexOauth(this.plexClientInformation);
@@ -141,11 +137,11 @@ export class PlexAPIOAuth {
console.log("Plex Auth URL:");
console.log(hostedUILink); // UI URL used to log into Plex
console.log("Plex Pin ID:");
console.log(pinId);
window.open(hostedUILink, "_blank");
window.focus();
if (typeof window !== "undefined") {
window.open(hostedUILink, "_blank");
window.focus();
}
/*
* You can now navigate the user's browser to the 'hostedUILink'. This will include the forward URL
@@ -168,7 +164,7 @@ export class PlexAPIOAuth {
return authToken;
} else {
console.log("Plex Authentication Failed");
return null;
return authToken;
}
// An auth token will only be null if the user never signs into the hosted UI, or you stop checking for a new one before they can log in
}
@@ -180,7 +176,8 @@ export class PlexAPIOAuth {
"https://plex.tv/api/v2/user?" +
qs.stringify({
"X-Plex-Product": this.plexClientInformation.product,
"X-Plex-Client-Identifier": this.plexClientInformation.clientId,
"X-Plex-Client-Identifier":
this.plexClientInformation.clientIdentifier,
"X-Plex-Token": this.plexTVAuthToken,
}),
headers: { accept: "application/json" },
@@ -203,16 +200,16 @@ export class PlexAPIOAuth {
console.log(error.config);
});
console.log(response);
console.log(response.status);
//console.log(response);
//console.log(response.status);
if (response.status === 200) {
console.log("Authentican Token Validated Successfully");
//console.log("Authentican Token Validated Successfully");
this.plexTVUserData = response.data;
console.log("Populated User Data Successfully");
//console.log("Populated User Data Successfully");
return response.data;
}
if (response.status === 401) {
console.log("Authentican Token Failed Validation");
//console.log("Authentican Token Failed Validation");
return null;
}
}
@@ -227,121 +224,50 @@ export class PlexAPIOAuth {
includeRelay: 1,
includeIPv6: 1,
"X-Plex-Product": this.plexClientInformation.product,
"X-Plex-Client-Identifier": this.plexClientInformation.clientId,
"X-Plex-Client-Identifier":
this.plexClientInformation.clientIdentifier,
"X-Plex-Token": this.plexTVAuthToken,
}),
headers: { accept: "application/json" },
}).catch((err) => {
throw err;
});
console.log("Plex Devices:");
console.log(response);
this.plexDevices = response.data;
this.plexServers = response.data
?.filter((obj) => obj?.product?.includes("Plex Media Server"))
?.map((obj) => {
return {
accessToken: obj?.accessToken,
clientIdentifier: obj?.clientIdentifier,
connections: obj?.connections,
localConnections: obj?.connections?.filter(
(obj) => obj?.local == true
),
relayConnections: obj?.connections?.filter(
(obj) => obj?.relay == true
),
createdAt: obj?.createdAt,
device: obj?.device,
dnsRebindingProtection: obj?.dnsRebindingProtection,
home: obj?.home,
httpsRequired: obj?.httpsRequired,
lastSeenAt: obj?.lastSeenAt,
libraries: [],
name: obj?.name,
natLoopbackSupported: obj?.natLoopbackSupported,
owned: obj?.owned,
ownerId: obj?.ownerId,
platform: obj?.platform,
platformVersion: obj?.platformVersion,
presence: obj?.presence,
product: obj?.product,
productVersion: obj?.productVersion,
provides: obj?.provides,
publicAddress: obj?.publicAddress,
publicAddressMatches: obj?.publicAddressMatches,
relay: obj?.relay,
sourceTitle: obj?.sourceTitle,
synced: obj?.accessTokensynced,
};
});
this.plexServers = response.data;
return response.data;
}
async GetPlexLibraries() {
this.plexServers?.forEach(async (server) => {
let response = await axios({
method: "GET",
url:
server?.relayConnections[0].uri +
"/library/sections/?" +
qs.stringify({
"X-Plex-Token": server?.accessToken,
}),
headers: { accept: "application/json" },
}).catch((err) => {
throw err;
});
// async GetPlexLibraries(server) {
// let response = await axios({
// method: "GET",
// url:
// server.relayConnections[0].uri +
// "/library/sections/?" +
// qs.stringify({
// "X-Plex-Token": server.accessToken,
// }),
// headers: { accept: "application/json" },
// }).catch((err) => {
// throw err;
// });
// return response?.data?.MediaContainer?.Directory;
// }
let plexLibraries = response?.data?.MediaContainer?.Directory;
let plexMusicLibraries =
response?.data?.MediaContainer?.Directory?.filter(
(obj) => obj.type === "artist"
);
let plexMovieLibraries =
response?.data?.MediaContainer?.Directory?.filter(
(obj) => obj.type === "movie"
);
let plexTVShowLibraries =
response?.data?.MediaContainer?.Directory?.filter(
(obj) => obj.type === "show"
);
console.log(this.plexServers[server]);
server.libraries = {
plexLibraries: plexLibraries,
plexMusicLibraries: plexMusicLibraries,
plexMovieLibraries: plexMovieLibraries,
plexTVShowLibraries: plexTVShowLibraries,
};
console.log(server);
this.plexServers[server] = server;
});
}
async GetPlexLibraryContent() {
this.plexServers?.forEach(async (server) => {
await server?.plexLibraries?.forEach(async (library) => {
let response = await axios({
method: "GET",
url:
server?.relayConnections[0].uri +
"/library/sections/" +
library.uuid +
"?" +
qs.stringify({
"X-Plex-Token": server?.accessToken,
}),
headers: { accept: "application/json" },
}).catch((err) => {
throw err;
});
console.log(response);
});
});
return true;
// this.plexMusic = response?.data?.MediaContainer?.Directory;
// console.log(this.plexLibraries);
}
// async PopulateLibraryContent(server: PlexServer, library: PlexLibrary) {
// let response = await axios({
// method: "GET",
// url:
// server?.relayConnections[0].uri +
// "/library/sections/" +
// library?.uuid +
// "?" +
// qs.stringify({
// "X-Plex-Token": server?.accessToken,
// }),
// headers: { accept: "application/json" },
// }).catch((err) => {
// throw err;
// });
// console.log(response.data);
// return response.data;
// }
}

1
src/index.js Normal file
View File

@@ -0,0 +1 @@
export { PlexAPIOAuth } from "./PlexAPIOAuth/PlexAPIOAuth.js";

View File

@@ -1,12 +1,41 @@
import { PlexAPIOAuth, PlexLogin } from "./index.mjs";
import { PlexAPIOAuth } from "../src/index.js";
import { strict as assert } from "assert";
describe("Login Test", function () {
let plexapioauth = new PlexAPIOAuth();
it("should be able to fail login", function () {
console.log(plexapioauth);
plexapioauth.generateClientId();
console.log(plexapioauth);
assert.strictEqual(PlexLogin(plexapioauth.plexClientInformation), null);
let PlexSession = new PlexAPIOAuth();
let emptyArray = [];
it("Generate ClientId", function () {
PlexSession.GenerateClientId();
assert.notEqual(PlexSession.clientId, null);
assert.notEqual(PlexSession.clientId, undefined);
console.log("Plex Session");
console.log(PlexSession);
});
it("Login", async function () {
this.timeout(10000);
let response = await PlexSession.PlexLogin();
assert.notEqual(PlexSession.plexTVAuthToken, undefined);
assert.notEqual(response, undefined);
console.log("Auth Token");
console.log(PlexSession.plexTVAuthToken);
});
it("Get Plex User Data", async function () {
this.timeout(5000);
let response = await PlexSession.GetPlexUserData();
assert.notEqual(PlexSession.plexTVUserData, undefined);
assert.notEqual(response, undefined);
console.log("User Data");
console.log(PlexSession.plexTVUserData);
});
it("Get Plex Servers", async function () {
this.timeout(10000);
let response = await PlexSession.GetPlexServers();
assert.notEqual(PlexSession.plexServers, emptyArray);
assert.notEqual(PlexSession.plexServers, null);
assert.notEqual(PlexSession.plexServers, undefined);
assert.notEqual(PlexSession.plexDevices, emptyArray);
assert.notEqual(response, null);
console.log("Plex Servers");
console.log(PlexSession.plexServers);
});
});

103
tsconfig.json Normal file
View File

@@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}