Skip to content

Commit

Permalink
Refactor Logger class to use static functions
Browse files Browse the repository at this point in the history
The changes remove the unnecessary logger member from all classes.
All logging functions are now static functions and accept an optional
parameter to specify the calling class.
  • Loading branch information
ifl0w committed Sep 24, 2023
1 parent dac2406 commit db773b7
Show file tree
Hide file tree
Showing 23 changed files with 119 additions and 178 deletions.
4 changes: 1 addition & 3 deletions src/adapter/baseAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ abstract class BaseAdapter {
protected _bowl = new SoupBowl();

protected _generalSettings: SettingsModule.Settings;
protected _logger: Logger;
protected _settings: SettingsModule.Settings;
protected _sourceName: string;

Expand All @@ -38,7 +37,6 @@ abstract class BaseAdapter {
schemaPath: string;
}) {
const path = `${SettingsModule.RWG_SETTINGS_SCHEMA_PATH}/sources/general/${params.id}/`;
this._logger = new Logger('RWG3', `${params.defaultName} adapter`);

this._settings = new SettingsModule.Settings(params.schemaID, params.schemaPath);
this._sourceName = params.name ?? params.defaultName;
Expand Down Expand Up @@ -113,7 +111,7 @@ abstract class BaseAdapter {
const blockedFilenames = this._generalSettings.getStrv('blocked-images');

if (blockedFilenames.includes(filename)) {
this._logger.info(`Image is blocked: ${filename}`);
Logger.info(`Image is blocked: ${filename}`, this);
return true;
}

Expand Down
13 changes: 7 additions & 6 deletions src/adapter/genericJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as Utils from './../utils.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from './../logger.js';

/** How many times the service should be queried at maximum. */
const MAX_SERVICE_RETRIES = 5;
Expand Down Expand Up @@ -48,7 +49,7 @@ class GenericJsonAdapter extends BaseAdapter {

const message = this._bowl.newGetMessage(url);
if (message === null) {
this._logger.error('Could not create request.');
Logger.error('Could not create request.', this);
throw wallpaperResult;
}

Expand All @@ -57,7 +58,7 @@ class GenericJsonAdapter extends BaseAdapter {
const response_body_bytes = await this._bowl.send_and_receive(message);
response_body = JSON.parse(new TextDecoder().decode(response_body_bytes)) as unknown;
} catch (error) {
this._logger.error(error);
Logger.error(error, this);
throw wallpaperResult;
}

Expand All @@ -70,7 +71,7 @@ class GenericJsonAdapter extends BaseAdapter {
for (let i = 0; i < MAX_ARRAY_RETRIES + count && wallpaperResult.length < count; i++) {
const [returnObject, resolvedPath] = JSONPath.getTarget(response_body, imageJSONPath);
if (!returnObject || (typeof returnObject !== 'string' && typeof returnObject !== 'number') || returnObject === '') {
this._logger.error('Unexpected json member found');
Logger.error('Unexpected json member found', this);
break;
}

Expand Down Expand Up @@ -124,7 +125,7 @@ class GenericJsonAdapter extends BaseAdapter {
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
throw wallpaperResult;
}

Expand All @@ -151,7 +152,7 @@ class GenericJsonAdapter extends BaseAdapter {
// eslint-disable-next-line no-await-in-loop
historyArray = await this._getHistoryEntry(count);
} catch (error) {
this._logger.warn('Failed getting image');
Logger.warn('Failed getting image', this);

if (Array.isArray(error) && error.length > 0 && error[0] instanceof HistoryEntry)
historyArray = error as HistoryEntry[];
Expand All @@ -168,7 +169,7 @@ class GenericJsonAdapter extends BaseAdapter {
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
throw wallpaperResult;
}

Expand Down
7 changes: 4 additions & 3 deletions src/adapter/localFolder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as Utils from './../utils.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from './../logger.js';

// https://gjs.guide/guides/gjs/asynchronous-programming.html#promisify-helper
Gio._promisify(Gio.File.prototype, 'copy_async', 'copy_finish');
Expand Down Expand Up @@ -44,11 +45,11 @@ class LocalFolderAdapter extends BaseAdapter {
const wallpaperResult: HistoryEntry[] = [];

if (files.length < 1) {
this._logger.error('No files found');
Logger.error('No files found', this);
reject(wallpaperResult);
return;
}
this._logger.debug(`Found ${files.length} possible wallpaper in "${this._settings.getString('folder')}"`);
Logger.debug(`Found ${files.length} possible wallpaper in "${this._settings.getString('folder')}"`, this);

const shuffledFiles = Utils.shuffleArray(files);

Expand All @@ -63,7 +64,7 @@ class LocalFolderAdapter extends BaseAdapter {
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
reject(wallpaperResult);
return;
}
Expand Down
9 changes: 5 additions & 4 deletions src/adapter/reddit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Utils from './../utils.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from '../logger.js';

interface RedditResponse {
data: {
Expand Down Expand Up @@ -78,12 +79,12 @@ class RedditAdapter extends BaseAdapter {
const response_body_bytes = await this._bowl.send_and_receive(message);
response_body = JSON.parse(new TextDecoder().decode(response_body_bytes)) as unknown;
} catch (error) {
this._logger.error(error);
Logger.error(error, this);
throw wallpaperResult;
}

if (!this._isRedditResponse(response_body)) {
this._logger.error('Unexpected response');
Logger.error('Unexpected response', this);
throw wallpaperResult;
}

Expand All @@ -108,7 +109,7 @@ class RedditAdapter extends BaseAdapter {
});

if (filteredSubmissions.length === 0) {
this._logger.error('No suitable submissions found!');
Logger.error('No suitable submissions found!', this);
throw wallpaperResult;
}

Expand All @@ -129,7 +130,7 @@ class RedditAdapter extends BaseAdapter {
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
throw wallpaperResult;
}

Expand Down
9 changes: 5 additions & 4 deletions src/adapter/unsplash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Utils from './../utils.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from './../logger.js';

/** How many times the service should be queried at maximum. */
const MAX_SERVICE_RETRIES = 5;
Expand Down Expand Up @@ -62,7 +63,7 @@ class UnsplashAdapter extends BaseAdapter {
let url = `https://source.unsplash.com${optionsString}`;
url = encodeURI(url);

this._logger.debug(`Unsplash request to: ${url}`);
Logger.debug(`Unsplash request to: ${url}`, this);

const message = this._bowl.newGetMessage(url);

Expand Down Expand Up @@ -113,16 +114,16 @@ class UnsplashAdapter extends BaseAdapter {
if (!this._includesWallpaper(wallpaperResult, historyEntry.source.imageDownloadUrl))
wallpaperResult.push(historyEntry);
} catch (error) {
this._logger.warn('Failed getting image.');
this._logger.warn(error);
Logger.warn('Failed getting image.', this);
Logger.warn(error, this);
// Do not escalate yet, try again
}

// Image blocked, try again
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
throw wallpaperResult;
}

Expand Down
3 changes: 2 additions & 1 deletion src/adapter/urlSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as SettingsModule from './../settings.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from '../logger.js';

/**
* Adapter for using a single static URL as an image source.
Expand Down Expand Up @@ -46,7 +47,7 @@ class UrlSourceAdapter extends BaseAdapter {
const postUrl = this._settings.getString('domain');

if (imageDownloadUrl === '') {
this._logger.error('Missing download url');
Logger.error('Missing download url', this);
throw wallpaperResult;
}

Expand Down
11 changes: 6 additions & 5 deletions src/adapter/wallhaven.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as Utils from './../utils.js';

import {BaseAdapter} from './../adapter/baseAdapter.js';
import {HistoryEntry} from './../history.js';
import {Logger} from './../logger.js';

interface QueryOptions {
/**
Expand Down Expand Up @@ -82,25 +83,25 @@ class WallhavenAdapter extends BaseAdapter {
if (apiKey !== '')
message.requestHeaders.append('X-API-Key', apiKey);

this._logger.debug(`Search URL: ${url}`);
Logger.debug(`Search URL: ${url}`, this);

let wallhavenResponse;
try {
const response_body_bytes = await this._bowl.send_and_receive(message);
wallhavenResponse = JSON.parse(new TextDecoder().decode(response_body_bytes)) as unknown;
} catch (error) {
this._logger.error(error);
Logger.error(error, this);
throw wallpaperResult;
}

if (!this._isWallhavenResponse(wallhavenResponse)) {
this._logger.error('Unexpected response');
Logger.error('Unexpected response', this);
throw wallpaperResult;
}

const response = wallhavenResponse.data;
if (!response || response.length === 0) {
this._logger.error('Empty response');
Logger.error('Empty response', this);
throw wallpaperResult;
}

Expand All @@ -121,7 +122,7 @@ class WallhavenAdapter extends BaseAdapter {
}

if (wallpaperResult.length < count) {
this._logger.warn('Returning less images than requested.');
Logger.warn('Returning less images than requested.', this);
throw wallpaperResult;
}

Expand Down
18 changes: 7 additions & 11 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type * as WallpaperControllerNamespace from './wallpaperController.js';
import type * as RandomWallpaperMenuNamespace from './randomWallpaperMenu.js';
import type {ExtensionMeta} from 'ExtensionMeta';

let Logger: typeof LoggerNamespace | null = null;
let Logger: typeof LoggerNamespace.Logger | null = null;
let Timer: typeof AFTimer | null = null;
let WallpaperController: typeof WallpaperControllerNamespace | null = null;
let RandomWallpaperMenu: typeof RandomWallpaperMenuNamespace | null = null;
Expand All @@ -38,7 +38,6 @@ function init(unusedMeta: ExtensionMeta): Extension {
* The functions enable() and disable() are required.
*/
class Extension {
private _logger: LoggerNamespace.Logger | null = null;
private _wallpaperController: WallpaperControllerNamespace.WallpaperController | null = null;
private _panelMenu: RandomWallpaperMenuNamespace.RandomWallpaperMenu | null = null;
private _timer: AFTimer.AFTimer | null = null;
Expand Down Expand Up @@ -67,16 +66,15 @@ class Extension {
if (!Logger || !Timer || !WallpaperController || !RandomWallpaperMenu)
throw new Error('Error importing module');

this._logger = new Logger.Logger('RWG3', 'Main');
this._timer = Timer.AFTimer.getTimer();
this._wallpaperController = new WallpaperController.WallpaperController();
this._panelMenu = new RandomWallpaperMenu.RandomWallpaperMenu(this._wallpaperController);

this._logger.info('Enable extension.');
Logger.info('Enable extension.', this);
this._panelMenu.init();
}).catch(error => {
if (this._logger)
this._logger.error(error);
if (Logger)
Logger.error(error, this);
else if (error instanceof Error)
logError(error);
else
Expand All @@ -98,8 +96,8 @@ class Extension {
* Not doing so is the most common reason extensions are rejected in review!
*/
disable(): void {
if (this._logger)
this._logger.info('Disable extension.');
if (Logger)
Logger.info('Disable extension.');

if (this._panelMenu)
this._panelMenu.cleanup();
Expand All @@ -112,12 +110,10 @@ class Extension {
this._wallpaperController.cleanup();

this._timer = null;
this._logger = null;
this._panelMenu = null;
this._wallpaperController = null;

Timer = null;
Logger = null;
WallpaperController = null;
RandomWallpaperMenu = null;
}
Expand All @@ -142,7 +138,7 @@ class Extension {
loggerPromise, timerPromise, wallpaperPromise, menuPromise,
]);

Logger = moduleLogger;
Logger = moduleLogger.Logger;
Timer = moduleTimer;
WallpaperController = moduleWallpaper;
RandomWallpaperMenu = moduleMenu;
Expand Down
3 changes: 1 addition & 2 deletions src/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ class HistoryController {
history: HistoryEntry[] = [];
size = 10;

private _logger = new Logger('RWG3', 'HistoryController');
private _settings = new Settings();

/**
Expand Down Expand Up @@ -267,7 +266,7 @@ class HistoryController {
* This tries to avoid invalid states later on because we would have thrown here and therefore skip saving.
*/
if (file.get_parent()?.query_exists(null) && error instanceof GLib.Error && error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND)) {
this._logger.warn(`Ignoring Gio.IOErrorEnum.NOT_FOUND: ${file.get_path() ?? 'undefined'}`);
Logger.warn(`Ignoring Gio.IOErrorEnum.NOT_FOUND: ${file.get_path() ?? 'undefined'}`, this);
return;
}

Expand Down
Loading

0 comments on commit db773b7

Please sign in to comment.