Skip to content

Commit

Permalink
Sync and refresh auth token in BackgroundTask
Browse files Browse the repository at this point in the history
Fixes #157
  • Loading branch information
akdasa committed Feb 19, 2023
1 parent faf3aee commit 6f9a127
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 13 deletions.
3 changes: 2 additions & 1 deletion src/app/shared/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as DarkImage } from './DarkImage.vue'
export * from './tasks/RefreshTokenTask'
export * from './tasks/RefreshTokenTask'
export * from './tasks/SyncTask'
18 changes: 11 additions & 7 deletions src/app/shared/tasks/RefreshTokenTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,20 @@ import { AuthService } from '@/services/AuthService'
export function runRefreshTokenTask(emitter: Emitter<Events>) {
const service = new AuthService(AUTH_HOST)
const log = new Logger('auth')
const supportedPlatforms = ['ios', 'android']
const currentPlatform = Capacitor.getPlatform()

emitter.on('appStateChanged', async ({ isActive }) => {
if (isActive) { return }
if (Capacitor.getPlatform() !== 'ios') { return }

emitter.on('appStateChanged', async ({ isActive }) => {
if (isActive) { return }
if (supportedPlatforms.includes(currentPlatform)) {
const taskId = await BackgroundTask.beforeExit(async () => {
await refreshToken()
})
BackgroundTask.finish({ taskId })
})
} else {
await refreshToken()
}
})

async function refreshToken() {
const now = new Date().getTime()
Expand All @@ -33,9 +37,9 @@ export function runRefreshTokenTask(emitter: Emitter<Events>) {
const token = await service.refreshToken(account.token)
if (!token) { log.error('Failed to refresh token') }
account.token.expires = token.expires
log.debug('auth token refreshed', account.token)
log.debug('Auth token refreshed', account.token)
} else {
log.debug('token still valid')
log.debug('Token still valid')
}
}
}
37 changes: 37 additions & 0 deletions src/app/shared/tasks/SyncTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Logger } from '@akdasa-studios/framework'
import { Application } from '@akdasa-studios/shlokas-core'
import { Capacitor } from '@capacitor/core'
import { BackgroundTask } from '@capawesome/capacitor-background-task'
import { Emitter } from 'mitt'
import { createRepositories } from '@/app/utils/sync'
import { useAccountStore } from '@/app/settings'
import { Events } from '@/app/Events'


export function runSyncTask(app: Application, emitter: Emitter<Events>) {
const log = new Logger('sync')
const supportedPlatforms = ['ios', 'android']
const currentPlatform = Capacitor.getPlatform()

emitter.on('appStateChanged', async ({ isActive }) => {
if (isActive) { return }
if (supportedPlatforms.includes(currentPlatform)) {
const taskId = await BackgroundTask.beforeExit(async () => {
await sync()
})
BackgroundTask.finish({ taskId })
} else {
await sync()
}
})

async function sync() {
const account = useAccountStore()
if (account.syncHost) {
log.debug('Syncing in background')
const remoteRepos = createRepositories(account.syncHost as string)
await app.sync(remoteRepos)
emitter.emit('syncCompleted')
}
}
}
3 changes: 2 additions & 1 deletion src/init/app/initTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Emitter } from 'mitt'
import { runSyncInboxDeckTask } from '@/app/decks/inbox'
import { runSyncReviewDeckTask } from '@/app/decks/review'
import { Events } from '@/app/Events'
import { runRefreshTokenTask } from '@/app/shared'
import { runRefreshTokenTask, runSyncTask } from '@/app/shared'
import { runUpdateStatisticsTask } from '@/app/statistics'
import { InitArgs } from '../initialization'

Expand All @@ -15,4 +15,5 @@ export async function initTasks(
runUpdateStatisticsTask(shlokas, emitter)
runSyncInboxDeckTask(shlokas, emitter)
runSyncReviewDeckTask(shlokas, emitter)
runSyncTask(shlokas, emitter)
}
14 changes: 10 additions & 4 deletions src/init/infrastructure/initLogging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,20 @@ export async function initLogging() {

class ConsoleLogTransport implements LogTransport {
log(record: LogRecord): void {
const context = `[${record.context}]`
const data = record.data
const styles = {
context: 'color: #9E9E9E; font-weight: bold',
}

if (record.level === LogLevel.DEBUG) {
console.debug(record.context, record.message, JSON.stringify(record.data))
console.debug('%c'+context, styles.context, record.message, data)
} else if (record.level === LogLevel.INFO) {
console.info(record.context, record.message, JSON.stringify(record.data))
console.info('%c'+context, record.message, data)
} else if (record.level === LogLevel.WARN) {
console.warn(record.context, record.message, JSON.stringify(record.data))
console.warn('%c'+context, record.message, data)
} else if (record.level === LogLevel.ERROR || record.level === LogLevel.FATAL) {
console.error(record.context, record.message, JSON.stringify(record.data))
console.error('%c'+context, record.message, data)
}
}
}

0 comments on commit 6f9a127

Please sign in to comment.