Converted classes scripts

pull/73/head
MillenniumEarl 2021-02-13 16:21:28 +01:00
parent df8b77fa4e
commit c6bf753f29
6 changed files with 185 additions and 212 deletions

View File

@ -1,22 +1,35 @@
"use strict"; "use strict";
// Modules from file // Modules from file
const { getF95Token } = require("../network-helper.js"); import { getF95Token } from "../network-helper.js";
class Credentials { /**
constructor(username, password) { * Represents the credentials used to access the platform.
*/
export class Credentials {
/**
* Username
*/
username: string;
/**
* Password of the user.
*/
password: string;
/**
* One time token used during login.
*/
token: string = null;
constructor(username: string, password: string) {
this.username = username; this.username = username;
this.password = password; this.password = password;
this.token = null;
} }
/** /**
* @public * @public
* Fetch and save the token used to log in to F95Zone. * Fetch and save the token used to log in to F95Zone.
*/ */
async fetchToken() { async fetchToken(): Promise<void> {
this.token = await getF95Token(); this.token = await getF95Token();
} }
} }
module.exports = Credentials;

View File

@ -1,97 +1,82 @@
"use strict"; "use strict";
class GameInfo { /**
constructor() { * Information of a game/mod on the platform.
//#region Properties */
/** export class GameInfo {
* Unique ID of the game on the platform. //#region Properties
* @type Number /**
*/ * Unique ID of the game on the platform.
this.id = -1; */
/** id = -1;
* Game name /**
* @type String * Game name
*/ */
this.name = null; name: string = null;
/** /**
* Game author * Game author
* @type String */
*/ author: string = null;
this.author = null; /**
/** * URL to the game's official conversation on the F95Zone portal
* URL to the game's official conversation on the F95Zone portal */
* @type String url: string = null;
*/ /**
this.url = null; * Game description
/** */
* Game description overview: string = null;
* @type String /**
*/ * Game language
this.overview = null; */
/** language: string = null;
* Game language. /**
* @type String * List of supported OS
*/ */
this.language = null; supportedOS: string[] = [];
/** /**
* List of supported OS. * Specify whether the game has censorship
* @type * measures regarding NSFW scenes
*/ */
this.supportedOS = []; censored: boolean = null;
/** /**
* Specify whether the game has censorship * List of tags associated with the game
* measures regarding NSFW scenes. */
* @type Boolean tags: string[] = [];
*/ /**
this.censored = null; * Graphics engine used for game development
/** */
* List of tags associated with the game engine: string = null;
* @type String[] /**
*/ * Development of the game
this.tags = []; */
/** status: string = null;
* Graphics engine used for game development /**
* @type String * Game description image URL
*/ */
this.engine = null; previewSrc: string = null;
/** /**
* Development of the game * Game version
* @type String */
*/ version: string = null;
this.status = null; /**
/** * Last time the game underwent updates
* Game description image URL */
* @type String lastUpdate: Date = null;
*/ /**
this.previewSrc = null; * Specifies if the game is original or a mod
/** */
* Game version isMod = false;
* @type String /**
*/ * Changelog for the last version
this.version = null; */
/** changelog: string = null;
* Last time the game underwent updates //#endregion Properties
* @type Date
*/
this.lastUpdate = null;
/**
* Specifies if the game is original or a mod
* @type Boolean
*/
this.isMod = false;
/**
* Changelog for the last version.
* @type String
*/
this.changelog = null;
//#endregion Properties
}
/** /**
* Converts the object to a dictionary used for JSON serialization. * Converts the object to a dictionary used for JSON serialization.
*/ */
/* istanbul ignore next */ /* istanbul ignore next */
toJSON() { toJSON(): Record<string, unknown> {
return { return {
id: this.id, id: this.id,
name: this.name, name: this.name,
@ -117,13 +102,12 @@ class GameInfo {
* @param {String} json JSON string used to create the new object * @param {String} json JSON string used to create the new object
* @returns {GameInfo} * @returns {GameInfo}
*/ */
static fromJSON(json) { static fromJSON(json: string): GameInfo {
// Convert string // Convert string
const temp = Object.assign(new GameInfo(), JSON.parse(json)); const temp = Object.assign(new GameInfo(), JSON.parse(json));
// JSON cannot transform a string to a date implicitly // JSON cannot transform a string to a date implicitly
temp.lastUpdate = new Date(temp.lastUpdate); temp.lastUpdate = new Date(temp.lastUpdate);
return temp; return temp;
} }
} }
module.exports = GameInfo;

View File

@ -3,18 +3,18 @@
/** /**
* Object obtained in response to an attempt to login to the portal. * Object obtained in response to an attempt to login to the portal.
*/ */
class LoginResult { export class LoginResult {
constructor(success, message) { /**
/** * Result of the login operation
* Result of the login operation */
* @type Boolean success: boolean;
*/ /**
* Login response message
*/
message: string;
constructor(success: boolean, message: string) {
this.success = success; this.success = success;
/**
* Login response message
* @type String
*/
this.message = message; this.message = message;
} }
} }
module.exports = LoginResult;

View File

@ -1,15 +1,12 @@
"use strict"; "use strict";
// Modules from file // Modules from file
const shared = require("../shared.js"); import shared = require("../shared.js");
/** /**
* Convert prefixes and platform tags from string to ID and vice versa. * Convert prefixes and platform tags from string to ID and vice versa.
*/ */
class PrefixParser { export class PrefixParser {
constructor() {
}
//#region Private methods //#region Private methods
/** /**
* @private * @private
@ -18,23 +15,19 @@ class PrefixParser {
* @param {Any} value Value associated with the key * @param {Any} value Value associated with the key
* @returns {String|undefined} Key found or undefined * @returns {String|undefined} Key found or undefined
*/ */
_getKeyByValue(object, value) { _getKeyByValue(object: { [x: string]: unknown; }, value: unknown): string | undefined {
return Object.keys(object).find(key => object[key] === value); return Object.keys(object).find(key => object[key] === value);
} }
/** /**
* @private * @private
* Makes an array of strings uppercase. * Makes an array of strings uppercase.
* @param {String[]} a
* @returns {String[]}
*/ */
_toUpperCaseArray(a) { _toUpperCaseArray(a: string[]): string[] {
/** /**
* Makes a string uppercase. * Makes a string uppercase.
* @param {String} s
* @returns {String}
*/ */
function toUpper(s) { function toUpper(s: string): string {
return s.toUpperCase(); return s.toUpperCase();
} }
return a.map(toUpper); return a.map(toUpper);
@ -43,10 +36,8 @@ class PrefixParser {
/** /**
* @private * @private
* Check if `dict` contains `value` as a value. * Check if `dict` contains `value` as a value.
* @param {Object.<number, string>} dict
* @param {String} value
*/ */
_valueInDict(dict, value) { _valueInDict(dict: { [s: number]: string; }, value: string): boolean {
const array = Object.values(dict); const array = Object.values(dict);
const upperArr = this._toUpperCaseArray(array); const upperArr = this._toUpperCaseArray(array);
const element = value.toUpperCase(); const element = value.toUpperCase();
@ -57,10 +48,9 @@ class PrefixParser {
/** /**
* @public * @public
* Convert a list of prefixes to their respective IDs. * Convert a list of prefixes to their respective IDs.
* @param {String[]} prefixes
*/ */
prefixesToIDs(prefixes) { prefixesToIDs(prefixes: string[]) : number[] {
const ids = []; const ids: number[] = [];
for(const p of prefixes) { for(const p of prefixes) {
// Check what dict contains the value // Check what dict contains the value
let dict = null; let dict = null;
@ -80,10 +70,9 @@ class PrefixParser {
/** /**
* @public * @public
* It converts a list of IDs into their respective prefixes. * It converts a list of IDs into their respective prefixes.
* @param {number[]} ids
*/ */
idsToPrefixes(ids) { idsToPrefixes(ids: number[]): string[] {
const prefixes = []; const prefixes:string[] = [];
for(const id of ids) { for(const id of ids) {
// Check what dict contains the key // Check what dict contains the key
let dict = null; let dict = null;
@ -98,6 +87,4 @@ class PrefixParser {
} }
return prefixes; return prefixes;
} }
} }
module.exports = PrefixParser;

View File

@ -1,53 +1,53 @@
"use strict"; "use strict";
// Core modules // Core modules
const fs = require("fs"); import * as fs from "fs";
const promisify = require("util").promisify; import { promisify } from "util";
// Public modules from npm // Public modules from npm
const md5 = require("md5"); import * as md5 from "md5";
// Promisifed functions // Promisifed functions
const areadfile = promisify(fs.readFile); const areadfile = promisify(fs.readFile);
const awritefile = promisify(fs.writeFile); const awritefile = promisify(fs.writeFile);
const aunlinkfile = promisify(fs.unlink); const aunlinkfile = promisify(fs.unlink);
class Session { export class Session {
constructor(path) { //#region Properties
/** /**
* Max number of days the session is valid. * Max number of days the session is valid.
*/ */
this.SESSION_TIME = 1; private readonly SESSION_TIME: number = 1;
/**
* Path of the session map file on disk.
*/
private path: string = null;
/**
* Indicates if the session is mapped on disk.
*/
private isMapped = null;
/**
* Date of creation of the session.
*/
private created = null;
/**
* MD5 hash of the username and the password.
*/
private hash = null;
//#endregion Properties
/** constructor(path: string) {
* Path of the session map file on disk. this.path = path;
*/ this.isMapped = fs.existsSync(this.path);
this._path = path; this.created = new Date(Date.now());
this.hash = null;
/**
* Indicates if the session is mapped on disk.
*/
this._isMapped = fs.existsSync(this._path);
/**
* Date of creation of the session.
*/
this._created = new Date(Date.now());
/**
* MD5 hash of the username and the password.
*/
this._hash = null;
} }
//#region Private Methods //#region Private Methods
/** /**
* @private
* Get the difference in days between two dates. * Get the difference in days between two dates.
* @param {Date} a
* @param {Date} b
*/ */
_dateDiffInDays(a, b) { private dateDiffInDays(a: Date, b: Date) {
const MS_PER_DAY = 1000 * 60 * 60 * 24; const MS_PER_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information. // Discard the time and time-zone information.
@ -58,72 +58,70 @@ class Session {
} }
/** /**
* @private
* Convert the object to a dictionary serializable in JSON. * Convert the object to a dictionary serializable in JSON.
*/ */
_toJSON() { private toJSON(): Record<string, unknown> {
return { return {
created: this._created, created: this.created,
hash: this._hash, hash: this.hash,
}; };
} }
//#endregion Private Methods //#endregion Private Methods
//#region Public Methods //#region Public Methods
create(username, password) { /**
* Create a new session
*/
create(username: string, password: string):void {
// First, create the hash of the credentials // First, create the hash of the credentials
const value = `${username}%%%${password}`; const value = `${username}%%%${password}`;
this._hash = md5(value); this.hash = md5(value);
// Update the creation date // Update the creation date
this._created = new Date(Date.now()); this.created = new Date(Date.now());
} }
/** /**
* @public
* Save the session to disk. * Save the session to disk.
*/ */
async save() { async save() : Promise<void> {
// Update the creation date // Update the creation date
this._created = new Date(Date.now()); this.created = new Date(Date.now());
// Convert data // Convert data
const json = this._toJSON(); const json = this.toJSON();
const data = JSON.stringify(json); const data = JSON.stringify(json);
// Write data // Write data
await awritefile(this._path, data); await awritefile(this.path, data);
} }
/** /**
* @public
* Load the session from disk. * Load the session from disk.
*/ */
async load() { async load(): Promise<void> {
// Read data // Read data
const data = await areadfile(this._path); const data = await areadfile(this.path, { encoding: 'utf-8', flag: 'r' });
const json = JSON.parse(data); const json = JSON.parse(data);
// Assign values // Assign values
this._created = json.created; this.created = json.created;
this._hash = json.hash; this.hash = json.hash;
} }
/** /**
* @public
* Delete the session from disk. * Delete the session from disk.
*/ */
async delete() { async delete(): Promise<void> {
await aunlinkfile(this._path); await aunlinkfile(this.path);
} }
/** /**
* @public
* Check if the session is valid. * Check if the session is valid.
*/ */
isValid(username, password) { isValid(username:string, password:string) : boolean {
// Get the number of days from the file creation // Get the number of days from the file creation
const diff = this._dateDiffInDays(new Date(Date.now()), this._created); const diff = this.dateDiffInDays(new Date(Date.now()), this.created);
// The session is valid if the number of days is minor than SESSION_TIME // The session is valid if the number of days is minor than SESSION_TIME
let valid = diff < this.SESSION_TIME; let valid = diff < this.SESSION_TIME;
@ -131,11 +129,9 @@ class Session {
if(valid) { if(valid) {
// Check the hash // Check the hash
const value = `${username}%%%${password}`; const value = `${username}%%%${password}`;
valid = md5(value) === this._hash; valid = md5(value) === this.hash;
} }
return valid; return valid;
} }
//#endregion Public Methods //#endregion Public Methods
} }
module.exports = Session;

View File

@ -3,24 +3,17 @@
/** /**
* Class containing the data of the user currently connected to the F95Zone platform. * Class containing the data of the user currently connected to the F95Zone platform.
*/ */
class UserData { export class UserData {
constructor() { /**
/** * User name.
* User name. */
* @type String username: string = null;
*/ /**
this.username = ""; * Path to the user's profile picture.
/** */
* Path to the user's profile picture. avatarSrc: string = null;
* @type String /**
*/ * List of followed game thread URLs.
this.avatarSrc = null; */
/** watchedGameThreads: string[] = [];
* List of followed game thread URLs.
* @type String[]
*/
this.watchedGameThreads = [];
}
} }
module.exports = UserData;