Skip to content

Commit

Permalink
perf: Lrucache move to background
Browse files Browse the repository at this point in the history
  • Loading branch information
Leon406 committed May 30, 2024
1 parent d5a31c3 commit 3af0f1b
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 81 deletions.
2 changes: 1 addition & 1 deletion public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"name": "__MSG_appName__",
"description": "__MSG_appDesc__",
"default_locale": "zh_CN",
"version": "0.4.2",
"version": "0.4.4",
"icons": {
"48": "assets/result48.png",
"128": "assets/icon_128.png"
Expand Down
56 changes: 48 additions & 8 deletions src/background.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { initContextMenus, make_default_online_dicts } from './context_menu_lib'
import { LRUCache } from 'lru-cache'

let gapi_loaded = false
let gapi_inited = false

const options = {
max: 100,
dispose: (value, key) => {
console.log('Cache Evict', key, value)
}
}

const cache = new LRUCache(options)
const cacheAudio = new LRUCache(options)


// TODO check chrome.runtime.lastError for all storage.local operations

function do_load_dictionary(file_text) {
Expand Down Expand Up @@ -428,22 +440,42 @@ function initialize_extension() {
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type === 'fetch') {
let cacheHtml = cache.get(request.q.toLowerCase())
console.log('request', request)
if (cacheHtml) {
console.log('request', 'cache bing ' + request.q)
sendResponse(cacheHtml)
return true
}
fetch(
`https://cn.bing.com/dict/clientsearch?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=${request.q}`
)
.then((response) => response.text())
.then(sendResponse)
.then(html=>{
cache.set(request.q.toLowerCase(), html)
sendResponse(html)
})
return true // Will respond asynchronously.
}
if (request.type === 'fetchArrayBuffer') {
console.log('request fetchArrayBuffer', request)
fetch(request.audioUrl)
.then((response) => response.arrayBuffer())
.then((buffer) => JSON.stringify({
data: Array.apply(null, new Uint8Array(buffer))
}))
.then(sendResponse)
let cached = cacheAudio.get(request.audioUrl)
if (cached) {
console.log('use Cache arraybuffer ' + request.audioUrl)
sendResponse(cached)
} else {
fetch(request.audioUrl)
.then((response) => response.arrayBuffer())
.then((buffer) => {
let jsonBuffer = JSON.stringify({
data: Array.apply(null, new Uint8Array(buffer))
})
cacheAudio.set(request.audioUrl, jsonBuffer)
return jsonBuffer
})
.then(sendResponse)
}

return true // Will respond asynchronously.
}
if (request.wdm_request === 'hostname') {
Expand Down Expand Up @@ -519,7 +551,15 @@ function initialize_extension() {
'wd_black_list',
'wd_white_list',
'wd_enable_tts'], function(result) {
let { wd_hl_settings, wd_enable_tts, wd_hover_settings ,wd_online_dicts,show_percents,black_list,white_list} = result
let {
wd_hl_settings,
wd_enable_tts,
wd_hover_settings,
wd_online_dicts,
show_percents,
black_list,
white_list
} = result
if (typeof wd_hl_settings === 'undefined') {
const word_hl_params = {
enabled: true,
Expand Down
120 changes: 48 additions & 72 deletions src/content_script.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import { add_lexeme, make_hl_style, make_id_suffix } from './common_lib'
import { handleLexResult } from './utils/bing'
import { LRUCache } from 'lru-cache'
import { get_dict_definition_url } from './context_menu_lib'

const options = {
max: 100,
dispose: (value, key) => {
console.log('Cache Evict', key, value)
}
}
import { get_dict_definition_url } from './context_menu_lib'

const cache = new LRUCache(options)
const cacheAudio = new LRUCache(options)

let dict_words = null
let dict_idioms = null
Expand Down Expand Up @@ -117,29 +108,22 @@ function play(audioUrl) {
new Audio(audioUrl).play()
.catch((e) => {
console.error(e)
let cached = cacheAudio.get(audioUrl)
if (cached) {
console.log('use Cache arraybuffer')
playArrayBuffer(cached)
} else {
chrome.runtime.sendMessage(
{
type: 'fetchArrayBuffer',
audioUrl
},
(res) => {
const arraybuffer = new Uint8Array(JSON.parse(res).data).buffer
cacheAudio.set(audioUrl, arraybuffer)
playArrayBuffer(arraybuffer)
}
)
}
chrome.runtime.sendMessage(
{
type: 'fetchArrayBuffer',
audioUrl
},
(res) => {
const arraybuffer = new Uint8Array(JSON.parse(res).data).buffer
playArrayBuffer(arraybuffer)
}
)
})
}

/**播放 ArrayBuffer 音频*/
function playArrayBuffer(arrayBuffer) {
var context = new AudioContext()
const context = new AudioContext()
context.decodeAudioData(arrayBuffer.slice(0), audioBuffer => { // `slice(0)`克隆一份(`decodeAudioData`后原数组清空)
const bufferSource = context.createBufferSource()
bufferSource.buffer = audioBuffer
Expand Down Expand Up @@ -176,8 +160,6 @@ function renderBubble() {
document.getElementById('wdn_translate_bing')
// 避免网络问题,显示上一次内容
wdnTranslateBingDom.innerHTML = ''
// 加入缓存,key为小写字母
let cacheResult = cache.get(wdSpanText.toLowerCase())

function bingHtml(bingResult) {
let inf_html = ''
Expand Down Expand Up @@ -209,55 +191,49 @@ function renderBubble() {
function errorHtml() {
const q = wdSpanText.toLowerCase()
const dict_html = `<div >Definition:
<a target="_blank" href="https://www.google.com/search?q=${q}+definition">Google</a>
</div>`
<a target="_blank" href="https://www.google.com/search?q=${q}+definition">Google</a>
</div>`
const pron_html = `<div>♫
<a target="_blank" href="https://youglish.com/search/${q}">
YouGlish</a>
<a target="_blank" href="https://www.playphrase.me/#/search?q=${q}">
PlayPhrase</a>
<a target="_blank" href="https://getyarn.io/yarn-find?text=${q}">
Yarn</a>
</div>`
<a target="_blank" href="https://youglish.com/search/${q}">
YouGlish</a>
<a target="_blank" href="https://www.playphrase.me/#/search?q=${q}">
PlayPhrase</a>
<a target="_blank" href="https://getyarn.io/yarn-find?text=${q}">
Yarn</a>
</div>`
wdnTranslateBingDom.innerHTML = dict_html + pron_html
}

if (cacheResult) {
console.log('use Cache', wdSpanText)
bingHtml(cacheResult)
} else {
chrome.runtime.sendMessage(
{
type: 'fetch',
q: wdSpanText
},
(res) => {
const doc = new DOMParser().parseFromString(res, 'text/html')
if (doc.querySelector('.client_def_hd_hd')) {
let lexResult = handleLexResult(
doc,
{
tense: true,
phsym: true,
cdef: true,
related: false,
sentence: 0
},
null
)
if (lexResult) {
const { result } = lexResult
cache.set(wdSpanText.toLowerCase(), result)
bingHtml(result)
} else {
errorHtml()
}
chrome.runtime.sendMessage(
{
type: 'fetch',
q: wdSpanText
},
(res) => {
const doc = new DOMParser().parseFromString(res, 'text/html')
if (doc.querySelector('.client_def_hd_hd')) {
let lexResult = handleLexResult(
doc,
{
tense: true,
phsym: true,
cdef: true,
related: false,
sentence: 0
},
null
)
if (lexResult) {
const { result } = lexResult
bingHtml(result)
} else {
errorHtml()
}
} else {
errorHtml()
}
)
}
}
)

bubbleText.textContent = limit_text_len(wdSpanText)
// if config third schema, use last one
Expand Down Expand Up @@ -708,7 +684,7 @@ function initForPage() {
[
'words_discoverer_eng_dict',
'wd_idioms',
'wd_user_vocabulary',
'wd_user_vocabulary'
],
function(result) {
dict_words = result.words_discoverer_eng_dict
Expand Down

0 comments on commit 3af0f1b

Please sign in to comment.