Skip to content

Commit

Permalink
fix: send extra message and error occur & migrate
Browse files Browse the repository at this point in the history
  • Loading branch information
cnwangjie committed Jan 29, 2019
1 parent 88400f6 commit 9f90941
Show file tree
Hide file tree
Showing 14 changed files with 114 additions and 63 deletions.
7 changes: 6 additions & 1 deletion src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import migrate from './common/migrate'
import boss from './common/service/boss'
import listManager from './common/listManager'
import browser from 'webextension-polyfill'
import {sendMessage} from './common/utils'

/* eslint-disable-next-line */
if (DEBUG && !MOZ) import(
Expand All @@ -27,6 +28,10 @@ if (DEBUG) {
window.listManager = listManager
window.boss = boss
browser.browserAction.setBadgeText({text: 'dev'})
import(
/* webpackChunkName: "helper", webpackMode: "lazy" */
'@/common/helper'
).then(helper => { window.helper = helper })
}

const getBrowserActionHandler = action => {
Expand Down Expand Up @@ -225,7 +230,7 @@ const init = async () => {
Object.assign(window.opts, changes)
if (changes.browserAction) updateBrowserAction(changes.browserAction)
if (['pageContext', 'allContext', 'disableDynamicMenu'].some(k => k in changes)) await setupContextMenus(changes)
await browser.runtime.sendMessage({optionsChangeHandledStatus: 'success'})
await sendMessage({optionsChangeHandledStatus: 'success'})
if (PRODUCTION) Object.keys(changes).map(key => ga('send', 'event', 'Options changed', key, changes[key]))
}
if (msg.restoreList) {
Expand Down
4 changes: 4 additions & 0 deletions src/common/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import browser from 'webextension-polyfill'

export const clearStorage = () => browser.storage.local.get()
.then(Object.keys).then(browser.storage.local.remove)
19 changes: 8 additions & 11 deletions src/common/listManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
REMOVE_LIST_BY_ID,
CHANGE_LIST_ORDER,
} from './constants'
import {isBackground} from './utils'
import {isBackground, sendMessage} from './utils'

const cache = { lists: null, ops: null }
let _readingStorage = false
Expand Down Expand Up @@ -75,7 +75,7 @@ const saveStorage = _.debounce(async () => {
cache.ops = compressOps(cache.ops)
await browser.storage.local.set(cache)
cache.lists = cache.ops = null
await browser.runtime.sendMessage({refresh: true})
await sendMessage({refresh: true})
}, 5000)
const manager = {}
// lists modifier (return true if need to add ops)
Expand Down Expand Up @@ -136,10 +136,10 @@ const genMethods = isBackground => {
manager[method] = isBackground ? async (...args) => { // for background
console.debug('[list manager] modify list:', method, ...args)
await applyChangesToStorage(method, args)
await browser.runtime.sendMessage({listModifed: {method, args}, from: END_BACKGROUND})
await sendMessage({listModifed: {method, args}, from: END_BACKGROUND})
} : async (...args) => { // for front end
console.debug('[list manager] call to modify list:', name, ...args)
await browser.runtime.sendMessage({listModifed: {method, args}, from: END_FRONT})
await sendMessage({listModifed: {method, args}, from: END_FRONT})
}
})
}
Expand All @@ -150,22 +150,19 @@ manager.init = async () => {
if (_isBackground) await addEventListener(END_FRONT, applyChangesToStorage)
genMethods(_isBackground)
}
const receiver = []
manager.receiveBackgroundModified = async lists => {
if (receiver.includes(lists)) return
receiver.push(lists)
await addEventListener(END_BACKGROUND, (method, args) => manager.modifiers[method](lists, args))
}
manager.mapMutations = () => {
const mutations = {}
Object.entries(manager.modifiers).forEach(([method, fn]) => {
mutations[method] = (state, payload) => fn(state.lists, payload)
})
mutations.receiveData = (state, {method, args}) => {
manager.modifiers[method](state.lists, args)
}
return mutations
}
manager.createVuexPlugin = () => store => {
addEventListener(END_BACKGROUND, (method, args) => {
store.commit(method, args)
store.commit('receiveData', {method, args})
})
browser.runtime.onMessage.addListener(({refreshed}) => {
if (refreshed && refreshed.success) store.dispatch('getLists')
Expand Down
56 changes: 35 additions & 21 deletions src/common/migrate.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,47 @@
import _ from 'lodash'
import {normalizeList} from './list'
import options from './options'
import {genObjectId} from './utils'
import logger from './logger'
import {genObjectId, compareVersion} from './utils'
import listManager from './listManager'
import browser from 'webextension-polyfill'
listManager.init()
const migrate = async () => {
const {version} = await browser.storage.local.get('version')
const {version: currentVersion} = browser.runtime.getManifest()
if (version !== currentVersion) await browser.storage.local.set({version: currentVersion})
if (version >= '1.4.0') return
// every list need an ID
const {lists} = await browser.storage.local.get('lists')
if (lists) {
const {0: listsWithoutId, 1: listsWithId} = _.groupBy(lists.map(normalizeList), list => +!!list._id)
if (listsWithId) await browser.storage.local.set({lists: listsWithId})

for (const list of listsWithoutId.reverse()) {
list._id = genObjectId()
await listManager.addList(list)
const migrations = {
'1.4.0': async () => {
// every list need an ID
const {lists} = await browser.storage.local.get('lists')
if (lists) {
const {0: listsWithoutId, 1: listsWithId} = _.groupBy(lists.map(normalizeList), list => +!!list._id)
if (listsWithId) await browser.storage.local.set({lists: listsWithId})

for (const list of listsWithoutId.reverse()) {
list._id = genObjectId()
await listManager.addList(list)
}
}
// remove deprecated storage keys
await browser.storage.local.remove(['conflict'])
}
// remove depracated options
const {opts} = await browser.storage.local.get('opts')
if (opts) {
await browser.storage.local.set({opts: _.pick(opts, _.keys(options.getDefaultOptions()))})
}

const migrate = async () => {
const {version: dataVersion} = await browser.storage.local.get('version')
const {version: currentVersion} = browser.runtime.getManifest()
if (dataVersion === currentVersion) return
const sorted = Object.keys(migrations).sort(compareVersion)
for (const v of sorted) {
if (compareVersion(currentVersion, v) > 0) continue
try {
console.debug('[migrate] migrating:', v)
await migrations[v]()
await browser.storage.local.set({version: v})
console.debug('[migrate] migrated to:', v)
} catch (err) {
logger.error('[migrate] migrate failed')
logger.error(err)
throw err
}
}
// remove deprecated storage keys
await browser.storage.local.remove(['conflict'])
}

export default migrate
4 changes: 2 additions & 2 deletions src/common/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ if (DEBUG) {
window.printOptionsMap = () => console.debug(availableOptionsList.map(i => i.name + ': ' + i.type.name + ',').join('\n'))
}


const getDefaultOptions = () => _.mapValues(_.keyBy(availableOptionsList, 'name'), i => i.default)
const _defaultOptions = _.mapValues(_.keyBy(availableOptionsList, 'name'), i => i.default)
const getDefaultOptions = () => _defaultOptions

export default {getDefaultOptions, optionsList: availableOptionsList}
10 changes: 5 additions & 5 deletions src/common/service/boss.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import _ from 'lodash'
import storage from '../storage'
import listManager from '../listManager'
import {isBackground, timeout} from '../utils'
import {isBackground, timeout, sendMessage} from '../utils'
import browser from 'webextension-polyfill'
import io from 'socket.io-client'
import logger from '../logger'
Expand Down Expand Up @@ -202,13 +202,13 @@ const refresh = async () => {
if (_refreshing || !(await hasToken())) return

_refreshing = true
await browser.runtime.sendMessage({refreshing: true})
await sendMessage({refreshing: true})
try {
await timeout(Promise.all([syncOptions(), syncLists()]), 20000)
await browser.runtime.sendMessage({refreshed: {success: true}})
await sendMessage({refreshed: {success: true}})
} catch (err) {
logger.error(err)
await browser.runtime.sendMessage({refreshed: {success: false}})
await sendMessage({refreshed: {success: false}})
} finally {
_refreshing = false
}
Expand All @@ -218,7 +218,7 @@ const login = async token => {
if (await hasToken()) return
await setToken(token)
const {uid} = await getInfo()
browser.runtime.sendMessage({logged: {uid}})
await sendMessage({logged: {uid}})
const loginNotificationId = 'login'
browser.notifications.create(loginNotificationId, {
type: 'basic',
Expand Down
6 changes: 5 additions & 1 deletion src/common/storage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import _ from 'lodash'
import {normalizeList} from '@/common/list'
import browser from 'webextension-polyfill'
import options from './options'

const get = key => browser.storage.local.get(key)

Expand All @@ -24,7 +25,10 @@ const setLists = async lists => {
const getOptions = () => get('opts')
.then(({opts}) => opts)

const setOptions = opts => set({opts, optsUpdatedAt: Date.now()})
const setOptions = opts => set({
opts: _.pick(opts, _.keys(options.getDefaultOptions())),
optsUpdatedAt: Date.now(),
})

export default {
getLists,
Expand Down
21 changes: 21 additions & 0 deletions src/common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,24 @@ export const timeout = (promise, ms) => Promise.race([
reject(new Error('promise timeout'))
}, ms))
])

export const compareVersion = (a, b) => {
if (a === b) return 0
const [ap, bp] = [a, b].map(i => i || '0').map(i => i.split('.').map(j => +j))
const len = Math.min(ap.length, bp.length)
for (let i = 0; i < len; i += 1) {
if (ap[i] !== bp[i]) return ap[i] - bp[i]
}
return ap.length - bp.length
}

export const sendMessage = async msg => {
try {
await browser.runtime.sendMessage(msg)
} catch (err) {
if (err.message === 'Could not establish connection. Receiving end does not exist.') {
return console.warn('error ignored', err.message)
}
throw err
}
}
13 changes: 9 additions & 4 deletions src/component/main/Drawer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
{{ __('ui_export_import') }}
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="openShortcutPage" :disabled="isFirefox">
<v-list-tile @click="openShortcutPage" :disabled="isLowFirefox">
<v-list-tile-action>
<v-icon>keyboard</v-icon>
</v-list-tile-action>
Expand Down Expand Up @@ -104,6 +104,7 @@ export default {
data() {
return {
isFirefox: false,
isLowFirefox: false,
}
},
computed: {
Expand All @@ -120,15 +121,19 @@ export default {
__,
async init() {
try {
const {name} = await browser.runtime.getBrowserInfo()
if (name === 'Firefox') this.isFirefox = true
const {name, version} = await browser.runtime.getBrowserInfo()
if (name === 'Firefox') {
this.isFirefox = true
if (version < '66') this.isLowFirefox = true
}
} catch (e) {
// ignored
}
this.preloadLists()
},
async openShortcutPage() {
await browser.tabs.create({url: 'chrome://extensions/shortcuts'})
if (this.isFirefox) await browser.tabs.create({url: 'about:addons'})
else await browser.tabs.create({url: 'chrome://extensions/shortcuts'})
},
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/component/main/Toolbar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import dynamicTime from '@/component/DynamicTime'
import browser from 'webextension-polyfill'
import {SYNC_SERVICE_URL} from '@/common/constants'
import {mapState, mapActions, mapMutations} from 'vuex'
import {sendMessage} from '@/common/utils'
export default {
data() {
Expand Down Expand Up @@ -88,7 +89,7 @@ export default {
syncBtnClicked() {
if (this.uploadSuccess) return
if (!this.hasToken) return browser.tabs.create({url: SYNC_SERVICE_URL + '/login'})
return browser.runtime.sendMessage({refresh: true})
return sendMessage({refresh: true})
},
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/content.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import browser from 'webextension-polyfill'
import {SYNC_SERVICE_URL} from './common/constants'
import {sendMessage} from './common/utils'

console.debug('content_script loaded')
const main = async () => {
if (!document.URL.startsWith(SYNC_SERVICE_URL)) return
const token = localStorage._BOSS_TOKEN
console.debug('token', token)
if (!token) return
await browser.runtime.sendMessage({login: {token}})
await sendMessage({login: {token}})
}

main()
Expand Down
16 changes: 7 additions & 9 deletions src/page/Popup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
<script>
import __ from '@/common/i18n'
import storage from '@/common/storage'
import {formatTime} from '@/common/utils'
import {formatTime, sendMessage} from '@/common/utils'
import browser from 'webextension-polyfill'
export default {
Expand Down Expand Up @@ -88,17 +88,15 @@ export default {
this.processed = true
},
clicked(index) {
if (['restore', 'restore-new-window'].includes(this.action)) {
chrome.runtime.sendMessage({restoreList: {
index,
newWindow: this.action === 'restore-new-window',
}})
} else return
if (!['restore', 'restore-new-window'].includes(this.action)) return
if (!this.lists[index].pinned) this.lists.splice(index, 1)
sendMessage({restoreList: {
index,
newWindow: this.action === 'restore-new-window',
}})
},
storeInto(index) {
browser.runtime.sendMessage({storeInto: {index}})
sendMessage({storeInto: {index}})
},
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/page/main/DetailList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ export default {
},
watch: {
// '$route.query.p': 'updateExpandStatus',
'listsToDisplay': 'updateExpandStatus',
listsToDisplay: 'updateExpandStatus',
// '$route.params.tag': 'setTagInView'
},
computed: {
Expand Down Expand Up @@ -460,10 +460,11 @@ export default {
},
async updateExpandStatus() {
await this.$nextTick()
if (this.opts.disableExpansion)
this.expandStatus = this.listsToDisplay.map(_ => true)
else
if (this.opts.disableExpansion) {
this.expandStatus = this.listsToDisplay.map(() => true)
} else {
this.expandStatus = this.getExpandStatus()
}
},
openTab(listIndex, tabIndex) {
tabs.openTab(this.lists[listIndex].tabs[tabIndex])
Expand Down
4 changes: 2 additions & 2 deletions src/page/main/Options.vue
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ import options from '@/common/options'
import __ from '@/common/i18n'
import _ from 'lodash'
import browser from 'webextension-polyfill'
import {formatTime} from '@/common/utils'
import {formatTime, sendMessage} from '@/common/utils'
import {mapState, mapMutations} from 'vuex'
const currentVersion = browser.runtime.getManifest().version
Expand Down Expand Up @@ -131,7 +131,7 @@ export default {
await storage.setOptions(this.opts) // eslint-disable-line
await storage.setOptions(this.opts) // eslint-disable-line
console.log(2)
chrome.runtime.sendMessage({optionsChanged: {[key]: value}})
await sendMessage({optionsChanged: {[key]: value}})
}, 100),
optionsChanged(key, value) {
this.setOption({[key]: value})
Expand Down

0 comments on commit 9f90941

Please sign in to comment.