Everywhere: Create abstract database handlers

The project now utilizes abstract handlers to fetch, modify
or otherwise manipulate data from the database.

This facilitates 3 aspects of the app, in addition of
making them future proof:

- Switching database libraries is now trivial
Since most of the app utilizes the abstract handlers, it's incredibly
easily to change to a different DB library.
Hypothetically, all that would need to be done is to simply replace the
the file containing the base handlers, while the rest of the app
would go unchanged.

- Syncing logic between Electron and web is now properly separated
There are now two distinct DB handling APIs: the Electron one and
the web one.
The app doesn't need to manually choose the API, because it's detected
which platform is being utilized on import.

- All Electron windows now share the same database instance
This provides a single source of truth, improving consistency
regarding data manipulation and windows synchronization.

As a sidenote, syncing implementation has been left as is
(web unimplemented; Electron only syncs settings, remaining
datastore syncing will be implemented in the upcoming commits).
This commit is contained in:
Svallinn 2021-10-17 23:31:20 +01:00
parent 1b5f40357f
commit dab73f8150
No known key found for this signature in database
GPG Key ID: 09FB527F34037CCA
12 changed files with 933 additions and 227 deletions

View File

@ -11,11 +11,47 @@ const IpcChannels = {
STOP_POWER_SAVE_BLOCKER: 'stop-power-save-blocker',
START_POWER_SAVE_BLOCKER: 'start-power-save-blocker',
CREATE_NEW_WINDOW: 'create-new-window',
OPEN_IN_EXTERNAL_PLAYER: 'open-in-external-player',
DB_SETTINGS: 'db-settings',
DB_HISTORY: 'db-history',
DB_PROFILES: 'db-profiles',
DB_PLAYLISTS: 'db-playlists',
SYNC_SETTINGS: 'sync-settings',
SYNC_HISTORY: 'sync-history',
SYNC_PROFILES: 'sync-profiles',
SYNC_PLAYLISTS: 'sync-playlists',
OPEN_IN_EXTERNAL_PLAYER: 'open-in-external-player'
SYNC_PLAYLISTS: 'sync-playlists'
}
const DBActions = {
GENERAL: {
CREATE: 'db-action-create',
FIND: 'db-action-find',
UPSERT: 'db-action-upsert',
DELETE: 'db-action-delete',
DELETE_MULTIPLE: 'db-action-delete-multiple',
DELETE_ALL: 'db-action-delete-all',
PERSIST: 'db-action-persist'
},
HISTORY: {
UPDATE_WATCH_PROGRESS: 'db-action-history-update-watch-progress'
},
PLAYLISTS: {
UPSERT_VIDEO: 'db-action-playlists-upsert-video-by-playlist-name',
UPSERT_VIDEO_IDS: 'db-action-playlists-upsert-video-ids-by-playlist-id',
DELETE_VIDEO_ID: 'db-action-playlists-delete-video-by-playlist-name',
DELETE_VIDEO_IDS: 'db-action-playlists-delete-video-ids',
DELETE_ALL_VIDEOS: 'db-action-playlists-delete-all-videos'
}
}
const SyncEvents = {
GENERAL: {
UPSERT: 'sync-upsert'
}
}
// Utils
@ -23,5 +59,7 @@ const MAIN_PROFILE_ID = 'allChannels'
export {
IpcChannels,
DBActions,
SyncEvents,
MAIN_PROFILE_ID
}

View File

@ -0,0 +1,153 @@
import db from '../index'
class Settings {
static find() {
return db.settings.find({ _id: { $ne: 'bounds' } })
}
static upsert(_id, value) {
return db.settings.update({ _id }, { _id, value }, { upsert: true })
}
// ******************** //
// Unique Electron main process handlers
static _findAppReadyRelatedSettings() {
return db.settings.find({
$or: [
{ _id: 'disableSmoothScrolling' },
{ _id: 'useProxy' },
{ _id: 'proxyProtocol' },
{ _id: 'proxyHostname' },
{ _id: 'proxyPort' }
]
})
}
static _findBounds() {
return db.settings.findOne({ _id: 'bounds' })
}
static _updateBounds(value) {
return db.settings.update({ _id: 'bounds' }, { _id: 'bounds', value }, { upsert: true })
}
// ******************** //
}
class History {
static find() {
return db.history.find({}).sort({ timeWatched: -1 })
}
static upsert(record) {
return db.history.update({ videoId: record.videoId }, record, { upsert: true })
}
static updateWatchProgress(videoId, watchProgress) {
return db.history.update({ videoId }, { $set: { watchProgress } }, { upsert: true })
}
static delete(videoId) {
return db.history.remove({ videoId })
}
static deleteAll() {
return db.history.remove({}, { multi: true })
}
static persist() {
db.history.persistence.compactDatafile()
}
}
class Profiles {
static create(profile) {
return db.profiles.insert(profile)
}
static find() {
return db.profiles.find({})
}
static upsert(profile) {
return db.profiles.update({ _id: profile._id }, profile, { upsert: true })
}
static delete(id) {
return db.profiles.remove({ _id: id })
}
static persist() {
db.profiles.persistence.compactDatafile()
}
}
class Playlists {
static create(playlists) {
return db.playlists.insert(playlists)
}
static find() {
return db.playlists.find({})
}
static upsertVideoByPlaylistName(playlistName, videoData) {
return db.playlists.update(
{ playlistName },
{ $push: { videos: videoData } },
{ upsert: true }
)
}
static upsertVideoIdsByPlaylistId(_id, videoIds) {
return db.playlists.update(
{ _id },
{ $push: { videos: { $each: videoIds } } },
{ upsert: true }
)
}
static delete(_id) {
return db.playlists.remove({ _id, protected: { $ne: true } })
}
static deleteVideoIdByPlaylistName(playlistName, videoId) {
return db.playlists.update(
{ playlistName },
{ $pull: { videos: { videoId } } },
{ upsert: true }
)
}
static deleteVideoIdsByPlaylistName(playlistName, videoIds) {
return db.playlists.update(
{ playlistName },
{ $pull: { videos: { $in: videoIds } } },
{ upsert: true }
)
}
static deleteAllVideosByPlaylistName(playlistName) {
return db.playlists.update(
{ playlistName },
{ $set: { videos: [] } },
{ upsert: true }
)
}
static deleteMultiple(ids) {
return db.playlists.remove({ _id: { $in: ids }, protected: { $ne: true } })
}
static deleteAll() {
return db.playlists.remove({ protected: { $ne: true } })
}
}
const baseHandlers = {
settings: Settings,
history: History,
profiles: Profiles,
playlists: Playlists
}
export default baseHandlers

View File

@ -0,0 +1,198 @@
import { ipcRenderer } from 'electron'
import { IpcChannels, DBActions } from '../../constants'
class Settings {
static find() {
return ipcRenderer.invoke(
IpcChannels.DB_SETTINGS,
{ action: DBActions.GENERAL.FIND }
)
}
static upsert(_id, value) {
return ipcRenderer.invoke(
IpcChannels.DB_SETTINGS,
{ action: DBActions.GENERAL.UPSERT, data: { _id, value } }
)
}
}
class History {
static find() {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{ action: DBActions.GENERAL.FIND }
)
}
static upsert(record) {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{ action: DBActions.GENERAL.UPSERT, data: record }
)
}
static updateWatchProgress(videoId, watchProgress) {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{
action: DBActions.HISTORY.UPDATE_WATCH_PROGRESS,
data: { videoId, watchProgress }
}
)
}
static delete(videoId) {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{ action: DBActions.GENERAL.DELETE, data: videoId }
)
}
static deleteAll() {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{ action: DBActions.GENERAL.DELETE_ALL }
)
}
static persist() {
return ipcRenderer.invoke(
IpcChannels.DB_HISTORY,
{ action: DBActions.GENERAL.PERSIST }
)
}
}
class Profiles {
static create(profile) {
return ipcRenderer.invoke(
IpcChannels.DB_PROFILES,
{ action: DBActions.GENERAL.CREATE, data: profile }
)
}
static find() {
return ipcRenderer.invoke(
IpcChannels.DB_PROFILES,
{ action: DBActions.GENERAL.FIND }
)
}
static upsert(profile) {
return ipcRenderer.invoke(
IpcChannels.DB_PROFILES,
{ action: DBActions.GENERAL.UPSERT, data: profile }
)
}
static delete(id) {
return ipcRenderer.invoke(
IpcChannels.DB_PROFILES,
{ action: DBActions.GENERAL.DELETE, data: id }
)
}
static persist() {
return ipcRenderer.invoke(
IpcChannels.DB_PROFILES,
{ action: DBActions.GENERAL.PERSIST }
)
}
}
class Playlists {
static create(playlists) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{ action: DBActions.GENERAL.CREATE, data: playlists }
)
}
static find() {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{ action: DBActions.GENERAL.FIND }
)
}
static upsertVideoByPlaylistName(playlistName, videoData) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{
action: DBActions.PLAYLISTS.UPSERT_VIDEO,
data: { playlistName, videoData }
}
)
}
static upsertVideoIdsByPlaylistId(_id, videoIds) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{
action: DBActions.PLAYLISTS.UPSERT_VIDEO_IDS,
data: { _id, videoIds }
}
)
}
static delete(_id) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{ action: DBActions.GENERAL.DELETE, data: _id }
)
}
static deleteVideoIdByPlaylistName(playlistName, videoId) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{
action: DBActions.PLAYLISTS.DELETE_VIDEO_ID,
data: { playlistName, videoId }
}
)
}
static deleteVideoIdsByPlaylistName(playlistName, videoIds) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{
action: DBActions.PLAYLISTS.DELETE_VIDEO_IDS,
data: { playlistName, videoIds }
}
)
}
static deleteAllVideosByPlaylistName(playlistName) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{
action: DBActions.PLAYLISTS.DELETE_ALL_VIDEOS,
data: playlistName
}
)
}
static deleteMultiple(ids) {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{ action: DBActions.GENERAL.DELETE_MULTIPLE, data: ids }
)
}
static deleteAll() {
return ipcRenderer.invoke(
IpcChannels.DB_PLAYLISTS,
{ action: DBActions.GENERAL.DELETE_ALL }
)
}
}
const handlers = {
settings: Settings,
history: History,
profiles: Profiles,
playlists: Playlists
}
export default handlers

View File

@ -0,0 +1,19 @@
let handlers
const usingElectron = window?.process?.type === 'renderer'
if (usingElectron) {
handlers = require('./electron').default
} else {
handlers = require('./web').default
}
const DBSettingHandlers = handlers.settings
const DBHistoryHandlers = handlers.history
const DBProfileHandlers = handlers.profiles
const DBPlaylistHandlers = handlers.playlists
export {
DBSettingHandlers,
DBHistoryHandlers,
DBProfileHandlers,
DBPlaylistHandlers
}

View File

@ -0,0 +1,120 @@
import baseHandlers from './base'
// TODO: Syncing
// Syncing on the web would involve a different implementation
// to the electron one (obviously)
// One idea would be to use a watcher-like mechanism on
// localStorage or IndexedDB to inform other tabs on the changes
// that have occurred in other tabs
//
// NOTE: NeDB uses `localForage` on the browser
// https://www.npmjs.com/package/localforage
class Settings {
static find() {
return baseHandlers.settings.find()
}
static upsert(_id, value) {
return baseHandlers.settings.upsert(_id, value)
}
}
class History {
static find() {
return baseHandlers.history.find()
}
static upsert(record) {
return baseHandlers.history.upsert(record)
}
static updateWatchProgress(videoId, watchProgress) {
return baseHandlers.history.updateWatchProgress(videoId, watchProgress)
}
static delete(videoId) {
return baseHandlers.history.delete(videoId)
}
static deleteAll() {
return baseHandlers.history.deleteAll()
}
static persist() {
baseHandlers.history.persist()
}
}
class Profiles {
static create(profile) {
return baseHandlers.profiles.create(profile)
}
static find() {
return baseHandlers.profiles.find()
}
static upsert(profile) {
return baseHandlers.profiles.upsert(profile)
}
static delete(id) {
return baseHandlers.profiles.delete(id)
}
static persist() {
baseHandlers.profiles.persist()
}
}
class Playlists {
static create(playlists) {
return baseHandlers.playlists.create(playlists)
}
static find() {
return baseHandlers.playlists.find()
}
static upsertVideoByPlaylistName(playlistName, videoData) {
return baseHandlers.playlists.upsertVideoByPlaylistName(playlistName, videoData)
}
static upsertVideoIdsByPlaylistId(_id, videoIds) {
return baseHandlers.playlists.upsertVideoIdsByPlaylistId(_id, videoIds)
}
static delete(_id) {
return baseHandlers.playlists.delete(_id)
}
static deleteVideoIdByPlaylistName(playlistName, videoId) {
return baseHandlers.playlists.deleteVideoIdByPlaylistName(playlistName, videoId)
}
static deleteVideoIdsByPlaylistName(playlistName, videoIds) {
return baseHandlers.playlists.deleteVideoIdsByPlaylistName(playlistName, videoIds)
}
static deleteAllVideosByPlaylistName(playlistName) {
return baseHandlers.playlists.deleteAllVideosByPlaylistName(playlistName)
}
static deleteMultiple(ids) {
return baseHandlers.playlists.deleteMultiple(ids)
}
static deleteAll() {
return baseHandlers.playlists.deleteAll()
}
}
const handlers = {
settings: Settings,
history: History,
profiles: Profiles,
playlists: Playlists
}
export default handlers

21
src/datastores/index.js Normal file
View File

@ -0,0 +1,21 @@
import Datastore from 'nedb-promises'
let dbPath = null
const isElectronMain = !!process?.versions?.electron
if (isElectronMain) {
const { app } = require('electron')
const { join } = require('path')
const userDataPath = app.getPath('userData') // This is based on the user's OS
dbPath = (dbName) => join(userDataPath, `${dbName}.db`)
} else {
dbPath = (dbName) => `${dbName}.db`
}
const db = {}
db.settings = Datastore.create({ filename: dbPath('settings'), autoload: true })
db.profiles = Datastore.create({ filename: dbPath('profiles'), autoload: true })
db.playlists = Datastore.create({ filename: dbPath('playlists'), autoload: true })
db.history = Datastore.create({ filename: dbPath('history'), autoload: true })
export default db

View File

@ -2,11 +2,11 @@ import {
app, BrowserWindow, dialog, Menu, ipcMain,
powerSaveBlocker, screen, session, shell
} from 'electron'
import Datastore from 'nedb-promises'
import path from 'path'
import cp from 'child_process'
import { IpcChannels } from '../constants'
import { IpcChannels, DBActions, SyncEvents } from '../constants'
import baseHandlers from '../datastores/handlers/base'
if (process.argv.includes('--version')) {
console.log(`v${app.getVersion()}`)
@ -23,13 +23,6 @@ function runApp() {
prepend: (params, browserWindow) => []
})
const localDataStorage = app.getPath('userData') // Grabs the userdata directory based on the user's OS
const settingsDb = Datastore.create({
filename: localDataStorage + '/settings.db',
autoload: true
})
// disable electron warning
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true'
const isDev = process.env.NODE_ENV === 'development'
@ -87,15 +80,7 @@ function runApp() {
app.on('ready', async (_, __) => {
let docArray
try {
docArray = await settingsDb.find({
$or: [
{ _id: 'disableSmoothScrolling' },
{ _id: 'useProxy' },
{ _id: 'proxyProtocol' },
{ _id: 'proxyHostname' },
{ _id: 'proxyPort' }
]
})
docArray = await baseHandlers.settings._findAppReadyRelatedSettings()
} catch (err) {
console.error(err)
app.exit()
@ -209,7 +194,7 @@ function runApp() {
height: 800
})
const boundsDoc = await settingsDb.findOne({ _id: 'bounds' })
const boundsDoc = await baseHandlers.settings._findBounds()
if (typeof boundsDoc?.value === 'object') {
const { maximized, ...bounds } = boundsDoc.value
const allDisplaysSummaryWidth = screen
@ -264,11 +249,7 @@ function runApp() {
maximized: newWindow.isMaximized()
}
await settingsDb.update(
{ _id: 'bounds' },
{ _id: 'bounds', value },
{ upsert: true }
)
await baseHandlers.settings._updateBounds(value)
})
newWindow.once('closed', () => {
@ -368,37 +349,213 @@ function runApp() {
createWindow(false)
})
ipcMain.on(IpcChannels.SYNC_SETTINGS, (event, payload) => {
passOntoSiblingWindows(IpcChannels.SYNC_SETTINGS, event, payload)
})
ipcMain.on(IpcChannels.SYNC_HISTORY, (event, payload) => {
passOntoSiblingWindows(IpcChannels.SYNC_HISTORY, event, payload)
})
ipcMain.on(IpcChannels.SYNC_PROFILES, (event, payload) => {
passOntoSiblingWindows(IpcChannels.SYNC_PROFILES, event, payload)
})
ipcMain.on(IpcChannels.SYNC_PLAYLISTS, (event, payload) => {
passOntoSiblingWindows(IpcChannels.SYNC_PLAYLISTS, event, payload)
})
function passOntoSiblingWindows(channel, event, payload) {
const siblingWindows = BrowserWindow.getAllWindows().filter((window) => {
return window.webContents.id !== event.sender.id
})
for (const window of siblingWindows) {
window.webContents.send(channel, payload)
}
}
ipcMain.on(IpcChannels.OPEN_IN_EXTERNAL_PLAYER, (_, payload) => {
const child = cp.spawn(payload.executable, payload.args, { detached: true, stdio: 'ignore' })
child.unref()
})
// ************************************************* //
// DB related IPC calls
// *********** //
// Settings
ipcMain.handle(IpcChannels.DB_SETTINGS, async (event, { action, data }) => {
try {
switch (action) {
case DBActions.GENERAL.FIND:
return await baseHandlers.settings.find()
case DBActions.GENERAL.UPSERT:
await baseHandlers.settings.upsert(data._id, data.value)
syncOtherWindows(
IpcChannels.SYNC_SETTINGS,
event,
{ event: SyncEvents.GENERAL.UPSERT, data }
)
return null
default:
// eslint-disable-next-line no-throw-literal
throw 'invalid settings db action'
}
} catch (err) {
if (typeof err === 'string') throw err
else throw err.toString()
}
})
// *********** //
// History
ipcMain.handle(IpcChannels.DB_HISTORY, async (_, { action, data }) => {
try {
switch (action) {
case DBActions.GENERAL.FIND:
return await baseHandlers.history.find()
case DBActions.GENERAL.UPSERT:
await baseHandlers.history.upsert(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_HISTORY, event, { event: '_', data })
return null
case DBActions.HISTORY.UPDATE_WATCH_PROGRESS:
await baseHandlers.history.updateWatchProgress(data.videoId, data.watchProgress)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_HISTORY, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE:
await baseHandlers.history.delete(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_HISTORY, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE_ALL:
await baseHandlers.history.deleteAll()
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_HISTORY, event, { event: '_', data })
return null
case DBActions.GENERAL.PERSIST:
baseHandlers.history.persist()
return null
default:
// eslint-disable-next-line no-throw-literal
throw 'invalid history db action'
}
} catch (err) {
if (typeof err === 'string') throw err
else throw err.toString()
}
})
// *********** //
// Profiles
ipcMain.handle(IpcChannels.DB_PROFILES, async (_, { action, data }) => {
try {
switch (action) {
case DBActions.GENERAL.CREATE:
await baseHandlers.profiles.create(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PROFILES, event, { event: '_', data })
return null
case DBActions.GENERAL.FIND:
return await baseHandlers.profiles.find()
case DBActions.GENERAL.UPSERT:
await baseHandlers.profiles.upsert(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PROFILES, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE:
await baseHandlers.profiles.delete(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PROFILES, event, { event: '_', data })
return null
case DBActions.GENERAL.PERSIST:
baseHandlers.profiles.persist()
return null
default:
// eslint-disable-next-line no-throw-literal
throw 'invalid profile db action'
}
} catch (err) {
if (typeof err === 'string') throw err
else throw err.toString()
}
})
// *********** //
// Playlists
ipcMain.handle(IpcChannels.DB_PLAYLISTS, async (_, { action, data }) => {
try {
switch (action) {
case DBActions.GENERAL.CREATE:
await baseHandlers.playlists.create(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.GENERAL.FIND:
return await baseHandlers.playlists.find()
case DBActions.PLAYLISTS.UPSERT_VIDEO:
await baseHandlers.playlists.upsertVideoByPlaylistName(data.playlistName, data.videoData)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.PLAYLISTS.UPSERT_VIDEO_IDS:
await baseHandlers.playlists.upsertVideoIdsByPlaylistId(data._id, data.videoIds)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE:
await baseHandlers.playlists.delete(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.PLAYLISTS.DELETE_VIDEO_ID:
await baseHandlers.playlists.deleteVideoIdByPlaylistName(data.playlistName, data.videoId)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.PLAYLISTS.DELETE_VIDEO_IDS:
await baseHandlers.playlists.deleteVideoIdsByPlaylistName(data.playlistName, data.videoIds)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.PLAYLISTS.DELETE_ALL_VIDEOS:
await baseHandlers.playlists.deleteAllVideosByPlaylistName(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE_MULTIPLE:
await baseHandlers.playlists.deleteMultiple(data)
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
case DBActions.GENERAL.DELETE_ALL:
await baseHandlers.playlists.deleteAll()
// TODO: Syncing
// syncOtherWindows(IpcChannels.SYNC_PLAYLISTS, event, { event: '_', data })
return null
default:
// eslint-disable-next-line no-throw-literal
throw 'invalid playlist db action'
}
} catch (err) {
if (typeof err === 'string') throw err
else throw err.toString()
}
})
// *********** //
function syncOtherWindows(channel, event, payload) {
const otherWindows = BrowserWindow.getAllWindows().filter((window) => {
return window.webContents.id !== event.sender.id
})
for (const window of otherWindows) {
window.webContents.send(channel, payload)
}
}
// ************************************************* //
app.once('window-all-closed', () => {
// Clear cache and storage if it's the last window
session.defaultSession.clearCache()

View File

@ -1,49 +0,0 @@
import Datastore from 'nedb-promises'
import { IpcChannels } from '../../constants'
// Initialize all datastores and export their references
// Current dbs:
// `settings.db`
// `profiles.db`
// `playlists.db`
// `history.db`
let buildFileName = null
// Check if using Electron
const usingElectron = window?.process?.type === 'renderer'
if (usingElectron) {
const { ipcRenderer } = require('electron')
const userDataPath = ipcRenderer.sendSync(IpcChannels.GET_USER_DATA_PATH_SYNC)
buildFileName = (dbName) => userDataPath + '/' + dbName + '.db'
} else {
buildFileName = (dbName) => dbName + '.db'
}
const settingsDb = Datastore.create({
filename: buildFileName('settings'),
autoload: true
})
const playlistsDb = Datastore.create({
filename: buildFileName('playlists'),
autoload: true
})
const profilesDb = Datastore.create({
filename: buildFileName('profiles'),
autoload: true
})
const historyDb = Datastore.create({
filename: buildFileName('history'),
autoload: true
})
export {
settingsDb,
profilesDb,
playlistsDb,
historyDb
}

View File

@ -1,4 +1,4 @@
import { historyDb } from '../datastores'
import { DBHistoryHandlers } from '../../../datastores/handlers/index'
const state = {
historyCache: []
@ -12,37 +12,52 @@ const getters = {
const actions = {
async grabHistory({ commit }) {
const results = await historyDb.find({}).sort({ timeWatched: -1 })
commit('setHistoryCache', results)
try {
const results = await DBHistoryHandlers.find()
commit('setHistoryCache', results)
} catch (errMessage) {
console.error(errMessage)
}
},
updateHistory({ commit }, record) {
historyDb.update(
{ videoId: record.videoId },
record,
{ upsert: true }
).catch(console.error)
commit('upsertToHistoryCache', record)
async updateHistory({ commit }, record) {
try {
await DBHistoryHandlers.upsert(record)
commit('upsertToHistoryCache', record)
} catch (errMessage) {
console.error(errMessage)
}
},
removeFromHistory({ commit }, videoId) {
historyDb.remove({ videoId: videoId }).catch(console.error)
commit('removeFromHistoryCacheById', videoId)
async removeFromHistory({ commit }, videoId) {
try {
await DBHistoryHandlers.delete(videoId)
commit('removeFromHistoryCacheById', videoId)
} catch (errMessage) {
console.error(errMessage)
}
},
removeAllHistory({ commit }) {
historyDb.remove({}, { multi: true }).catch(console.error)
commit('setHistoryCache', [])
async removeAllHistory({ commit }) {
try {
await DBHistoryHandlers.deleteAll()
commit('setHistoryCache', [])
} catch (errMessage) {
console.error(errMessage)
}
},
updateWatchProgress({ commit }, { videoId, watchProgress }) {
historyDb.update({ videoId }, { $set: { watchProgress } }, { upsert: true }).catch(console.error)
commit('updateRecordWatchProgressInHistoryCache', { videoId, watchProgress })
async updateWatchProgress({ commit }, { videoId, watchProgress }) {
try {
await DBHistoryHandlers.updateWatchProgress(videoId, watchProgress)
commit('updateRecordWatchProgressInHistoryCache', { videoId, watchProgress })
} catch (errMessage) {
console.error(errMessage)
}
},
compactHistory(_) {
historyDb.persistence.compactDatafile()
DBHistoryHandlers.persist()
}
}

View File

@ -1,4 +1,4 @@
import { playlistsDb } from '../datastores'
import { DBPlaylistHandlers } from '../../../datastores/handlers/index'
const state = {
playlists: [
@ -25,89 +25,111 @@ const getters = {
const actions = {
async addPlaylist({ commit }, payload) {
await playlistsDb.insert(payload)
commit('addPlaylist', payload)
try {
await DBPlaylistHandlers.create(payload)
commit('addPlaylist', payload)
} catch (errMessage) {
console.error(errMessage)
}
},
async addPlaylists({ commit }, payload) {
await playlistsDb.insert(payload)
commit('addPlaylists', payload)
try {
await DBPlaylistHandlers.create(payload)
commit('addPlaylists', payload)
} catch (errMessage) {
console.error(errMessage)
}
},
async addVideo({ commit }, payload) {
await playlistsDb.update(
{ playlistName: payload.playlistName },
{ $push: { videos: payload.videoData } },
{ upsert: true }
)
commit('addVideo', payload)
try {
const { playlistName, videoData } = payload
await DBPlaylistHandlers.upsertVideoByPlaylistName(playlistName, videoData)
commit('addVideo', payload)
} catch (errMessage) {
console.error(errMessage)
}
},
async addVideos({ commit }, payload) {
await playlistsDb.update(
{ _id: payload.playlistId },
{ $push: { videos: { $each: payload.videosIds } } },
{ upsert: true }
)
commit('addVideos', payload)
try {
const { playlistId, videoIds } = payload
await DBPlaylistHandlers.upsertVideoIdsByPlaylistId(playlistId, videoIds)
commit('addVideos', payload)
} catch (errMessage) {
console.error(errMessage)
}
},
async grabAllPlaylists({ commit, dispatch }) {
const payload = await playlistsDb.find({})
if (payload.length === 0) {
commit('setAllPlaylists', state.playlists)
dispatch('addPlaylists', payload)
} else {
commit('setAllPlaylists', payload)
async grabAllPlaylists({ commit, dispatch, state }) {
try {
const payload = await DBPlaylistHandlers.find()
if (payload.length === 0) {
commit('setAllPlaylists', state.playlists)
dispatch('addPlaylists', payload)
} else {
commit('setAllPlaylists', payload)
}
} catch (errMessage) {
console.error(errMessage)
}
},
async removeAllPlaylists({ commit }) {
await playlistsDb.remove({ protected: { $ne: true } })
commit('removeAllPlaylists')
try {
await DBPlaylistHandlers.deleteAll()
commit('removeAllPlaylists')
} catch (errMessage) {
console.error(errMessage)
}
},
async removeAllVideos({ commit }, playlistName) {
await playlistsDb.update(
{ playlistName: playlistName },
{ $set: { videos: [] } },
{ upsert: true }
)
commit('removeAllVideos', playlistName)
try {
await DBPlaylistHandlers.deleteAllVideosByPlaylistName(playlistName)
commit('removeAllVideos', playlistName)
} catch (errMessage) {
console.error(errMessage)
}
},
async removePlaylist({ commit }, playlistId) {
await playlistsDb.remove({
_id: playlistId,
protected: { $ne: true }
})
commit('removePlaylist', playlistId)
try {
await DBPlaylistHandlers.delete(playlistId)
commit('removePlaylist', playlistId)
} catch (errMessage) {
console.error(errMessage)
}
},
async removePlaylists({ commit }, playlistIds) {
await playlistsDb.remove({
_id: { $in: playlistIds },
protected: { $ne: true }
})
commit('removePlaylists', playlistIds)
try {
await DBPlaylistHandlers.deleteMultiple(playlistIds)
commit('removePlaylists', playlistIds)
} catch (errMessage) {
console.error(errMessage)
}
},
async removeVideo({ commit }, payload) {
await playlistsDb.update(
{ playlistName: payload.playlistName },
{ $pull: { videos: { videoId: payload.videoId } } },
{ upsert: true }
)
commit('removeVideo', payload)
try {
const { playlistName, videoId } = payload
await DBPlaylistHandlers.deleteVideoIdByPlaylistName(playlistName, videoId)
commit('removeVideo', payload)
} catch (errMessage) {
console.error(errMessage)
}
},
async removeVideos({ commit }, payload) {
await playlistsDb.update(
{ _id: payload.playlistName },
{ $pull: { videos: { $in: payload.videoId } } },
{ upsert: true }
)
commit('removeVideos', payload)
try {
const { playlistName, videoIds } = payload
await DBPlaylistHandlers.deleteVideoIdsByPlaylistName(playlistName, videoIds)
commit('removeVideos', payload)
} catch (errMessage) {
console.error(errMessage)
}
}
}

View File

@ -1,5 +1,5 @@
import { profilesDb } from '../datastores'
import { MAIN_PROFILE_ID } from '../../../constants'
import { DBProfileHandlers } from '../../../datastores/handlers/index'
const state = {
profileList: [{
@ -40,7 +40,14 @@ function profileSort(a, b) {
const actions = {
async grabAllProfiles({ rootState, dispatch, commit }, defaultName = null) {
let profiles = await profilesDb.find({}).catch(console.error)
let profiles
try {
profiles = await DBProfileHandlers.find()
} catch (errMessage) {
console.error(errMessage)
return
}
if (!Array.isArray(profiles)) return
if (profiles.length === 0) {
@ -55,8 +62,13 @@ const actions = {
subscriptions: []
}
await profilesDb.insert(defaultProfile).catch(console.error)
commit('setProfileList', [defaultProfile])
try {
await DBProfileHandlers.create(defaultProfile)
commit('setProfileList', [defaultProfile])
} catch (errMessage) {
console.error(errMessage)
}
return
}
@ -77,22 +89,26 @@ const actions = {
commit('setProfileList', profiles)
},
updateProfile({ commit }, profile) {
profilesDb.update(
{ _id: profile._id },
profile,
{ upsert: true }
).catch(console.error)
commit('upsertProfileToList', profile)
async updateProfile({ commit }, profile) {
try {
await DBProfileHandlers.upsert(profile)
commit('upsertProfileToList', profile)
} catch (errMessage) {
console.error(errMessage)
}
},
removeProfile({ commit }, profileId) {
profilesDb.remove({ _id: profileId }).catch(console.error)
commit('removeProfileFromList', profileId)
async removeProfile({ commit }, profileId) {
try {
await DBProfileHandlers.delete(profileId)
commit('removeProfileFromList', profileId)
} catch (errMessage) {
console.error(errMessage)
}
},
compactProfiles(_) {
profilesDb.persistence.compactDatafile()
DBProfileHandlers.persist()
},
updateActiveProfile({ commit }, id) {

View File

@ -1,6 +1,6 @@
import { settingsDb } from '../datastores'
import i18n from '../../i18n/index'
import { MAIN_PROFILE_ID, IpcChannels } from '../../../constants'
import { MAIN_PROFILE_ID, IpcChannels, SyncEvents } from '../../../constants'
import { DBSettingHandlers } from '../../../datastores/handlers/index'
/*
* Due to the complexity of the settings module in FreeTube, a more
@ -312,17 +312,18 @@ Object.assign(customGetters, {
const customActions = {
grabUserSettings: async ({ commit, dispatch, getters }) => {
const userSettings = await settingsDb.find({
_id: { $ne: 'bounds' }
})
try {
const userSettings = await DBSettingHandlers.find()
for (const setting of userSettings) {
const { _id, value } = setting
if (getters.settingHasSideEffects(_id)) {
dispatch(defaultSideEffectsTriggerId(_id), value)
}
for (const setting of userSettings) {
const { _id, value } = setting
if (getters.settingHasSideEffects(_id)) {
dispatch(defaultSideEffectsTriggerId(_id), value)
commit(defaultMutationId(_id), value)
}
commit(defaultMutationId(_id), value)
} catch (errMessage) {
console.error(errMessage)
}
},
@ -331,13 +332,19 @@ const customActions = {
// Already known to be Electron, no need to check
const { ipcRenderer } = require('electron')
ipcRenderer.on(IpcChannels.SYNC_SETTINGS, (_, payload) => {
// Payload is a single setting => { _id, value }
if (getters.settingHasSideEffects(payload._id)) {
dispatch(defaultSideEffectsTriggerId(payload._id), payload.value)
}
ipcRenderer.on(IpcChannels.SYNC_SETTINGS, (_, { event, data }) => {
switch (event) {
case SyncEvents.GENERAL.UPSERT:
if (getters.settingHasSideEffects(data._id)) {
dispatch(defaultSideEffectsTriggerId(data._id), data.value)
}
commit(defaultMutationId(payload._id), payload.value)
commit(defaultMutationId(data._id), data.value)
break
default:
console.error('settings: invalid sync event received')
}
})
ipcRenderer.on(IpcChannels.SYNC_HISTORY, (_, __) => {
@ -393,27 +400,16 @@ for (const settingId of Object.keys(state)) {
}
actions[updaterId] = async ({ commit, dispatch, getters }, value) => {
await settingsDb.update(
{ _id: settingId },
{ _id: settingId, value: value },
{ upsert: true }
)
try {
await DBSettingHandlers.upsert(settingId, value)
const {
getUsingElectron: usingElectron,
settingHasSideEffects
} = getters
if (getters.settingHasSideEffects(settingId)) {
dispatch(triggerId, value)
}
if (settingHasSideEffects(settingId)) {
dispatch(triggerId, value)
}
commit(mutationId, value)
if (usingElectron) {
const { ipcRenderer } = require('electron')
// Propagate settings to all other existing windows
ipcRenderer.send(IpcChannels.SYNC_SETTINGS, { _id: settingId, value: value })
commit(mutationId, value)
} catch (errMessage) {
console.error(errMessage)
}
}
}