Skip to content

Commit

Permalink
fix: migrate will occur an error & list manager error & etc.
Browse files Browse the repository at this point in the history
 - add missing locale fields
  • Loading branch information
cnwangjie committed Jan 29, 2019
1 parent 7c870ed commit 4efaf5a
Show file tree
Hide file tree
Showing 12 changed files with 127 additions and 208 deletions.
12 changes: 12 additions & 0 deletions src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,18 @@
"ui_unauth": {
"message": "Unauthorized"
},
"ui_turn_off": {
"message": "Turn off"
},
"ui_sync_setting": {
"message": "Sync Setting"
},
"ui_manage_account": {
"message": "Manage Account"
},
"ui_login": {
"message": "Login"
},
"ui_beta_warn": {
"message": "This is a feature in the test, if you find any problem please send me a feedback."
},
Expand Down
12 changes: 12 additions & 0 deletions src/_locales/zh_CN/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,18 @@
"ui_new_warn": {
"message": "这是当前版本的新特性。"
},
"ui_turn_off": {
"message": "停用"
},
"ui_sync_setting": {
"message": "同步设置"
},
"ui_manage_account": {
"message": "管理账户"
},
"ui_login": {
"message": "登录"
},
"ui_save_to_gdrive": {
"message": "将列表保存至 Google Drive"
},
Expand Down
1 change: 1 addition & 0 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ const init = async () => {
})
await migrate()
await boss.refresh()
boss.initTimer()
}

init()
2 changes: 2 additions & 0 deletions src/common/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export const AUTH_HEADER = 'auth'

export const END_FRONT = 'front'
export const END_BACKGROUND = 'background'

export const SYNC_SERVICE_URL = DEBUG ? 'http://127.0.0.1:3000' : 'https://boss.cnwangjie.com'
8 changes: 7 additions & 1 deletion src/common/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,17 @@ export const createNewTabList = ({tabs, title, time}) => ({
color: '',
})

export const validateList = list => {
if (list == null) return false
if (!Array.isArray(list.tabs)) return false
return true
}

// Preserving the needed properties before store lists.
export const normalizeList = list => {
const normalizedList = _.pick(list, PICKED_LIST_RPOPS)
normalizedList.tabs = normalizedList.tabs.map(normalizeTab)
return normalizedList
}

export default {createNewTabList, normalizeList}
export default {createNewTabList, normalizeList, validateList}
5 changes: 3 additions & 2 deletions src/common/listManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const getStorage = async () => {
return cache
}
const compressOps = ops => {
console.debug('[listManager] compress ops: (before)', ops)
const removed = []
const updated = {}
const finalOps = []
Expand Down Expand Up @@ -50,13 +51,13 @@ const compressOps = ops => {
finalOps.unshift(op)
}
}
console.debug('[listManager] compress ops: (after)', finalOps)
return finalOps
}
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})
}, 5000)
const manager = {}
// lists modifier (return true if need to add ops)
Expand Down Expand Up @@ -89,7 +90,7 @@ manager.modifiers = {
}
const applyChangesToStorage = async (method, args) => {
const {lists, ops} = await getStorage()
if (manager.modifiers[method](lists, args)) ops.push({method: name, args, time: Date.now()})
if (manager.modifiers[method](lists, args)) ops.push({method, args, time: Date.now()})
saveStorage()
}
const addEventListener = (receiveFrom, callback) => browser.runtime.onMessage.addListener(({listModifed, from}) => {
Expand Down
12 changes: 7 additions & 5 deletions src/common/migrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ const migrate = async () => {
if (version >= '1.4.0') return
// every list need an ID
const {lists} = await browser.storage.local.get('lists')
const {0: listsWithoutId, 1: listsWithId} = _.groupBy(lists.map(normalizeList), list => +!!list._id)
await browser.storage.local.set({lists: listsWithId})
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)
for (const list of listsWithoutId.reverse()) {
list._id = genObjectId()
await listManager.addList(list)
}
}
// remove depracated options
const {opts} = await browser.storage.local.get('opts')
Expand Down
66 changes: 38 additions & 28 deletions src/common/service/boss.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {
TOKEN_KEY,
AUTH_HEADER,
SYNC_SERVICE_URL,
} from '../constants'
import {isBackground} from '../utils'
import browser from 'webextension-polyfill'

const apiUrl = 'http://127.0.0.1:3000' // TODO: use online address
const apiUrl = SYNC_SERVICE_URL

const hasToken = async () => TOKEN_KEY in await browser.storage.local.get(TOKEN_KEY)

Expand Down Expand Up @@ -125,40 +126,47 @@ const applyRemoteOpts = async () => {

const refresh = async () => {
if (!(await hasToken())) return
const remoteInfo = await getInfo()
const localInfo = await browser.storage.local.get(['listsUpdatedAt', 'optsUpdatedAt'])
localInfo.listsUpdatedAt = localInfo.listsUpdatedAt || 0
localInfo.optsUpdatedAt = localInfo.optsUpdatedAt || 0
await browser.runtime.sendMessage({refreshing: true})
try {
const remoteInfo = await getInfo()
const localInfo = await browser.storage.local.get(['listsUpdatedAt', 'optsUpdatedAt'])
localInfo.listsUpdatedAt = localInfo.listsUpdatedAt || 0
localInfo.optsUpdatedAt = localInfo.optsUpdatedAt || 0

const {ops} = await browser.storage.local.get('ops')
if (remoteInfo.listsUpdatedAt === 0) {
const {listsUpdatedAt} = await uploadWholeLists()
await browser.storage.local.set({listsUpdatedAt})
} else if (ops && ops.length) {
// normal lists sync logic: apply local operations firstly
const {listsUpdatedAt} = await uploadOperations()
await browser.storage.local.set({listsUpdatedAt})
}
// apply remote lists if remote lists update time later than local
if (remoteInfo.listsUpdatedAt > localInfo.listsUpdatedAt) {
const {listsUpdatedAt} = await applyRemoteLists()
await browser.storage.local.set({listsUpdatedAt})
}

if (localInfo.optsUpdatedAt > remoteInfo.optsUpdatedAt) {
const {optsUpdatedAt} = await uploadOpts()
await browser.storage.local.set({optsUpdatedAt})
} else if (localInfo.optsUpdatedAt < remoteInfo.optsUpdatedAt) {
await applyRemoteOpts()
await browser.storage.local.set({optsUpdatedAt: remoteInfo.optsUpdatedAt})
const {ops} = await browser.storage.local.get('ops')
if (remoteInfo.listsUpdatedAt === 0) {
const {listsUpdatedAt} = await uploadWholeLists()
await browser.storage.local.set({listsUpdatedAt})
} else if (ops && ops.length) {
// normal lists sync logic: apply local operations firstly
const {listsUpdatedAt} = await uploadOperations()
await browser.storage.local.set({listsUpdatedAt})
}
// apply remote lists if remote lists update time later than local
if (remoteInfo.listsUpdatedAt > localInfo.listsUpdatedAt) {
const {listsUpdatedAt} = await applyRemoteLists()
await browser.storage.local.set({listsUpdatedAt})
}

if (localInfo.optsUpdatedAt > remoteInfo.optsUpdatedAt) {
const {optsUpdatedAt} = await uploadOpts()
await browser.storage.local.set({optsUpdatedAt})
} else if (localInfo.optsUpdatedAt < remoteInfo.optsUpdatedAt) {
await applyRemoteOpts()
await browser.storage.local.set({optsUpdatedAt: remoteInfo.optsUpdatedAt})
}
await browser.runtime.sendMessage({refreshed: {success: true}})
} catch (error) {
console.error(error)
await browser.runtime.sendMessage({refreshed: {success: false}})
}
await browser.runtime.sendMessage({refreshed: true})
}

const login = async token => {
if (await hasToken()) return
await setToken(token)
await getInfo()
const {uid} = await getInfo()
browser.runtime.sendMessage({logged: {uid}})
const loginNotificationId = 'login'
browser.notifications.create(loginNotificationId, {
type: 'basic',
Expand All @@ -183,7 +191,9 @@ const initTimer = async () => {

export default {
hasToken,
removeToken,
refresh,
login,
initTimer,
getInfo,
}
7 changes: 7 additions & 0 deletions src/common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,17 @@ export const readFile = file => new Promise((resolve, reject) => {
reader.readAsText(file)
})
export const genObjectId = () => {
// refer: https://gist.github.com/solenoid/1372386
const timestamp = (new Date().getTime() / 1000 | 0).toString(16)
return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, () => (Math.random() * 16 | 0).toString(16)).toLowerCase()
}
export const isBackground = async () => {
if (window._isBackground == null) window._isBackground = window === await browser.runtime.getBackgroundPage()
return window._isBackground
}
export const formatSize = bytes => {
// refer: https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string
const sufixes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(1024))
return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sufixes[i]
}
11 changes: 7 additions & 4 deletions src/component/main/Toolbar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import __ from '@/common/i18n'
import searchForm from './SearchForm'
import dynamicTime from '@/component/DynamicTime'
import browser from 'webextension-polyfill'
import {SYNC_SERVICE_URL} from '@/common/constants'
import {mapState, mapActions, mapMutations} from 'vuex'
export default {
Expand Down Expand Up @@ -73,12 +74,14 @@ export default {
window.addEventListener('online', () => { this.online = true })
window.addEventListener('offline', () => { this.online = false })
chrome.runtime.onMessage.addListener(msg => {
if (msg.refresh) {
if (msg.refreshing) {
this.syncing = true
} else if (msg.refreshed) {
this.syncing = false
this.uploadSuccess = true
setTimeout(() => { this.uploadSuccess = false }, 3000)
this.uploadSuccess = msg.refreshed.success
if (this.uploadSuccess) {
setTimeout(() => { this.uploadSuccess = false }, 3000)
}
}
})
},
Expand All @@ -87,7 +90,7 @@ export default {
},
syncBtnClicked() {
if (this.uploadSuccess) return
if (!this.hasToken) return browser.tabs.create({url: 'http://127.0.0.1:3000/login'})
if (!this.hasToken) return browser.tabs.create({url: SYNC_SERVICE_URL + '/login'})
return browser.runtime.sendMessage({refresh: true})
},
}
Expand Down
4 changes: 2 additions & 2 deletions src/content.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import browser from 'webextension-polyfill'
import {SYNC_SERVICE_URL} from './common/constants'
console.debug('content_script loaded')
const main = async () => {
const url = DEBUG ? 'http://127.0.0.1' : 'https://boss.cnwangjie.com'
if (!document.URL.startsWith(url)) return
if (!document.URL.startsWith(SYNC_SERVICE_URL)) return
const token = localStorage._BOSS_TOKEN
console.debug('token', token)
if (!token) return
Expand Down
Loading

0 comments on commit 4efaf5a

Please sign in to comment.