Skip to content

Commit

Permalink
fix: get list after refresh & avoid update same list twice & etc.
Browse files Browse the repository at this point in the history
 - change sync timer
  • Loading branch information
cnwangjie committed Jan 29, 2019
1 parent 0d41ed6 commit 8a3a2f3
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 49 deletions.
32 changes: 12 additions & 20 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ import storage from './common/storage'
import options from './common/options'
import migrate from './common/migrate'
import boss from './common/service/boss'
import listManger from './common/listManager'
import listManager from './common/listManager'
import browser from 'webextension-polyfill'


/* eslint-disable-next-line */
if (DEBUG && !MOZ) import(
/* webpackChunkName: "autoreload", webpackMode: "lazy" */
Expand All @@ -24,7 +23,7 @@ if (PRODUCTION) import(
if (DEBUG) {
window.tabs = tabs
window.browser = browser
window.listManger = listManger
window.listManager = listManager
window.boss = boss
browser.browserAction.setBadgeText({text: 'dev'})
}
Expand Down Expand Up @@ -196,26 +195,19 @@ const setupContextMenus = _.debounce(async ({pageContext, allContext}) => {
dynamicDisableMenu()
}, 250)

const commandHandler = async command => {
const commandHandler = command => {
console.log('received command', command)
if (command === 'store-selected-tabs') tabs.storeSelectedTabs()
else if (command === 'store-all-tabs') tabs.storeAllTabs()
else if (command === 'store-all-in-all-windows') tabs.storeAllTabInAllWindows()
else if (command === 'restore-lastest-list') {
const lists = await storage.getLists()
if (lists.length === 0) return true
const [lastest] = lists
await tabs.restoreList(lastest)
if (lastest.pinned) return true
lists.shift()
return storage.setLists(lists)
} else if (command === 'open-lists') tabs.openTabLists()
else if (command === 'restore-lastest-list') tabs.restoreLastestList()
else if (command === 'open-lists') tabs.openTabLists()
else return true
if (PRODUCTION) ga('send', 'event', 'Command used', command)
}

const init = async () => {
await listManger.init()
await listManager.init()
const opts = window.opts = await storage.getOptions() || {}
_.defaults(opts, options.getDefaultOptions())
await storage.setOptions(opts)
Expand All @@ -237,14 +229,14 @@ const init = async () => {
const {restoreList} = msg
const listIndex = restoreList.index
const lists = await storage.getLists()
const list = lists[listIndex]
if (restoreList.newWindow) {
tabs.restoreListInNewWindow(lists[listIndex])
tabs.restoreListInNewWindow(list)
} else {
tabs.restoreList(lists[listIndex])
tabs.restoreList(list)
}
if (!lists[listIndex].pinned) {
lists.splice(listIndex, 1)
storage.setLists(lists)
if (!list.pinned) {
listManager.removeListById(list._id)
}
if (PRODUCTION) ga('send', 'event', 'Popup item clicked')
}
Expand All @@ -259,7 +251,7 @@ const init = async () => {
}
if (msg.import) {
const {lists} = msg.import
lists.forEach(list => listManger.addList(list))
lists.forEach(list => listManager.addList(list))
}
})
browser.runtime.onMessageExternal.addListener(commandHandler)
Expand Down
3 changes: 2 additions & 1 deletion src/common/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const COLORS = [
export const ILLEGAL_URLS = ['about:', 'chrome:', 'file:', 'wss:', 'ws:']

export const PICKED_TAB_PROPS = ['url', 'title', 'favIconUrl', 'pinned']
export const PICKED_LIST_RPOPS = ['_id', 'tabs', 'title', 'tags', 'time', 'pinned', 'expand', 'color']
export const PICKED_LIST_RPOPS = ['_id', 'tabs', 'title', 'tags', 'time', 'pinned', 'expand', 'color', 'updatedAt']
export const SYNCED_LIST_PROPS = ['_id', 'tabs', 'title', 'tags', 'time', 'pinned', 'color']

export const TOKEN_KEY = 'token'
Expand All @@ -18,6 +18,7 @@ export const END_BACKGROUND = 'background'

export const SYNC_SERVICE_URL = DEBUG ? 'http://127.0.0.1:3000' : 'https://boss.cnwangjie.com'
export const SYNC_MAX_INTERVAL = 864e5
export const SYNC_MIN_INTERVAL = 3e5

export const ADD_LIST = 'addList'
export const UPDATE_LIST_BY_ID = 'updateListById'
Expand Down
16 changes: 16 additions & 0 deletions src/common/listManager.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

declare class ListManager {
addList(list: object): Promise<void>
updateListById(listId: string, list: object, time?: number): Promise<void>
removeListById(listId: string): Promise<void>
changeListOrderRelatively(listId: string, diff: number): Promise<void>

init(): Promise<void>
mapMutations(): object
createVuexPlugin(): object
idle(): Promise<void>
}

declare const listManager: ListManager

export default listManager
3 changes: 3 additions & 0 deletions src/common/listManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ manager.createVuexPlugin = () => store => {
addEventListener(END_BACKGROUND, (method, args) => {
store.commit(method, args)
})
browser.runtime.onMessage.addListener(({refreshed}) => {
if (refreshed && refreshed.success) store.dispatch('getLists')
})
store.subscribe(({type, payload}) => {
if (type in manager.modifiers) {
manager[type](...payload)
Expand Down
44 changes: 27 additions & 17 deletions src/common/service/boss.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
AUTH_HEADER,
SYNC_SERVICE_URL,
SYNC_MAX_INTERVAL,
UPDATE_LIST_BY_ID,
SYNC_MIN_INTERVAL,
} from '../constants'
import _ from 'lodash'
import storage from '../storage'
Expand Down Expand Up @@ -228,23 +228,33 @@ const login = async token => {
await refresh()
}

const initTimer = () => {
window._nextSyncInterval = 6e4
window.addEventListener('offline', () => {
window._nextSyncInterval = SYNC_MAX_INTERVAL
})
window.addEventListener('online', () => {
window._nextSyncInterval = 6e4
})
const _nextTimer = () => {
setTimeout(() => {
_nextTimer()
getInfo() // for update token
if (window._socket && window._socket.connected) refresh()
else window._nextSyncInterval = Math.min(window._nextSyncInterval * 2, SYNC_MAX_INTERVAL)
}, window._nextSyncInterval)
const initTimer = async () => {
if (window._syncTimer || !(await isBackground())) return

const _nextTimer = time => {
window._syncTimer = setTimeout(async () => {
if (await hasToken()) {
getInfo() // for update token
if (window._socket && window._socket.connected) {
refresh()
return _nextTimer(time)
}
}
_nextTimer(Math.min(time * 2, SYNC_MAX_INTERVAL))
}, time)
}
_nextTimer()

const _refreshTimer = time => {
clearTimeout(window._syncTimer)
_nextTimer(time)
}

window.addEventListener('offline', () => _refreshTimer(SYNC_MAX_INTERVAL))
window.addEventListener('online', () => _refreshTimer(SYNC_MIN_INTERVAL))
browser.runtime.onMessage.addListener(({login, refreshed}) => {
if (login || refreshed && refreshed.success) window._nextSyncInterval = SYNC_MIN_INTERVAL
})
_nextTimer(SYNC_MIN_INTERVAL)
}

const init = async () => {
Expand Down
12 changes: 11 additions & 1 deletion src/common/tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const storeTabs = async (tabs, listIndex) => {
} else {
const list = lists[listIndex]
tabs.forEach(tab => list.tabs.push(tab))
await storage.setLists(lists._id, _.pick(list, 'tabs'))
await listManager.updateListById(lists._id, _.pick(list, 'tabs'))
}
if (opts.addHistory) {
for (let i = 0; i < tabs.length; i += 1) {
Expand Down Expand Up @@ -143,6 +143,15 @@ const restoreListInNewWindow = async list => {
})
}

const restoreLastestList = async () => {
const lists = await storage.getLists()
if (lists.length === 0) return true
const [lastest] = lists
await restoreList(lastest)
if (lastest.pinned) return true
return listManager.removeListById(lastest._id)
}

const openTab = tab => browser.tabs.create({ url: tab.url })

export default {
Expand All @@ -156,6 +165,7 @@ export default {
storeAllTabInAllWindows,
restoreList,
restoreListInNewWindow,
restoreLastestList,
openTab,
openTabLists,
openAboutPage,
Expand Down
13 changes: 3 additions & 10 deletions src/page/main/DetailList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -319,13 +319,10 @@ import draggable from 'vuedraggable'
import __ from '@/common/i18n'
import tabs from '@/common/tabs'
import {createNewTabList} from '@/common/list'
import listManager from '@/common/listManager'
import {formatTime, getColorByHash} from '@/common/utils'
import dynamicTime from '@/component/DynamicTime'
import browser from 'webextension-polyfill'
import {COLORS, ADD_LIST} from '@/common/constants'
import {COLORS} from '@/common/constants'
import {mapState, mapActions, mapMutations, mapGetters} from 'vuex'
if (DEBUG) window.listManager = listManager
export default {
data() {
Expand Down Expand Up @@ -399,7 +396,7 @@ export default {
getColorByHash,
...mapMutations([
'openChangeTitle', 'showAll', 'tabSelected', 'addTab',
'removeTabDirectly', 'setTitle',
'removeTabDirectly', 'setTitle', 'addList',
]),
...mapActions([
'showSnackbar', 'itemClicked', 'getLists', 'itemClicked',
Expand All @@ -417,10 +414,6 @@ export default {
if (this.$route.query.listIndex != null) this.jumpTo(this.$route.query)
}
})
listManager.init()
browser.runtime.onMessage.addListener(({refreshed}) => {
if (refreshed) this.getLists()
})
document.addEventListener('click', () => {
if (!this.currentHighlightItem) return
this.currentHighlightItem.$el.classList.remove('elevation-20')
Expand Down Expand Up @@ -489,7 +482,7 @@ export default {
if (targetListIndex === -1) {
const newList = createNewTabList({tabs})
this[ADD_LIST]([newList])
this.addList([newList])
this.tabMoved(changedLists.map(i => i + 1)) // it will create a new list
} else {
tabs.forEach(tab => this.addTab([targetListIndex, tab]))
Expand Down
1 change: 1 addition & 0 deletions src/store/lists.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export default {
},
saveTitle({commit, state}, listIndex) {
const list = state.lists[listIndex]
if (!list.titleEditing) return
commit('closeChangeTitle', listIndex)
commit(UPDATE_LIST_BY_ID, [list._id, _.pick(list, 'title')])
},
Expand Down

0 comments on commit 8a3a2f3

Please sign in to comment.