Various refactoring

This commit is contained in:
Geomitron
2020-03-03 21:48:41 -05:00
parent 442736205e
commit 4ebf2db650
34 changed files with 503 additions and 329 deletions

View File

@@ -50,6 +50,9 @@ export default class Database {
})
}
/**
* Destroys the database connection.
*/
static closeConnection() {
if (this.database != undefined) {
this.database.conn.destroy()
@@ -57,10 +60,9 @@ export default class Database {
}
/**
* Sends <query> to the database.
* @param query The query string to be sent.
* @param queryStatement The nth response statement to be returned.
* @returns one of the responses as type <ResponseType[]>, or an empty array if the query fails.
* Sends `query` to the database.
* @param queryStatement The nth response statement to be returned. If undefined, the entire response is returned.
* @returns the selected response statement, or an empty array if the query fails.
*/
async sendQuery<ResponseType>(query: string, queryStatement?: number) {
return new Promise<ResponseType[] | ResponseType>(resolve => {

View File

@@ -1,11 +1,10 @@
import InitSettingsHandler from '../ipc/InitSettingsHandler.ipc'
import { basename } from 'path'
import { GetSettingsHandler } from '../ipc/SettingsHandler.ipc'
/**
* @param absoluteFilepath The absolute filepath to a folder
* @returns The relative filepath from the scanned folder to <absoluteFilepath>
* @returns The relative filepath from the library folder to `absoluteFilepath`.
*/
export async function getRelativeFilepath(absoluteFilepath: string) {
const settings = await InitSettingsHandler.getSettings()
export function getRelativeFilepath(absoluteFilepath: string) {
const settings = GetSettingsHandler.getSettings()
return basename(settings.libraryPath) + absoluteFilepath.substring(settings.libraryPath.length)
}

View File

@@ -43,7 +43,7 @@ export function failDelete(filepath: string, error: any) {
*/
export function failEncoding(filepath: string, error: any) {
console.error(`${red('ERROR:')} Failed to read text file (${getRelativeFilepath(filepath)
}):\nJavaScript cannot parse using the detected text encoding of (${error})`)
}):\nJavaScript cannot parse using the detected text encoding of (${error})`)
}
/**

View File

@@ -3,12 +3,11 @@ import { VersionResult, AlbumArtResult } from './interfaces/songDetails.interfac
import SearchHandler from '../ipc/SearchHandler.ipc'
import SongDetailsHandler from '../ipc/SongDetailsHandler.ipc'
import AlbumArtHandler from '../ipc/AlbumArtHandler.ipc'
import { Download, NewDownload, DownloadProgress } from './interfaces/download.interface'
import { Download, DownloadProgress } from './interfaces/download.interface'
import { DownloadHandler } from '../ipc/download/DownloadHandler'
import { Settings } from './Settings'
import InitSettingsHandler from '../ipc/InitSettingsHandler.ipc'
import BatchSongDetailsHandler from '../ipc/BatchSongDetailsHandler.ipc'
import SaveSettingsHandler from '../ipc/SaveSettingsHandler.ipc'
import { GetSettingsHandler, SetSettingsHandler } from '../ipc/SettingsHandler.ipc'
/**
* To add a new IPC listener:
@@ -20,7 +19,7 @@ import SaveSettingsHandler from '../ipc/SaveSettingsHandler.ipc'
export function getIPCInvokeHandlers(): IPCInvokeHandler<keyof IPCInvokeEvents>[] {
return [
new InitSettingsHandler(),
new GetSettingsHandler(),
new SearchHandler(),
new SongDetailsHandler(),
new BatchSongDetailsHandler(),
@@ -28,8 +27,11 @@ export function getIPCInvokeHandlers(): IPCInvokeHandler<keyof IPCInvokeEvents>[
]
}
/**
* The list of possible async IPC events that return values, mapped to their input and output types.
*/
export type IPCInvokeEvents = {
'init-settings': {
'get-settings': {
input: undefined
output: Settings
}
@@ -51,24 +53,34 @@ export type IPCInvokeEvents = {
}
}
/**
* Describes an object that handles the `E` async IPC event that will return a value.
*/
export interface IPCInvokeHandler<E extends keyof IPCInvokeEvents> {
event: E
handler(data: IPCInvokeEvents[E]['input']): Promise<IPCInvokeEvents[E]['output']> | IPCInvokeEvents[E]['output']
}
export function getIPCEmitHandlers(): IPCEmitHandler<keyof IPCEmitEvents>[]{
export function getIPCEmitHandlers(): IPCEmitHandler<keyof IPCEmitEvents>[] {
return [
new DownloadHandler(),
new SaveSettingsHandler()
new SetSettingsHandler()
]
}
/**
* The list of possible async IPC events that don't return values, mapped to their input types.
*/
export type IPCEmitEvents = {
'download': Download
'download-updated': DownloadProgress
'update-settings': Settings
'set-settings': Settings
}
/**
* Describes an object that handles the `E` async IPC event that will not return a value.
*/
export interface IPCEmitHandler<E extends keyof IPCEmitEvents> {
event: E
handler(data: IPCEmitEvents[E]): void

View File

@@ -1,9 +1,15 @@
/**
* Represents Bridge's user settings.
*/
export interface Settings {
rateLimitDelay: number // Number of seconds to wait between each file download from Google servers
theme: string // The name of the currently enabled UI theme
libraryPath: string // The path to the user's library
}
/**
* Bridge's default user settings.
*/
export const defaultSettings: Settings = {
rateLimitDelay: 31,
theme: 'Default',

View File

@@ -1,17 +1,17 @@
let sanitize = require('sanitize-filename')
const sanitize = require('sanitize-filename')
/**
* @returns A random UUID
* @returns a random UUID
*/
export function generateUUID() { // Public Domain/MIT
var d = new Date().getTime()//Timestamp
var d2 = Date.now() // Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16//random number between 0 and 16
if (d > 0) {//Use timestamp until depleted
let d = new Date().getTime() // Timestamp
let d2 = Date.now() // Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let r = Math.random() * 16 // Random number between 0 and 16
if (d > 0) { // Use timestamp until depleted
r = (d + r) % 16 | 0
d = Math.floor(d / 16)
} else {//Use microseconds since page-load if supported
} else { // Use microseconds since page-load if supported
r = (d2 + r) % 16 | 0
d2 = Math.floor(d2 / 16)
}
@@ -20,9 +20,8 @@ export function generateUUID() { // Public Domain/MIT
}
/**
* Sanitizes a filename of any characters that cannot be part of a windows filename.
* @param filename The name of the file to sanitize.
*/
* @returns `filename`, but with any invalid filename characters replaced with similar valid characters.
*/
export function sanitizeFilename(filename: string): string {
const newName = sanitize(filename, {
replacement: ((invalidChar: string) => {
@@ -30,7 +29,7 @@ export function sanitizeFilename(filename: string): string {
case '/': return '-'
case '\\': return '-'
case '"': return "'"
default: return '_' //TODO: add more cases for replacing invalid characters
default: return '_' // TODO: add more cases for replacing invalid characters
}
})
})
@@ -38,16 +37,14 @@ export function sanitizeFilename(filename: string): string {
}
/**
* Converts <val> from the range (<fromA>, <fromB>) to the range (<toA>, <toB>).
* Converts `val` from the range (`fromA`, `fromB`) to the range (`toA`, `toB`).
*/
export function interpolate(val: number, fromA: number, fromB: number, toA: number, toB: number) {
return ((val - fromA) / (fromB - fromA)) * (toB - toA) + toA
}
/**
* Splits <objectList> into multiple arrays, grouping by matching <key> values.
* @param objectList A list of objects.
* @param key A key from the list of objects.
* @returns `objectList` split into multiple arrays, where each array contains the objects with matching `key` values.
*/
export function groupBy<T>(objectList: T[], key: keyof T) {
const results: T[][] = []

View File

@@ -1,11 +1,14 @@
/**
* Represents a user's request to interact with the download system.
*/
export interface Download {
action: 'add' | 'retry' | 'continue' | 'cancel'
versionID: number
data ?: NewDownload
data?: NewDownload // Should be defined if action == 'add'
}
/**
* Contains the data required to start downloading a single chart
* Contains the data required to start downloading a single chart.
*/
export interface NewDownload {
avTagName: string
@@ -15,7 +18,7 @@ export interface NewDownload {
}
/**
* Represents the download progress of a single chart
* Represents the download progress of a single chart.
*/
export interface DownloadProgress {
versionID: number

View File

@@ -1,12 +1,21 @@
/**
* Represents a user's song search query.
*/
export interface SongSearch {
query: string
type: SearchType
}
/**
* The list of possible search categories.
*/
export enum SearchType {
'Any', 'Name', 'Artist', 'Album', 'Genre', 'Year', 'Charter'
}
/**
* Represents a single song search result.
*/
export interface SongResult {
id: number
name: string

View File

@@ -1,7 +1,13 @@
/**
* The image data for a song's album art.
*/
export interface AlbumArtResult {
art: Buffer
}
/**
* Represents a single chart version.
*/
export interface VersionResult {
versionID: number
chartID: number