Skip to content

Commit

Permalink
fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
hermanho committed Jan 14, 2024
1 parent 0e1e63a commit 4267f47
Show file tree
Hide file tree
Showing 11 changed files with 146 additions and 731 deletions.
13 changes: 8 additions & 5 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
"root": true,
"extends": [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:jsdoc/recommended"
"plugin:jsdoc/recommended",
"plugin:jsdoc/recommended-typescript-flavor"
],
"plugins": [
"prettier",
"jsdoc",
"jest"
],
Expand All @@ -31,10 +30,14 @@
}
},
"rules": {
"prettier/prettier": [
"comma-dangle": [
"error",
{
"endOfLine": "auto"
"arrays": "always-multiline",
"objects": "always-multiline",
"imports": "always-multiline",
"exports": "always-multiline",
"functions": "only-multiline"
}
],
"eqeqeq": "error",
Expand Down
4 changes: 0 additions & 4 deletions .prettierignore

This file was deleted.

9 changes: 5 additions & 4 deletions MMM-OneDrive.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ Module.register("MMM-OneDrive", {
minHeight: null, // Or 400
maxHeight: null, // Or 8000
minWHRatio: null,
maxWHRatio: null
maxWHRatio: null,
// WHRatio = Width/Height ratio ( ==1 : Squared Photo, < 1 : Portraited Photo, > 1 : Landscaped Photo)
},
showWidth: 1080, // These values will be used for quality of downloaded photos to show. real size to show in your MagicMirror region is recommended.
showHeight: 1920,
timeFormat: "YYYY/MM/DD HH:mm",
autoInfoPosition: false
autoInfoPosition: false,
},
requiresVersion: "2.24.0",

suspended: false,

Expand Down Expand Up @@ -169,7 +170,7 @@ Module.register("MMM-OneDrive", {
[0, "none", "none", 0],
["none", "none", 0, 0],
["none", 0, 0, "none"],
[0, 0, "none", "none"]
[0, 0, "none", "none"],
];
return r[q];
};
Expand Down Expand Up @@ -233,5 +234,5 @@ Module.register("MMM-OneDrive", {

resume() {
this.suspended = false;
}
},
});
39 changes: 19 additions & 20 deletions OneDrivePhotos.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const moment = require("moment");
const { Client } = require('@microsoft/microsoft-graph-client');
const { LogLevel } = require("@azure/msal-node");
const path = require("path");
const { randomUUID } = require('crypto');
const { error_to_string } = require("./error_to_string");
const { msalConfig, protectedResources } = require("./msal/authConfig");
const AuthProvider = require("./msal/AuthProvider");
Expand Down Expand Up @@ -47,7 +46,7 @@ class Auth extends EventEmitter {
// console.log("[ONEDRIVE:CORE] AuthProvider login done");
}

get AuthProvider() { return this.#authProvider };
get AuthProvider() { return this.#authProvider; }
// get AccountInfo() { return this.#msalAccount };
}

Expand Down Expand Up @@ -80,10 +79,10 @@ class OneDrivePhotos {
const auth = new Auth(this.debug);
return new Promise((resolve, reject) => {
auth.on("ready", async () => {
console.log("onAuthReady ready")
console.log("onAuthReady ready");
const authProvider = auth.AuthProvider;
const tokenRequest = {
scopes: protectedResources.graphMe.scopes
scopes: protectedResources.graphMe.scopes,
};
const tokenResponse = await authProvider.getToken(tokenRequest);
this.#graphClient = Client.init({
Expand All @@ -93,7 +92,7 @@ class OneDrivePhotos {
});
const graphResponse = await this.#graphClient.api(protectedResources.graphMe.endpoint).get();
this.#userId = graphResponse.id;
console.log("onAuthReady done")
console.log("onAuthReady done");
resolve();
});
auth.on("error", (error) => {
Expand Down Expand Up @@ -129,8 +128,8 @@ class OneDrivePhotos {
let found = 0;
/**
*
* @param {String} pageUrl
* @returns {import("@microsoft/microsoft-graph-types").DriveItem[]}
* @param {string} pageUrl
* @returns {import("@microsoft/microsoft-graph-types").DriveItem[]} DriveItem
*/
const getAlbum = async (pageUrl) => {
this.log("Getting Album info chunks.");
Expand Down Expand Up @@ -159,7 +158,7 @@ class OneDrivePhotos {
}

async getAlbumThumbnail(album) {
const thumbnailUrl = protectedResources.getThumbnail.endpoint.replace("$$drive-id$$", album.parentReference.driveId).replace('$$item-id$$', album.id) + "?select=mediumSquare"
const thumbnailUrl = protectedResources.getThumbnail.endpoint.replace("$$drive-id$$", album.parentReference.driveId).replace('$$item-id$$', album.id) + "?select=mediumSquare";
let response2 = await this.request(thumbnailUrl, "get");
if (Array.isArray(response2.value) && response2.value.length > 0) {
const thumbnail = response2.value[0];
Expand All @@ -177,8 +176,8 @@ class OneDrivePhotos {
let list = [];
/**
*
* @param {String} pageUrl
* @returns {Promise<OneDriveMediaItem[]>}
* @param {string} pageUrl
* @returns {Promise<OneDriveMediaItem[]>} DriveItem
*/
const getImage = async (pageUrl) => {
this.log("Indexing photos now. total: ", list.length);
Expand All @@ -198,7 +197,7 @@ class OneDrivePhotos {
filename: item.name,
mediaMetadata: {},
parentReference: item.parentReference,
}
};
if (list.length < maxNum) {
if (item.image) {
itemVal.mediaMetadata.creationTime = item.fileSystemInfo?.createdDateTime;
Expand All @@ -213,13 +212,13 @@ class OneDrivePhotos {
apertureFNumber: item.photo.fNumber,
isoEquivalent: item.photo.iso,
exposureTime: (item.photo.exposureNumerator * 1.0 / item.photo.exposureDenominator).toFixed(2) + 's',
}
};
}
if (item.video) {
itemVal.mediaMetadata.creationTime = item.fileSystemInfo?.createdDateTime;
itemVal.mediaMetadata.width = item.video.width;
itemVal.mediaMetadata.height = item.video.height;
itemVal.mediaMetadata.video = item.video
itemVal.mediaMetadata.video = item.video;
}
if (typeof isValid === "function") {
if (isValid(itemVal)) list.push(itemVal);
Expand Down Expand Up @@ -253,11 +252,11 @@ class OneDrivePhotos {
/**
*
* @param {OneDriveMediaItem[]} items
* @param {String} cachePath
* @returns
* @param {string} cachePath
* @returns items
*/
async updateTheseMediaItems(items, cachePath) {
console.log("updateTheseMediaItems updateTheseMediaItems updateTheseMediaItems")
console.log("updateTheseMediaItems updateTheseMediaItems updateTheseMediaItems");
if (items.length <= 0) {
return [];
}
Expand All @@ -273,11 +272,11 @@ class OneDrivePhotos {
const requestsValue = grp.filter(i => i.item?.parentReference).map((item, i) => ({
id: i,
method: "GET",
url: protectedResources.getItem.endpoint.replace("$$drive-id$$", item.parentReference.driveId).replace('$$item-id$$', item.id)
}))
url: protectedResources.getItem.endpoint.replace("$$drive-id$$", item.parentReference.driveId).replace('$$item-id$$', item.id),
}));
if (requestsValue.length > 0) {
const requestsPayload = {
"requests": requestsValue
"requests": requestsValue,
};
const response = await this.request(protectedResources.$batch.endpoint, "post", requestsPayload);
for (let r of response.response) {
Expand All @@ -288,7 +287,7 @@ class OneDrivePhotos {
}
}

const heicPhotos = items.filter(i => i.mimeType == "image/heic");
const heicPhotos = items.filter(i => i.mimeType === "image/heic");
for (let photo of heicPhotos) {
const buf = await convertHEIC(photo.baseUrl);
const cacheFilename = encodeURI(path.join(cachePath, photo.id + "-convert.jpg"));
Expand Down
8 changes: 4 additions & 4 deletions PhotosConverter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ const convert = require('heic-convert');

/**
*
* @param {String} url
* @param {string} url
*/
const convertHEIC = async (url) => {
const resp = await fetch(url);
const inputBuffer = Buffer.from(await resp.arrayBuffer());
const outputBuffer = await convert({
buffer: inputBuffer, // the HEIC file buffer
format: 'JPEG', // output format
quality: 0.8 // the jpeg compression quality, between 0 and 1
quality: 0.8, // the jpeg compression quality, between 0 and 1
});
return Buffer.from(outputBuffer);
}
};

module.exports = { convertHEIC }
module.exports = { convertHEIC };
48 changes: 22 additions & 26 deletions msal/AuthProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
* Licensed under the MIT License.
*/

const { PublicClientApplication, InteractionRequiredAuthError, ServerError } = require('@azure/msal-node');
const { shell } = require('electron');
const { PublicClientApplication, InteractionRequiredAuthError, ServerError } = require("@azure/msal-node");
const { shell } = require("electron");

class AuthProvider {
msalConfig
msalConfig;
clientApplication;
/** @type {import("@azure/msal-node").AccountInfo} */
account;
Expand Down Expand Up @@ -44,7 +44,7 @@ class AuthProvider {
* the optional token claim 'login_hint' for this to work as expected. For more information, visit:
* https://learn.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request
*/
if (this.account.idTokenClaims.hasOwnProperty('login_hint')) {
if (this.account.idTokenClaims.hasOwnProperty("login_hint")) {
await shell.openExternal(`${this.msalConfig.auth.authority}/oauth2/v2.0/logout?logout_hint=${encodeURIComponent(this.account.idTokenClaims.login_hint)}`);
}

Expand Down Expand Up @@ -74,11 +74,11 @@ class AuthProvider {
return await this.clientApplication.acquireTokenSilent(tokenRequest);
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
console.log('Silent token acquisition failed, acquiring token interactive');
console.log("Silent token acquisition failed, acquiring token interactive");
return await this.getTokenInteractive(tokenRequest);
}
if (error instanceof ServerError && error.errorCode == 'invalid_grant') {
console.log('Silent token acquisition failed, acquiring token interactive');
if (error instanceof ServerError && error.errorCode === "invalid_grant") {
console.log("Silent token acquisition failed, acquiring token interactive");
return await this.getTokenInteractive(tokenRequest);
}

Expand All @@ -87,22 +87,18 @@ class AuthProvider {
}

async getTokenInteractive(tokenRequest) {
try {
const openBrowser = async (url) => {
await shell.openExternal(url);
};

const authResponse = await this.clientApplication.acquireTokenInteractive({
...tokenRequest,
openBrowser,
successTemplate: '<h1>Successfully signed in!</h1> <p>You can close this window now.</p>',
errorTemplate: '<h1>Oops! Something went wrong</h1> <p>Check the console for more information.</p>',
});

return authResponse;
} catch (error) {
throw error;
}
const openBrowser = async (url) => {
await shell.openExternal(url);
};

const authResponse = await this.clientApplication.acquireTokenInteractive({
...tokenRequest,
openBrowser,
successTemplate: "<h1>Successfully signed in!</h1> <p>You can close this window now.</p>",
errorTemplate: "<h1>Oops! Something went wrong</h1> <p>Check the console for more information.</p>",
});

return authResponse;
}

/**
Expand All @@ -127,13 +123,13 @@ class AuthProvider {
const currentAccounts = await this.cache.getAllAccounts();

if (!currentAccounts) {
console.log('No accounts detected');
console.log("No accounts detected");
return null;
}

if (currentAccounts.length > 1) {
// Add choose account code here
console.log('Multiple accounts detected, need to add choose account code.');
console.log("Multiple accounts detected, need to add choose account code.");
return currentAccounts[0];
} else if (currentAccounts.length === 1) {
return currentAccounts[0];
Expand All @@ -143,4 +139,4 @@ class AuthProvider {
}
}

module.exports = AuthProvider;
module.exports = AuthProvider;
54 changes: 0 additions & 54 deletions msal/CachePlugin.js

This file was deleted.

Loading

0 comments on commit 4267f47

Please sign in to comment.