Skip to content

Commit

Permalink
feat(wordbook): add database for words
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed May 1, 2018
1 parent 310b198 commit 46c4327
Show file tree
Hide file tree
Showing 4 changed files with 197 additions and 3 deletions.
135 changes: 135 additions & 0 deletions src/background/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import Dexie from 'dexie'
import { storage } from '@/_helpers/browser-api'
import { SelectionInfo } from '@/_helpers/selection'
import {
MsgIsInNotebook,
MsgSaveWord,
MsgDeleteWord,
MsgGetWordsByText,
MsgGetAllWords,
} from '@/typings/message'

export interface Word {
/** primary key, milliseconds elapsed since the UNIX epoch */
date: number
/** word text */
text: string
/** the sentence where the text string is located */
context: string
/** page title */
title: string
/** page url */
url: string
/** favicon url */
favicon: string
/** translation */
trans: string
/** custom note */
note: string
}

export type Area = 'notebook' | 'history'

export class SaladictDB extends Dexie {
// @ts-ignore
notebook: Dexie.Table<Word, number>
// @ts-ignore
history: Dexie.Table<Word, number>

constructor () {
super('SaladictWords')

this.version(1).stores({
notebook: 'date,text,context,url',
history: 'date,text,context,url',
})
}
}

export const db = new SaladictDB()

/*-----------------------------------------------*\
Apis
\*-----------------------------------------------*/

export function isInNotebook ({ info }: MsgIsInNotebook) {
return db.notebook
.where('text')
.equals(info.text)
.count()
.then(count => count > 0)
}

export function saveWord ({ area, info }: MsgSaveWord) {
return db[area].put({
...info,
date: Date.now()
})
}

export function deleteWord ({ area, word }: MsgDeleteWord) {
return db[area].delete(word.date)
}

export function getWordsByText ({ area, text }: MsgGetWordsByText) {
return db[area]
.where('text')
.equals(text)
.toArray()
}

export function getAllWords ({ area, itemsPerPage, pageNum }: MsgGetAllWords) {
return db[area]
.orderBy('date')
.reverse()
.offset(itemsPerPage * (pageNum - 1))
.limit(itemsPerPage)
.toArray()
}

/*-----------------------------------------------*\
Init
\*-----------------------------------------------*/

// Populate data from old non-indexed db version
db.on('ready', () => {
return db.notebook.count(async count => {
if (count > 0) { return }

const { notebookCat } = await storage.local.get('notebookCat')
if (!notebookCat || !Array.isArray(notebookCat.data)) { return }
const sliceIDs = notebookCat.data

const dbSlices = await storage.local.get(sliceIDs)
const words: Word[] = []

sliceIDs.forEach(sliceID => {
const slice = dbSlices[sliceID]
if (!slice || !Array.isArray(slice.data)) { return }
slice.data.forEach(wordsGroupByDate => {
const { date, data } = wordsGroupByDate
const dateNum = new Date(`${date.slice(0, 2)}/${date.slice(2, 4)}/${date.slice(4)}`)
.getTime()
const oldWords = data.map((oldWord, i) => ({
date: dateNum + i,
text: oldWord.text || '',
context: oldWord.context || '',
title: oldWord.title || '',
favicon: (oldWord.favicon && !oldWord.favicon.startsWith('chrome')) ? oldWord.favicon : '',
url: oldWord.url || '',
trans: oldWord.trans || '',
note: oldWord.note || '',
}))
words.push(...oldWords)
})
})

browser.storage.local.clear()

return db.transaction('rw', db.notebook, () => {
return db.notebook.bulkAdd(words)
})
})
})

db.open()
4 changes: 2 additions & 2 deletions src/background/initialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ browser.runtime.onInstalled.addListener(onInstalled)
browser.runtime.onStartup.addListener(onStartup)
browser.notifications.onClicked.addListener(genClickListener('https://github.com/crimx/crx-saladict/wiki'))
if (browser.notifications.onButtonClicked) {
// Firefox don't support
// Firefox doesn't support
browser.notifications.onButtonClicked.addListener(genClickListener('https://github.com/crimx/crx-saladict/releases'))
}

Expand All @@ -21,7 +21,7 @@ function onInstalled ({ reason, previousVersion }: { reason: string, previousVer
// got previous config
return mergeConfig(config)
}
return Promise.all([storage.local.clear(), storage.sync.clear()])
return storage.sync.clear() // local get cleared by database
.then(() => {
openURL('https://github.com/crimx/crx-saladict/wiki/Instructions')
return mergeConfig()
Expand Down
24 changes: 23 additions & 1 deletion src/background/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import { message, openURL } from '@/_helpers/browser-api'
import { play } from './audio-manager'
import { isInNotebook, saveWord, deleteWord, getWordsByText, getAllWords } from './database'
import { chsToChz } from '@/_helpers/chs-to-chz'
import { MsgType, MsgOpenUrl, MsgAudioPlay, MsgFetchDictResult } from '@/typings/message'
import {
MsgType,
MsgOpenUrl,
MsgAudioPlay,
MsgFetchDictResult,
MsgIsInNotebook,
MsgSaveWord,
MsgDeleteWord,
MsgGetWordsByText,
MsgGetAllWords,
} from '@/typings/message'

message.self.initServer()

Expand All @@ -18,6 +29,17 @@ message.addListener((data, sender: browser.runtime.MessageSender) => {
return preloadSelection()
case MsgType.GetClipboard:
return getClipboard()

case MsgType.IsInNotebook:
return isInNotebook(data as MsgIsInNotebook)
case MsgType.SaveWord:
return saveWord(data as MsgSaveWord)
case MsgType.DeleteWord:
return deleteWord(data as MsgDeleteWord)
case MsgType.GetWordsByText:
return getWordsByText(data as MsgGetWordsByText)
case MsgType.GetAllWords:
return getAllWords(data as MsgGetAllWords)
}
})

Expand Down
37 changes: 37 additions & 0 deletions src/typings/message.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { SelectionInfo } from '@/_helpers/selection'
import { DictID } from '@/app-config'
import { Word, Area as DBArea } from '@/background/database'

export const enum MsgType {
/** Nothing */
Expand Down Expand Up @@ -27,6 +28,12 @@ export const enum MsgType {
/** Get clipboard content */
GetClipboard,

IsInNotebook,
SaveWord,
DeleteWord,
GetWordsByText,
GetAllWords,

/**
* Background proxy sends back underlyingly
*/
Expand Down Expand Up @@ -89,3 +96,33 @@ export interface MsgFetchDictResult {
readonly id: DictID
readonly text: string
}

export interface MsgIsInNotebook {
readonly type: MsgType.IsInNotebook
readonly info: SelectionInfo
}

export interface MsgSaveWord {
readonly type: MsgType.SaveWord
readonly area: DBArea
readonly info: SelectionInfo
}

export interface MsgDeleteWord {
readonly type: MsgType.DeleteWord
readonly area: DBArea
readonly word: Word
}

export interface MsgGetWordsByText {
readonly type: MsgType.GetWordsByText
readonly area: DBArea
readonly text: string
}

export interface MsgGetAllWords {
readonly type: MsgType.GetAllWords
readonly area: DBArea
readonly itemsPerPage: number
readonly pageNum: number
}

0 comments on commit 46c4327

Please sign in to comment.