Refactor session management to use a new "Agent" API (#165)
* Add the atp-agent implementation (temporarily in this repo) * Rewrite all session & API management to use the new atp-agent * Update tests for the atp-agent refactor * Refactor management of session-related state. Includes: - More careful management of when state is cleared or fetched - Debug logging to help trace future issues - Clearer APIs overall * Bubble session-expiration events to the user and display a toast to explain * Switch to the new @atproto/api@0.1.0
This commit is contained in:
@@ -14,6 +14,7 @@ import {MobileShell} from './view/shell/mobile'
|
||||
import {s} from './view/lib/styles'
|
||||
import notifee, {EventType} from '@notifee/react-native'
|
||||
import {segmentClient} from './lib/segmentClient'
|
||||
import * as Toast from './view/com/util/Toast'
|
||||
|
||||
const App = observer(() => {
|
||||
const [rootStore, setRootStore] = useState<RootStoreModel | undefined>(
|
||||
@@ -36,6 +37,9 @@ const App = observer(() => {
|
||||
Linking.addEventListener('url', ({url}) => {
|
||||
store.nav.handleLink(url)
|
||||
})
|
||||
store.onSessionDropped(() => {
|
||||
Toast.show('Sorry! Your session expired. Please log in again.')
|
||||
})
|
||||
notifee.onForegroundEvent(async ({type}: {type: EventType}) => {
|
||||
store.log.debug('Notifee foreground event', {type})
|
||||
if (type === EventType.PRESS) {
|
||||
|
||||
+4
-14
@@ -1,6 +1,6 @@
|
||||
import {autorun} from 'mobx'
|
||||
import {Platform} from 'react-native'
|
||||
import {sessionClient as SessionAtpApi} from '@atproto/api'
|
||||
import {AtpAgent} from '@atproto/api'
|
||||
import {RootStoreModel} from './models/root-store'
|
||||
import * as libapi from './lib/api'
|
||||
import * as storage from './lib/storage'
|
||||
@@ -19,8 +19,7 @@ export async function setupState(serviceUri = DEFAULT_SERVICE) {
|
||||
|
||||
libapi.doPolyfill()
|
||||
|
||||
const api = SessionAtpApi.service(serviceUri)
|
||||
rootStore = new RootStoreModel(api)
|
||||
rootStore = new RootStoreModel(new AtpAgent({service: serviceUri}))
|
||||
try {
|
||||
data = (await storage.load(ROOT_STATE_STORAGE_KEY)) || {}
|
||||
rootStore.log.debug('Initial hydrate', {hasSession: !!data.session})
|
||||
@@ -28,16 +27,7 @@ export async function setupState(serviceUri = DEFAULT_SERVICE) {
|
||||
} catch (e: any) {
|
||||
rootStore.log.error('Failed to load state from storage', e)
|
||||
}
|
||||
|
||||
rootStore.session
|
||||
.connect()
|
||||
.then(() => {
|
||||
rootStore.log.debug('Session connected')
|
||||
return rootStore.fetchStateUpdate()
|
||||
})
|
||||
.catch((e: any) => {
|
||||
rootStore.log.warn('Failed initial connect', e)
|
||||
})
|
||||
rootStore.attemptSessionResumption()
|
||||
|
||||
// track changes & save to storage
|
||||
autorun(() => {
|
||||
@@ -47,7 +37,7 @@ export async function setupState(serviceUri = DEFAULT_SERVICE) {
|
||||
|
||||
// periodic state fetch
|
||||
setInterval(() => {
|
||||
rootStore.fetchStateUpdate()
|
||||
rootStore.updateSessionState()
|
||||
}, STATE_FETCH_INTERVAL)
|
||||
|
||||
return rootStore
|
||||
|
||||
+15
-13
@@ -1,14 +1,4 @@
|
||||
/**
|
||||
* The environment is a place where services and shared dependencies between
|
||||
* models live. They are made available to every model via dependency injection.
|
||||
*/
|
||||
|
||||
// import {ReactNativeStore} from './auth'
|
||||
import AtpApi, {
|
||||
sessionClient as SessionAtpApi,
|
||||
AppBskyEmbedImages,
|
||||
AppBskyEmbedExternal,
|
||||
} from '@atproto/api'
|
||||
import AtpAgent, {AppBskyEmbedImages, AppBskyEmbedExternal} from '@atproto/api'
|
||||
import RNFS from 'react-native-fs'
|
||||
import {AtUri} from '../../third-party/uri'
|
||||
import {RootStoreModel} from '../models/root-store'
|
||||
@@ -20,8 +10,7 @@ import {Image} from '../../lib/images'
|
||||
const TIMEOUT = 10e3 // 10s
|
||||
|
||||
export function doPolyfill() {
|
||||
AtpApi.xrpc.fetch = fetchHandler
|
||||
SessionAtpApi.xrpc.fetch = fetchHandler
|
||||
AtpAgent.configure({fetch: fetchHandler})
|
||||
}
|
||||
|
||||
export interface ExternalEmbedDraft {
|
||||
@@ -31,6 +20,19 @@ export interface ExternalEmbedDraft {
|
||||
localThumb?: Image
|
||||
}
|
||||
|
||||
export async function resolveName(store: RootStoreModel, didOrHandle: string) {
|
||||
if (!didOrHandle) {
|
||||
throw new Error('Invalid handle: ""')
|
||||
}
|
||||
if (didOrHandle.startsWith('did:')) {
|
||||
return didOrHandle
|
||||
}
|
||||
const res = await store.api.com.atproto.handle.resolve({
|
||||
handle: didOrHandle,
|
||||
})
|
||||
return res.data.did
|
||||
}
|
||||
|
||||
export async function post(
|
||||
store: RootStoreModel,
|
||||
text: string,
|
||||
|
||||
@@ -258,6 +258,7 @@ export class FeedModel {
|
||||
* Nuke all data
|
||||
*/
|
||||
clear() {
|
||||
this.rootStore.log.debug('FeedModel:clear')
|
||||
this.isLoading = false
|
||||
this.isRefreshing = false
|
||||
this.hasNewLatest = false
|
||||
@@ -273,6 +274,7 @@ export class FeedModel {
|
||||
* Load for first render
|
||||
*/
|
||||
async setup(isRefreshing = false) {
|
||||
this.rootStore.log.debug('FeedModel:setup', {isRefreshing})
|
||||
if (isRefreshing) {
|
||||
this.isRefreshing = true // set optimistically for UI
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ export class MeModel {
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.mainFeed.clear()
|
||||
this.notifications.clear()
|
||||
this.did = ''
|
||||
this.handle = ''
|
||||
this.displayName = ''
|
||||
@@ -77,9 +79,10 @@ export class MeModel {
|
||||
|
||||
async load() {
|
||||
const sess = this.rootStore.session
|
||||
if (sess.hasSession && sess.data) {
|
||||
this.did = sess.data.did || ''
|
||||
this.handle = sess.data.handle
|
||||
this.rootStore.log.debug('MeModel:load', {hasSession: sess.hasSession})
|
||||
if (sess.hasSession) {
|
||||
this.did = sess.currentSession?.did || ''
|
||||
this.handle = sess.currentSession?.handle || ''
|
||||
const profile = await this.rootStore.api.app.bsky.actor.getProfile({
|
||||
actor: this.did,
|
||||
})
|
||||
@@ -94,11 +97,6 @@ export class MeModel {
|
||||
this.avatar = ''
|
||||
}
|
||||
})
|
||||
this.mainFeed.clear()
|
||||
this.mainFeed = new FeedModel(this.rootStore, 'home', {
|
||||
algorithm: 'reverse-chronological',
|
||||
})
|
||||
this.notifications = new NotificationsViewModel(this.rootStore, {})
|
||||
await Promise.all([
|
||||
this.mainFeed.setup().catch(e => {
|
||||
this.rootStore.log.error('Failed to setup main feed model', e)
|
||||
|
||||
@@ -234,10 +234,26 @@ export class NotificationsViewModel {
|
||||
// public api
|
||||
// =
|
||||
|
||||
/**
|
||||
* Nuke all data
|
||||
*/
|
||||
clear() {
|
||||
this.rootStore.log.debug('NotificationsModel:clear')
|
||||
this.isLoading = false
|
||||
this.isRefreshing = false
|
||||
this.hasLoaded = false
|
||||
this.error = ''
|
||||
this.hasMore = true
|
||||
this.loadMoreCursor = undefined
|
||||
this.notifications = []
|
||||
this.mostRecentNotification = undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Load for first render
|
||||
*/
|
||||
async setup(isRefreshing = false) {
|
||||
this.rootStore.log.debug('NotificationsModel:setup', {isRefreshing})
|
||||
if (isRefreshing) {
|
||||
this.isRefreshing = true // set optimistically for UI
|
||||
}
|
||||
@@ -299,7 +315,9 @@ export class NotificationsViewModel {
|
||||
|
||||
async getNewMostRecent(): Promise<NotificationsViewItemModel | undefined> {
|
||||
let old = this.mostRecentNotification
|
||||
const res = await this.rootStore.api.app.bsky.notification.list({limit: 1})
|
||||
const res = await this.rootStore.api.app.bsky.notification.list({
|
||||
limit: 1,
|
||||
})
|
||||
if (
|
||||
!res.data.notifications[0] ||
|
||||
old?.uri === res.data.notifications[0].uri
|
||||
|
||||
@@ -291,7 +291,7 @@ export class PostThreadViewModel {
|
||||
const urip = new AtUri(this.params.uri)
|
||||
if (!urip.host.startsWith('did:')) {
|
||||
try {
|
||||
urip.host = await this.rootStore.resolveName(urip.host)
|
||||
urip.host = await apilib.resolveName(this.rootStore, urip.host)
|
||||
} catch (e: any) {
|
||||
this.error = e.toString()
|
||||
}
|
||||
|
||||
@@ -31,7 +31,9 @@ export class ProfilesViewModel {
|
||||
}
|
||||
}
|
||||
try {
|
||||
const promise = this.rootStore.api.app.bsky.actor.getProfile({actor: did})
|
||||
const promise = this.rootStore.api.app.bsky.actor.getProfile({
|
||||
actor: did,
|
||||
})
|
||||
this.cache.set(did, promise)
|
||||
const res = await promise
|
||||
this.cache.set(did, res)
|
||||
|
||||
@@ -3,6 +3,7 @@ import {AtUri} from '../../third-party/uri'
|
||||
import {AppBskyFeedGetRepostedBy as GetRepostedBy} from '@atproto/api'
|
||||
import {RootStoreModel} from './root-store'
|
||||
import {cleanError} from '../../lib/strings'
|
||||
import * as apilib from '../lib/api'
|
||||
|
||||
const PAGE_SIZE = 30
|
||||
|
||||
@@ -93,7 +94,7 @@ export class RepostedByViewModel {
|
||||
const urip = new AtUri(this.params.uri)
|
||||
if (!urip.host.startsWith('did:')) {
|
||||
try {
|
||||
urip.host = await this.rootStore.resolveName(urip.host)
|
||||
urip.host = await apilib.resolveName(this.rootStore, urip.host)
|
||||
} catch (e: any) {
|
||||
this.error = e.toString()
|
||||
}
|
||||
|
||||
@@ -3,10 +3,7 @@
|
||||
*/
|
||||
|
||||
import {makeAutoObservable} from 'mobx'
|
||||
import {
|
||||
sessionClient as SessionAtpApi,
|
||||
SessionServiceClient,
|
||||
} from '@atproto/api'
|
||||
import {AtpAgent} from '@atproto/api'
|
||||
import {createContext, useContext} from 'react'
|
||||
import {DeviceEventEmitter, EmitterSubscription} from 'react-native'
|
||||
import BackgroundFetch from 'react-native-background-fetch'
|
||||
@@ -19,10 +16,9 @@ import {ProfilesViewModel} from './profiles-view'
|
||||
import {LinkMetasViewModel} from './link-metas-view'
|
||||
import {MeModel} from './me'
|
||||
import {OnboardModel} from './onboard'
|
||||
import {isNetworkError} from '../../lib/errors'
|
||||
|
||||
export class RootStoreModel {
|
||||
api: SessionServiceClient
|
||||
agent: AtpAgent
|
||||
log = new LogModel()
|
||||
session = new SessionModel(this)
|
||||
nav = new NavigationModel()
|
||||
@@ -32,62 +28,18 @@ export class RootStoreModel {
|
||||
profiles = new ProfilesViewModel(this)
|
||||
linkMetas = new LinkMetasViewModel(this)
|
||||
|
||||
constructor(api: SessionServiceClient) {
|
||||
this.api = api // to keep typescript from whining
|
||||
this.setAPI(api)
|
||||
constructor(agent: AtpAgent) {
|
||||
this.agent = agent
|
||||
makeAutoObservable(this, {
|
||||
api: false,
|
||||
resolveName: false,
|
||||
serialize: false,
|
||||
hydrate: false,
|
||||
})
|
||||
this.initBgFetch()
|
||||
}
|
||||
|
||||
setAPI(api: SessionServiceClient) {
|
||||
if (this.api) {
|
||||
this.api.sessionManager.removeAllListeners('session')
|
||||
}
|
||||
this.api = api
|
||||
this.api.sessionManager.on('session', this.onSessionChange.bind(this))
|
||||
}
|
||||
|
||||
onSessionChange() {
|
||||
if (!this.api.sessionManager.session && this.session.hasSession) {
|
||||
this.log.debug('Session invalidated, logging the user out')
|
||||
this.session.clear()
|
||||
} else if (this.api.sessionManager.session) {
|
||||
this.log.debug('Session refreshed, updating auth tokens')
|
||||
this.session.updateAuthTokens(this.api.sessionManager.session)
|
||||
}
|
||||
}
|
||||
|
||||
async resolveName(didOrHandle: string) {
|
||||
if (!didOrHandle) {
|
||||
throw new Error('Invalid handle: ""')
|
||||
}
|
||||
if (didOrHandle.startsWith('did:')) {
|
||||
return didOrHandle
|
||||
}
|
||||
const res = await this.api.com.atproto.handle.resolve({handle: didOrHandle})
|
||||
return res.data.did
|
||||
}
|
||||
|
||||
async fetchStateUpdate() {
|
||||
if (!this.session.hasSession) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (!this.session.online) {
|
||||
await this.session.connect()
|
||||
}
|
||||
await this.me.fetchNotifications()
|
||||
} catch (e: any) {
|
||||
if (isNetworkError(e)) {
|
||||
this.session.setOnline(false) // connection lost
|
||||
}
|
||||
this.log.error('Failed to fetch latest state', e)
|
||||
}
|
||||
get api() {
|
||||
return this.agent.api
|
||||
}
|
||||
|
||||
serialize(): unknown {
|
||||
@@ -124,12 +76,72 @@ export class RootStoreModel {
|
||||
}
|
||||
}
|
||||
|
||||
clearAll() {
|
||||
/**
|
||||
* Called during init to resume any stored session.
|
||||
*/
|
||||
async attemptSessionResumption() {
|
||||
this.log.debug('RootStoreModel:attemptSessionResumption')
|
||||
try {
|
||||
await this.session.attemptSessionResumption()
|
||||
this.log.debug('Session initialized', {
|
||||
hasSession: this.session.hasSession,
|
||||
})
|
||||
this.updateSessionState()
|
||||
} catch (e: any) {
|
||||
this.log.warn('Failed to initialize session', e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the session model. Refreshes session-oriented state.
|
||||
*/
|
||||
async handleSessionChange(agent: AtpAgent) {
|
||||
this.log.debug('RootStoreModel:handleSessionChange')
|
||||
this.agent = agent
|
||||
this.nav.clear()
|
||||
this.me.clear()
|
||||
await this.me.load()
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by the session model. Handles session drops by informing the user.
|
||||
*/
|
||||
async handleSessionDrop() {
|
||||
this.log.debug('RootStoreModel:handleSessionDrop')
|
||||
this.nav.clear()
|
||||
this.me.clear()
|
||||
this.emitSessionDropped()
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all session-oriented state.
|
||||
*/
|
||||
clearAllSessionState() {
|
||||
this.log.debug('RootStoreModel:clearAllSessionState')
|
||||
this.session.clear()
|
||||
this.nav.clear()
|
||||
this.me.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Periodic poll for new session state.
|
||||
*/
|
||||
async updateSessionState() {
|
||||
if (!this.session.hasSession) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await this.me.fetchNotifications()
|
||||
} catch (e: any) {
|
||||
this.log.error('Failed to fetch latest state', e)
|
||||
}
|
||||
}
|
||||
|
||||
// global event bus
|
||||
// =
|
||||
// - some events need to be passed around between views and models
|
||||
// in order to keep state in sync; these methods are for that
|
||||
|
||||
onPostDeleted(handler: (uri: string) => void): EmitterSubscription {
|
||||
return DeviceEventEmitter.addListener('post-deleted', handler)
|
||||
}
|
||||
@@ -138,6 +150,14 @@ export class RootStoreModel {
|
||||
DeviceEventEmitter.emit('post-deleted', uri)
|
||||
}
|
||||
|
||||
onSessionDropped(handler: () => void): EmitterSubscription {
|
||||
return DeviceEventEmitter.addListener('session-dropped', handler)
|
||||
}
|
||||
|
||||
emitSessionDropped() {
|
||||
DeviceEventEmitter.emit('session-dropped')
|
||||
}
|
||||
|
||||
// background fetch
|
||||
// =
|
||||
// - we use this to poll for unread notifications, which is not "ideal" behavior but
|
||||
@@ -172,7 +192,7 @@ export class RootStoreModel {
|
||||
}
|
||||
|
||||
const throwawayInst = new RootStoreModel(
|
||||
SessionAtpApi.service('http://localhost'),
|
||||
new AtpAgent({service: 'http://localhost'}),
|
||||
) // this will be replaced by the loader, we just need to supply a value at init
|
||||
const RootStoreContext = createContext<RootStoreModel>(throwawayInst)
|
||||
export const RootStoreProvider = RootStoreContext.Provider
|
||||
|
||||
+186
-199
@@ -1,24 +1,22 @@
|
||||
import {makeAutoObservable, runInAction} from 'mobx'
|
||||
import AtpApi, {
|
||||
sessionClient as SessionAtpApi,
|
||||
Session,
|
||||
import {makeAutoObservable} from 'mobx'
|
||||
import {
|
||||
AtpAgent,
|
||||
AtpSessionEvent,
|
||||
AtpSessionData,
|
||||
ComAtprotoServerGetAccountsConfig as GetAccountsConfig,
|
||||
} from '@atproto/api'
|
||||
import normalizeUrl from 'normalize-url'
|
||||
import {isObj, hasProp} from '../lib/type-guards'
|
||||
import {z} from 'zod'
|
||||
import {RootStoreModel} from './root-store'
|
||||
import {isNetworkError} from '../../lib/errors'
|
||||
|
||||
export type ServiceDescription = GetAccountsConfig.OutputSchema
|
||||
|
||||
export const sessionData = z.object({
|
||||
export const activeSession = z.object({
|
||||
service: z.string(),
|
||||
refreshJwt: z.string(),
|
||||
accessJwt: z.string(),
|
||||
handle: z.string(),
|
||||
did: z.string(),
|
||||
})
|
||||
export type SessionData = z.infer<typeof sessionData>
|
||||
export type ActiveSession = z.infer<typeof activeSession>
|
||||
|
||||
export const accountData = z.object({
|
||||
service: z.string(),
|
||||
@@ -31,18 +29,20 @@ export const accountData = z.object({
|
||||
})
|
||||
export type AccountData = z.infer<typeof accountData>
|
||||
|
||||
interface AdditionalAccountData {
|
||||
displayName?: string
|
||||
aviUrl?: string
|
||||
}
|
||||
|
||||
export class SessionModel {
|
||||
/**
|
||||
* Current session data
|
||||
* Currently-active session
|
||||
*/
|
||||
data: SessionData | null = null
|
||||
data: ActiveSession | null = null
|
||||
/**
|
||||
* A listing of the currently & previous sessions, used for account switching
|
||||
* A listing of the currently & previous sessions
|
||||
*/
|
||||
accounts: AccountData[] = []
|
||||
online = false
|
||||
attemptingConnect = false
|
||||
private _connectPromise: Promise<boolean> | undefined
|
||||
|
||||
constructor(public rootStore: RootStoreModel) {
|
||||
makeAutoObservable(this, {
|
||||
@@ -52,8 +52,22 @@ export class SessionModel {
|
||||
})
|
||||
}
|
||||
|
||||
get currentSession() {
|
||||
if (!this.data) {
|
||||
return undefined
|
||||
}
|
||||
const {did, service} = this.data
|
||||
return this.accounts.find(
|
||||
account =>
|
||||
normalizeUrl(account.service) === normalizeUrl(service) &&
|
||||
account.did === did &&
|
||||
!!account.accessJwt &&
|
||||
!!account.refreshJwt,
|
||||
)
|
||||
}
|
||||
|
||||
get hasSession() {
|
||||
return this.data !== null
|
||||
return !!this.currentSession && !!this.rootStore.agent.session
|
||||
}
|
||||
|
||||
get hasAccounts() {
|
||||
@@ -74,8 +88,8 @@ export class SessionModel {
|
||||
hydrate(v: unknown) {
|
||||
this.accounts = []
|
||||
if (isObj(v)) {
|
||||
if (hasProp(v, 'data') && sessionData.safeParse(v.data)) {
|
||||
this.data = v.data as SessionData
|
||||
if (hasProp(v, 'data') && activeSession.safeParse(v.data)) {
|
||||
this.data = v.data as ActiveSession
|
||||
}
|
||||
if (hasProp(v, 'accounts') && Array.isArray(v.accounts)) {
|
||||
for (const account of v.accounts) {
|
||||
@@ -89,93 +103,91 @@ export class SessionModel {
|
||||
|
||||
clear() {
|
||||
this.data = null
|
||||
this.setOnline(false)
|
||||
}
|
||||
|
||||
setState(data: SessionData) {
|
||||
this.data = data
|
||||
this.addSessionToAccounts()
|
||||
}
|
||||
|
||||
setOnline(online: boolean, attemptingConnect?: boolean) {
|
||||
this.online = online
|
||||
if (typeof attemptingConnect === 'boolean') {
|
||||
this.attemptingConnect = attemptingConnect
|
||||
}
|
||||
}
|
||||
|
||||
updateAuthTokens(session: Session) {
|
||||
if (this.data) {
|
||||
this.setState({
|
||||
...this.data,
|
||||
accessJwt: session.accessJwt,
|
||||
refreshJwt: session.refreshJwt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the XRPC API, must be called before connecting to a service
|
||||
* Attempts to resume the previous session loaded from storage
|
||||
*/
|
||||
private configureApi(): boolean {
|
||||
if (!this.data) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const serviceUri = new URL(this.data.service)
|
||||
const api = SessionAtpApi.service(serviceUri)
|
||||
api.sessionManager.set({
|
||||
refreshJwt: this.data.refreshJwt,
|
||||
accessJwt: this.data.accessJwt,
|
||||
})
|
||||
this.rootStore.setAPI(api)
|
||||
} catch (e: any) {
|
||||
this.rootStore.log.error(
|
||||
`Invalid service URL: ${this.data.service}. Resetting session.`,
|
||||
e,
|
||||
async attemptSessionResumption() {
|
||||
const sess = this.currentSession
|
||||
if (sess) {
|
||||
this.rootStore.log.debug(
|
||||
'SessionModel:attemptSessionResumption found stored session',
|
||||
)
|
||||
return this.resumeSession(sess)
|
||||
} else {
|
||||
this.rootStore.log.debug(
|
||||
'SessionModel:attemptSessionResumption has no session to resume',
|
||||
)
|
||||
this.clear()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts the current session into the accounts
|
||||
* Sets the active session
|
||||
*/
|
||||
private addSessionToAccounts() {
|
||||
if (!this.data) {
|
||||
return
|
||||
setActiveSession(agent: AtpAgent, did: string) {
|
||||
this.rootStore.log.debug('SessionModel:setActiveSession')
|
||||
this.data = {
|
||||
service: agent.service.toString(),
|
||||
did,
|
||||
}
|
||||
this.rootStore.handleSessionChange(agent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts a session into the accounts
|
||||
*/
|
||||
private persistSession(
|
||||
service: string,
|
||||
did: string,
|
||||
event: AtpSessionEvent,
|
||||
session?: AtpSessionData,
|
||||
addedInfo?: AdditionalAccountData,
|
||||
) {
|
||||
this.rootStore.log.debug('SessionModel:persistSession', {
|
||||
service,
|
||||
did,
|
||||
event,
|
||||
hasSession: !!session,
|
||||
})
|
||||
|
||||
// upsert the account in our listing
|
||||
const existingAccount = this.accounts.find(
|
||||
acc => acc.service === this.data?.service && acc.did === this.data.did,
|
||||
account => account.service === service && account.did === did,
|
||||
)
|
||||
const newAccount = {
|
||||
service: this.data.service,
|
||||
refreshJwt: this.data.refreshJwt,
|
||||
accessJwt: this.data.accessJwt,
|
||||
handle: this.data.handle,
|
||||
did: this.data.did,
|
||||
displayName: this.rootStore.me.displayName,
|
||||
aviUrl: this.rootStore.me.avatar,
|
||||
service,
|
||||
did,
|
||||
refreshJwt: session?.refreshJwt,
|
||||
accessJwt: session?.accessJwt,
|
||||
handle: session?.handle || existingAccount?.handle || '',
|
||||
displayName: addedInfo
|
||||
? addedInfo.displayName
|
||||
: existingAccount?.displayName || '',
|
||||
aviUrl: addedInfo ? addedInfo.aviUrl : existingAccount?.aviUrl || '',
|
||||
}
|
||||
if (!existingAccount) {
|
||||
this.accounts.push(newAccount)
|
||||
} else {
|
||||
this.accounts = this.accounts
|
||||
.filter(
|
||||
acc =>
|
||||
!(acc.service === this.data?.service && acc.did === this.data.did),
|
||||
)
|
||||
.concat([newAccount])
|
||||
this.accounts = [
|
||||
newAccount,
|
||||
...this.accounts.filter(
|
||||
account => !(account.service === service && account.did === did),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
// if the session expired, fire an event to let the user know
|
||||
if (event === 'expired') {
|
||||
this.rootStore.handleSessionDrop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears any session tokens from the accounts; used on logout.
|
||||
*/
|
||||
private clearSessionTokensFromAccounts() {
|
||||
private clearSessionTokens() {
|
||||
this.rootStore.log.debug('SessionModel:clearSessionTokens')
|
||||
this.accounts = this.accounts.map(acct => ({
|
||||
service: acct.service,
|
||||
handle: acct.handle,
|
||||
@@ -186,59 +198,73 @@ export class SessionModel {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the current session from the service, if possible.
|
||||
* Requires an existing session (.data) to be populated with access tokens.
|
||||
* Fetches additional information about an account on load.
|
||||
*/
|
||||
async connect(): Promise<boolean> {
|
||||
if (this._connectPromise) {
|
||||
return this._connectPromise
|
||||
}
|
||||
this._connectPromise = this._connect()
|
||||
const res = await this._connectPromise
|
||||
this._connectPromise = undefined
|
||||
return res
|
||||
}
|
||||
|
||||
private async _connect(): Promise<boolean> {
|
||||
this.attemptingConnect = true
|
||||
if (!this.configureApi()) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const sess = await this.rootStore.api.com.atproto.session.get()
|
||||
if (sess.success && this.data && this.data.did === sess.data.did) {
|
||||
this.setOnline(true, false)
|
||||
if (this.rootStore.me.did !== sess.data.did) {
|
||||
this.rootStore.me.clear()
|
||||
}
|
||||
this.rootStore.me.load().then(() => {
|
||||
this.addSessionToAccounts()
|
||||
})
|
||||
return true // success
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (isNetworkError(e)) {
|
||||
this.setOnline(false, false) // connection issue
|
||||
return false
|
||||
} else {
|
||||
this.clear() // invalid session cached
|
||||
private async loadAccountInfo(agent: AtpAgent, did: string) {
|
||||
const res = await agent.api.app.bsky.actor
|
||||
.getProfile({actor: did})
|
||||
.catch(_e => undefined)
|
||||
if (res) {
|
||||
return {
|
||||
dispayName: res.data.displayName,
|
||||
aviUrl: res.data.avatar,
|
||||
}
|
||||
}
|
||||
|
||||
this.setOnline(false, false)
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to fetch the accounts config settings from an account.
|
||||
*/
|
||||
async describeService(service: string): Promise<ServiceDescription> {
|
||||
const api = AtpApi.service(service)
|
||||
const res = await api.com.atproto.server.getAccountsConfig({})
|
||||
const agent = new AtpAgent({service})
|
||||
const res = await agent.api.com.atproto.server.getAccountsConfig({})
|
||||
return res.data
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to resume a session that we still have access tokens for.
|
||||
*/
|
||||
async resumeSession(account: AccountData): Promise<boolean> {
|
||||
this.rootStore.log.debug('SessionModel:resumeSession')
|
||||
if (!(account.accessJwt && account.refreshJwt && account.service)) {
|
||||
this.rootStore.log.debug(
|
||||
'SessionModel:resumeSession aborted due to lack of access tokens',
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
const agent = new AtpAgent({
|
||||
service: account.service,
|
||||
persistSession: (evt: AtpSessionEvent, sess?: AtpSessionData) => {
|
||||
this.persistSession(account.service, account.did, evt, sess)
|
||||
},
|
||||
})
|
||||
try {
|
||||
await agent.resumeSession({
|
||||
accessJwt: account.accessJwt,
|
||||
refreshJwt: account.refreshJwt,
|
||||
did: account.did,
|
||||
handle: account.handle,
|
||||
})
|
||||
const addedInfo = await this.loadAccountInfo(agent, account.did)
|
||||
this.persistSession(
|
||||
account.service,
|
||||
account.did,
|
||||
'create',
|
||||
agent.session,
|
||||
addedInfo,
|
||||
)
|
||||
this.rootStore.log.debug('SessionModel:resumeSession succeeded')
|
||||
} catch (e: any) {
|
||||
this.rootStore.log.debug('SessionModel:resumeSession failed', {
|
||||
error: e.toString(),
|
||||
})
|
||||
return false
|
||||
}
|
||||
this.setActiveSession(agent, account.did)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session.
|
||||
*/
|
||||
@@ -251,66 +277,22 @@ export class SessionModel {
|
||||
identifier: string
|
||||
password: string
|
||||
}) {
|
||||
const api = AtpApi.service(service)
|
||||
const res = await api.com.atproto.session.create({identifier, password})
|
||||
if (res.data.accessJwt && res.data.refreshJwt) {
|
||||
this.setState({
|
||||
service: service,
|
||||
accessJwt: res.data.accessJwt,
|
||||
refreshJwt: res.data.refreshJwt,
|
||||
handle: res.data.handle,
|
||||
did: res.data.did,
|
||||
})
|
||||
this.configureApi()
|
||||
this.setOnline(true, false)
|
||||
this.rootStore.me.load().then(() => {
|
||||
this.addSessionToAccounts()
|
||||
})
|
||||
this.rootStore.log.debug('SessionModel:login')
|
||||
const agent = new AtpAgent({service})
|
||||
await agent.login({identifier, password})
|
||||
if (!agent.session) {
|
||||
throw new Error('Failed to establish session')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to resume a session that we still have access tokens for.
|
||||
*/
|
||||
async resumeSession(account: AccountData): Promise<boolean> {
|
||||
if (!(account.accessJwt && account.refreshJwt && account.service)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// test that the session is good
|
||||
const api = SessionAtpApi.service(account.service)
|
||||
api.sessionManager.set({
|
||||
refreshJwt: account.refreshJwt,
|
||||
accessJwt: account.accessJwt,
|
||||
})
|
||||
try {
|
||||
const sess = await api.com.atproto.session.get()
|
||||
if (
|
||||
!sess.success ||
|
||||
sess.data.did !== account.did ||
|
||||
!api.sessionManager.session
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// copy over the access tokens, as they may have refreshed during the .get() above
|
||||
runInAction(() => {
|
||||
account.refreshJwt = api.sessionManager.session?.refreshJwt
|
||||
account.accessJwt = api.sessionManager.session?.accessJwt
|
||||
})
|
||||
} catch (_e) {
|
||||
return false
|
||||
}
|
||||
|
||||
// session is good, connect
|
||||
this.setState({
|
||||
service: account.service,
|
||||
accessJwt: account.accessJwt,
|
||||
refreshJwt: account.refreshJwt,
|
||||
handle: account.handle,
|
||||
did: account.did,
|
||||
})
|
||||
return this.connect()
|
||||
const did = agent.session.did
|
||||
const addedInfo = await this.loadAccountInfo(agent, did)
|
||||
this.persistSession(service, did, 'create', agent.session, addedInfo)
|
||||
agent.setPersistSessionHandler(
|
||||
(evt: AtpSessionEvent, sess?: AtpSessionData) => {
|
||||
this.persistSession(service, did, evt, sess)
|
||||
},
|
||||
)
|
||||
this.setActiveSession(agent, did)
|
||||
this.rootStore.log.debug('SessionModel:login succeeded')
|
||||
}
|
||||
|
||||
async createAccount({
|
||||
@@ -326,33 +308,38 @@ export class SessionModel {
|
||||
handle: string
|
||||
inviteCode?: string
|
||||
}) {
|
||||
const api = AtpApi.service(service)
|
||||
const res = await api.com.atproto.account.create({
|
||||
this.rootStore.log.debug('SessionModel:createAccount')
|
||||
const agent = new AtpAgent({service})
|
||||
await agent.createAccount({
|
||||
handle,
|
||||
password,
|
||||
email,
|
||||
inviteCode,
|
||||
})
|
||||
if (res.data.accessJwt && res.data.refreshJwt) {
|
||||
this.setState({
|
||||
service: service,
|
||||
accessJwt: res.data.accessJwt,
|
||||
refreshJwt: res.data.refreshJwt,
|
||||
handle: res.data.handle,
|
||||
did: res.data.did,
|
||||
})
|
||||
this.rootStore.onboard.start()
|
||||
this.configureApi()
|
||||
this.rootStore.me.load().then(() => {
|
||||
this.addSessionToAccounts()
|
||||
})
|
||||
if (!agent.session) {
|
||||
throw new Error('Failed to establish session')
|
||||
}
|
||||
const did = agent.session.did
|
||||
const addedInfo = await this.loadAccountInfo(agent, did)
|
||||
this.persistSession(service, did, 'create', agent.session, addedInfo)
|
||||
agent.setPersistSessionHandler(
|
||||
(evt: AtpSessionEvent, sess?: AtpSessionData) => {
|
||||
this.persistSession(service, did, evt, sess)
|
||||
},
|
||||
)
|
||||
this.setActiveSession(agent, did)
|
||||
this.rootStore.onboard.start()
|
||||
this.rootStore.log.debug('SessionModel:createAccount succeeded')
|
||||
}
|
||||
|
||||
/**
|
||||
* Close all sessions across all accounts.
|
||||
*/
|
||||
async logout() {
|
||||
this.rootStore.log.debug('SessionModel:logout')
|
||||
// TODO
|
||||
// need to evaluate why deleting the session has caused errors at times
|
||||
// -prf
|
||||
/*if (this.hasSession) {
|
||||
this.rootStore.api.com.atproto.session.delete().catch((e: any) => {
|
||||
this.rootStore.log.warn(
|
||||
@@ -361,7 +348,7 @@ export class SessionModel {
|
||||
)
|
||||
})
|
||||
}*/
|
||||
this.clearSessionTokensFromAccounts()
|
||||
this.rootStore.clearAll()
|
||||
this.clearSessionTokens()
|
||||
this.rootStore.clearAllSessionState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {AtUri} from '../../third-party/uri'
|
||||
import {AppBskyFeedGetVotes as GetVotes} from '@atproto/api'
|
||||
import {RootStoreModel} from './root-store'
|
||||
import {cleanError} from '../../lib/strings'
|
||||
import * as apilib from '../lib/api'
|
||||
|
||||
const PAGE_SIZE = 30
|
||||
|
||||
@@ -90,7 +91,7 @@ export class VotesViewModel {
|
||||
const urip = new AtUri(this.params.uri)
|
||||
if (!urip.host.startsWith('did:')) {
|
||||
try {
|
||||
urip.host = await this.rootStore.resolveName(urip.host)
|
||||
urip.host = await apilib.resolveName(this.rootStore, urip.host)
|
||||
} catch (e: any) {
|
||||
this.error = e.toString()
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from 'react-native'
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
|
||||
import * as EmailValidator from 'email-validator'
|
||||
import AtpApi from '@atproto/api'
|
||||
import AtpAgent from '@atproto/api'
|
||||
import {useAnalytics} from '@segment/analytics-react-native'
|
||||
import {LogoTextHero} from './Logo'
|
||||
import {Text} from '../util/text/Text'
|
||||
@@ -488,8 +488,8 @@ const ForgotPasswordForm = ({
|
||||
setIsProcessing(true)
|
||||
|
||||
try {
|
||||
const api = AtpApi.service(serviceUrl)
|
||||
await api.com.atproto.account.requestPasswordReset({email})
|
||||
const agent = new AtpAgent({service: serviceUrl})
|
||||
await agent.api.com.atproto.account.requestPasswordReset({email})
|
||||
onEmailSent()
|
||||
} catch (e: any) {
|
||||
const errMsg = e.toString()
|
||||
@@ -625,8 +625,11 @@ const SetNewPasswordForm = ({
|
||||
setIsProcessing(true)
|
||||
|
||||
try {
|
||||
const api = AtpApi.service(serviceUrl)
|
||||
await api.com.atproto.account.resetPassword({token: resetCode, password})
|
||||
const agent = new AtpAgent({service: serviceUrl})
|
||||
await agent.api.com.atproto.account.resetPassword({
|
||||
token: resetCode,
|
||||
password,
|
||||
})
|
||||
onPasswordSet()
|
||||
} catch (e: any) {
|
||||
const errMsg = e.toString()
|
||||
|
||||
@@ -30,7 +30,7 @@ export function UserAvatar({
|
||||
avatar?: string | null
|
||||
onSelectNewAvatar?: (img: PickedImage) => void
|
||||
}) {
|
||||
const initials = getInitials(displayName || handle)
|
||||
const initials = getInitials(displayName || handle || '')
|
||||
const pal = usePalette('default')
|
||||
const renderSvg = (svgSize: number, svgInitials: string) => (
|
||||
<Svg width={svgSize} height={svgSize} viewBox="0 0 100 100">
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import React from 'react'
|
||||
import {observer} from 'mobx-react-lite'
|
||||
import {
|
||||
ActivityIndicator,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
} from 'react-native'
|
||||
import {StyleSheet, TouchableOpacity, View} from 'react-native'
|
||||
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
|
||||
import {UserAvatar} from './UserAvatar'
|
||||
import {Text} from './text/Text'
|
||||
@@ -40,11 +35,6 @@ export const ViewHeader = observer(function ViewHeader({
|
||||
const onPressSearch = () => {
|
||||
store.nav.navigate('/search')
|
||||
}
|
||||
const onPressReconnect = () => {
|
||||
store.session.connect().catch(e => {
|
||||
store.log.warn('Failed to reconnect to server', e)
|
||||
})
|
||||
}
|
||||
if (typeof canGoBack === 'undefined') {
|
||||
canGoBack = store.nav.tab.canGoBack
|
||||
}
|
||||
@@ -89,25 +79,6 @@ export const ViewHeader = observer(function ViewHeader({
|
||||
style={styles.btn}>
|
||||
<MagnifyingGlassIcon size={21} strokeWidth={3} style={pal.text} />
|
||||
</TouchableOpacity>
|
||||
{!store.session.online ? (
|
||||
<TouchableOpacity style={styles.btn} onPress={onPressReconnect}>
|
||||
{store.session.attemptingConnect ? (
|
||||
<ActivityIndicator />
|
||||
) : (
|
||||
<>
|
||||
<FontAwesomeIcon icon="signal" style={pal.text} size={16} />
|
||||
<FontAwesomeIcon
|
||||
icon="x"
|
||||
style={[
|
||||
styles.littleXIcon,
|
||||
{backgroundColor: pal.colors.background},
|
||||
]}
|
||||
size={8}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
) : undefined}
|
||||
</View>
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user