Skip to content

Commit 44ad6c2

Browse files
committed
refactor: simplify code
1 parent d62d6ae commit 44ad6c2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+222
-290
lines changed

src/auth/account-manager.ts

+22-32
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import { AccountInfo } from './account-info'
2-
import { globalCtx } from '@/services/global-state'
2+
import { globalCtx } from '@/services/global-ctx'
33
import vscode, { authentication, AuthenticationGetSessionOptions, Disposable } from 'vscode'
44
import { accountViewDataProvider } from '@/tree-view-providers/account-view-data-provider'
55
import { postsDataProvider } from '@/tree-view-providers/posts-data-provider'
66
import { postCategoriesDataProvider } from '@/tree-view-providers/post-categories-tree-data-provider'
7-
import { OauthApi } from '@/services/oauth.api'
7+
import { Oauth } from '@/services/oauth.api'
88
import { AuthProvider } from '@/auth/auth-provider'
9-
import { AuthSession } from '@/auth/session'
9+
import { AuthSession } from '@/auth/auth-session'
1010
import { BlogExportProvider } from '@/tree-view-providers/blog-export-provider'
1111
import { AlertService } from '@/services/alert.service'
1212

@@ -16,13 +16,12 @@ export const ACQUIRE_TOKEN_REJECT_UNAUTHENTICATED = 'unauthenticated'
1616
export const ACQUIRE_TOKEN_REJECT_EXPIRED = 'expired'
1717

1818
class AccountManager extends vscode.Disposable {
19-
private readonly _authProvider = AuthProvider.instance
2019
private readonly _disposable = Disposable.from(
21-
this._authProvider.onDidChangeSessions(async ({ added }) => {
20+
AuthProvider.instance.onDidChangeSessions(async ({ added }) => {
2221
this._session = null
2322
if (added != null && added.length > 0) await this.ensureSession()
2423

25-
await this.updateAuthorizationStatus()
24+
await this.updateAuthStatus()
2625

2726
accountViewDataProvider.fireTreeDataChangedEvent()
2827
postsDataProvider.fireTreeDataChangedEvent(undefined)
@@ -32,7 +31,6 @@ class AccountManager extends vscode.Disposable {
3231
})
3332
)
3433

35-
private _oauthClient: OauthApi | null = null
3634
private _session: AuthSession | null = null
3735

3836
constructor() {
@@ -45,15 +43,10 @@ class AccountManager extends vscode.Disposable {
4543
return this._session !== null
4644
}
4745

48-
get curUser(): AccountInfo {
46+
get currentUser(): AccountInfo {
4947
return this._session?.account ?? AccountInfo.newAnonymous()
5048
}
5149

52-
protected get oauthClient() {
53-
this._oauthClient ??= new OauthApi()
54-
return this._oauthClient
55-
}
56-
5750
/**
5851
* Acquire the access token.
5952
* This will reject with a human-readable reason string if not sign-in or the token has expired.
@@ -77,51 +70,48 @@ class AccountManager extends vscode.Disposable {
7770
if (!this.isAuthorized) return
7871

7972
const session = await authentication.getSession(AuthProvider.providerId, [])
80-
if (session !== undefined) await this._authProvider.removeSession(session.id)
8173

82-
// For old version compatibility, **never** remove this line
74+
// WRN: For old version compatibility, **never** remove this line
8375
await globalCtx.storage.update('user', undefined)
8476

85-
if (session) {
86-
return this.oauthClient
87-
.revoke(session.accessToken)
88-
.catch(console.warn)
89-
.then(ok => (!ok ? console.warn('Revocation failed') : undefined))
90-
}
91-
}
77+
if (session === undefined) return
9278

93-
setup = async () => {
94-
await this.updateAuthorizationStatus()
79+
try {
80+
await AuthProvider.instance.removeSession(session.id)
81+
await Oauth.revokeToken(session.accessToken)
82+
} catch (e: any) {
83+
AlertService.err(`登出发生错误: ${e}`)
84+
}
9585
}
9686

97-
private async updateAuthorizationStatus() {
87+
async updateAuthStatus() {
9888
await this.ensureSession({ createIfNone: false })
9989

10090
await vscode.commands.executeCommand(
10191
'setContext',
102-
`${globalCtx.extensionName}.${isAuthorizedStorageKey}`,
92+
`${globalCtx.extName}.${isAuthorizedStorageKey}`,
10393
this.isAuthorized
10494
)
10595

10696
if (this.isAuthorized) {
107-
await vscode.commands.executeCommand('setContext', `${globalCtx.extensionName}.user`, {
108-
name: this.curUser.name,
109-
avatar: this.curUser.avatar,
97+
await vscode.commands.executeCommand('setContext', `${globalCtx.extName}.user`, {
98+
name: this.currentUser.name,
99+
avatar: this.currentUser.avatar,
110100
})
111101
}
112102
}
113103

114104
private async ensureSession(opt?: AuthenticationGetSessionOptions): Promise<AuthSession | null> {
115-
const session = await authentication.getSession(this._authProvider.providerId, [], opt).then(
105+
const session = await authentication.getSession(AuthProvider.instance.providerId, [], opt).then(
116106
session => (session ? AuthSession.from(session) : null),
117107
e => {
118-
AlertService.err(`创建/获取 session 失败: ${e}`)
108+
AlertService.err(`创建/获取 Session 失败: ${e}`)
119109
}
120110
)
121111

122112
if (session != null && session.account.accountId < 0) {
123113
this._session = null
124-
await this._authProvider.removeSession(session.id)
114+
await AuthProvider.instance.removeSession(session.id)
125115
} else {
126116
this._session = session
127117
}

src/auth/auth-provider.ts

+20-32
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { AuthSession } from '@/auth/session'
2-
import { genCodePair } from '@/services/code-challenge.service'
1+
import { AuthSession } from '@/auth/auth-session'
2+
import { genVerifyChallengePair } from '@/services/code-challenge.service'
33
import { isArray, isUndefined } from 'lodash-es'
44
import {
55
authentication,
@@ -14,9 +14,9 @@ import {
1414
Uri,
1515
window,
1616
} from 'vscode'
17-
import { globalCtx } from '@/services/global-state'
17+
import { globalCtx } from '@/services/global-ctx'
1818
import RandomString from 'randomstring'
19-
import { OauthApi } from '@/services/oauth.api'
19+
import { Oauth } from '@/services/oauth.api'
2020
import extensionUriHandler from '@/utils/uri-handler'
2121
import { AccountInfo } from '@/auth/account-info'
2222
import { TokenInfo } from '@/models/token-info'
@@ -35,14 +35,16 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
3535
protected readonly allScopes = globalCtx.config.oauth.scope.split(' ')
3636

3737
private _allSessions?: AuthSession[] | null
38-
private _oauthClient?: OauthApi | null
38+
3939
private readonly _sessionChangeEmitter = new EventEmitter<VscAuthProviderAuthSessionChEv>()
4040
private readonly _disposable = Disposable.from(
4141
this._sessionChangeEmitter,
4242
authentication.registerAuthenticationProvider(AuthProvider.providerId, AuthProvider.providerName, this, {
4343
supportsMultipleAccounts: false,
4444
}),
45-
this.onDidChangeSessions(() => (this._allSessions = null))
45+
this.onDidChangeSessions(() => {
46+
this._allSessions = null
47+
})
4648
)
4749

4850
static get instance() {
@@ -55,7 +57,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
5557
}
5658

5759
protected get context() {
58-
return globalCtx.extensionContext
60+
return globalCtx.extCtx
5961
}
6062

6163
protected get secretStorage() {
@@ -66,11 +68,6 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
6668
return globalCtx.config
6769
}
6870

69-
protected get oauthClient() {
70-
this._oauthClient ??= new OauthApi()
71-
return this._oauthClient
72-
}
73-
7471
async getSessions(scopes?: readonly string[] | undefined): Promise<readonly AuthSession[]> {
7572
const sessions = await this.getAllSessions()
7673
const parsedScopes = this.ensureScopes(scopes)
@@ -99,7 +96,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
9996
cancelTokenSrc.cancel()
10097
}, 30 * 60 * 1000) // 30 min
10198

102-
const codeVerifier = this.signInWithBrowser({ scopes: parsedScopes })
99+
const verifyCode = this.signInWithBrowser({ scopes: parsedScopes })
103100

104101
return window.withProgress<AuthSession>(options, async (progress, cancelToken) => {
105102
progress.report({ message: '等待用户在浏览器中进行授权...' })
@@ -121,15 +118,10 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
121118

122119
progress.report({ message: '已获得授权, 正在获取令牌...' })
123120

124-
this.oauthClient
125-
.fetchToken({
126-
codeVerifier,
127-
authorizationCode,
128-
cancellationToken: cancelTokenSrc.token,
129-
})
121+
Oauth.fetchToken(verifyCode, authorizationCode, cancelTokenSrc.token)
130122
.then(token =>
131123
this.onAccessTokenGranted(token, {
132-
cancellationToken: cancelTokenSrc.token,
124+
cancelToken: cancelTokenSrc.token,
133125
onStateChange(state) {
134126
progress.report({ message: state })
135127
},
@@ -185,15 +177,15 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
185177
}
186178

187179
private signInWithBrowser({ scopes }: { scopes: readonly string[] }) {
188-
const { codeVerifier, codeChallenge } = genCodePair()
180+
const [verifyCode, challengeCode] = genVerifyChallengePair()
189181
const { clientId, responseType, authorizeEndpoint, authority, clientSecret } = this.config.oauth
190182

191183
const search = new URLSearchParams([
192184
['client_id', clientId],
193185
['response_type', responseType],
194186
['redirect_uri', globalCtx.extensionUrl],
195187
['nonce', RandomString.generate(32)],
196-
['code_challenge', codeChallenge],
188+
['code_challenge', challengeCode],
197189
['code_challenge_method', 'S256'],
198190
['scope', scopes.join(' ')],
199191
['client_secret', clientSecret],
@@ -204,7 +196,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
204196
console.warn
205197
)
206198

207-
return codeVerifier
199+
return verifyCode
208200
}
209201

210202
private ensureScopes(
@@ -219,17 +211,17 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
219211
private async onAccessTokenGranted(
220212
{ accessToken, refreshToken }: TokenInfo,
221213
{
222-
cancellationToken,
214+
cancelToken,
223215
onStateChange,
224216
shouldFireSessionAddedEvent = true,
225217
}: {
226218
onStateChange?: (state: string) => void
227-
cancellationToken?: CancellationToken
219+
cancelToken?: CancellationToken
228220
shouldFireSessionAddedEvent?: boolean
229221
} = {}
230222
) {
231223
const ifNotCancelledThen = <TR>(f: () => TR): TR | undefined => {
232-
if (cancellationToken?.isCancellationRequested) return
224+
if (cancelToken?.isCancellationRequested) return
233225
return f()
234226
}
235227

@@ -238,11 +230,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
238230
try {
239231
onStateChange?.('正在获取账户信息...')
240232

241-
const spec = await ifNotCancelledThen(() =>
242-
this.oauthClient.fetchUserInfo(accessToken, {
243-
cancellationToken: cancellationToken,
244-
})
245-
)
233+
const spec = await ifNotCancelledThen(() => Oauth.fetchUserInfo(accessToken, cancelToken))
246234

247235
onStateChange?.('即将完成...')
248236

@@ -277,7 +265,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
277265
})
278266
})
279267
} finally {
280-
if (session != null && cancellationToken?.isCancellationRequested) await this.removeSession(session.id)
268+
if (session != null && cancelToken?.isCancellationRequested) await this.removeSession(session.id)
281269
}
282270

283271
if (session == null) throw new Error('Failed to create session')
File renamed without changes.

src/auth/index.ts

-4
This file was deleted.

src/commands/blog-export/download.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { TreeViewCommandHandler } from '@/commands/command-handler'
22
import { AlertService } from '@/services/alert.service'
33
import { BlogExportApi } from '@/services/blog-export.api'
44
import { DownloadedExportStore } from '@/services/downloaded-export.store'
5-
import { globalCtx } from '@/services/global-state'
5+
import { globalCtx } from '@/services/global-ctx'
66
import { Settings } from '@/services/settings.service'
77
import { BlogExportProvider } from '@/tree-view-providers/blog-export-provider'
88
import { BlogExportRecordTreeItem } from '@/tree-view-providers/models/blog-export'
@@ -118,7 +118,7 @@ export class DownloadExportCommandHandler extends TreeViewCommandHandler<BlogExp
118118
private setIsDownloading(value: boolean) {
119119
return commands.executeCommand(
120120
'setContext',
121-
`${globalCtx.extensionName}.blog-export.downloading`,
121+
`${globalCtx.extName}.blog-export.downloading`,
122122
value || undefined
123123
)
124124
}

src/commands/blog-export/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { RefreshExportRecordsCommandHandler } from './refresh'
2-
import { globalCtx } from '@/services/global-state'
2+
import { globalCtx } from '@/services/global-ctx'
33
import { commands, Disposable } from 'vscode'
44
import { OpenLocalExportCommandHandler } from '@/commands/blog-export/open-local'
55
import { EditExportPostCommandHandler } from '@/commands/blog-export/edit'
@@ -9,9 +9,9 @@ import { ViewPostCommandHandler } from '@/commands/blog-export/view-post'
99
import { DeleteCommandHandler } from '@/commands/blog-export/delete'
1010

1111
export function registerCommandsForBlogExport(disposables: Disposable[]) {
12-
const { extensionName } = globalCtx
12+
const { extName } = globalCtx
1313
disposables.push(
14-
commands.registerCommand(`${extensionName}.blog-export.refresh-records`, () =>
14+
commands.registerCommand(`${extName}.blog-export.refresh-records`, () =>
1515
new RefreshExportRecordsCommandHandler().handle()
1616
),
1717
commands.registerCommand(OpenLocalExportCommandHandler.commandName, () =>

src/commands/blog-export/refresh.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CommandHandler } from '@/commands/command-handler'
2-
import { globalCtx } from '@/services/global-state'
2+
import { globalCtx } from '@/services/global-ctx'
33
import { BlogExportProvider } from '@/tree-view-providers/blog-export-provider'
44
import { commands } from 'vscode'
55

@@ -15,7 +15,7 @@ export class RefreshExportRecordsCommandHandler extends CommandHandler {
1515
private setIsRefreshing(value: boolean) {
1616
return commands.executeCommand(
1717
'setContext',
18-
`${globalCtx.extensionName}.blog-export.records.isRefreshing`,
18+
`${globalCtx.extName}.blog-export.records.isRefreshing`,
1919
value || undefined
2020
)
2121
}

src/commands/commands-registration.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { openMyWebBlogConsole } from './open-my-blog-management-background'
44
import { openMyHomePage } from './open-my-home-page'
55
import { login, logout } from './login'
66
import { openMyBlog } from './open-my-blog'
7-
import { globalCtx } from '@/services/global-state'
7+
import { globalCtx } from '@/services/global-ctx'
88
import {
99
gotoNextPostsList,
1010
gotoPreviousPostsList,
@@ -39,8 +39,8 @@ import { CopyPostLinkCommandHandler } from '@/commands/posts-list/copy-link'
3939
import { registerCommandsForBlogExport } from '@/commands/blog-export'
4040

4141
export const registerCommands = () => {
42-
const context = globalCtx.extensionContext
43-
const appName = globalCtx.extensionName
42+
const context = globalCtx.extCtx
43+
const appName = globalCtx.extName
4444

4545
// TODO: simplify register
4646
const disposables = [

src/commands/ing/ings-list-commands-registration.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { commands } from 'vscode'
22
import { RefreshIngsList } from 'src/commands/ing/refresh-ings-list'
3-
import { globalCtx } from 'src/services/global-state'
3+
import { globalCtx } from 'src/services/global-ctx'
44
import { IDisposable } from '@fluentui/react'
55
import {
66
GotoIngsListFirstPage,
@@ -11,7 +11,7 @@ import { SelectIngType } from '@/commands/ing/select-ing-type'
1111
import { OpenIngInBrowser } from '@/commands/ing/open-ing-in-browser'
1212

1313
export const registerCommandsForIngsList = (disposables: IDisposable[]) => {
14-
const appName = globalCtx.extensionName
14+
const appName = globalCtx.extName
1515

1616
disposables.push(
1717
...[

src/commands/ing/open-ing-in-browser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CommandHandler } from '@/commands/command-handler'
2-
import { globalCtx } from '@/services/global-state'
2+
import { globalCtx } from '@/services/global-ctx'
33
import { commands, Uri } from 'vscode'
44

55
export class OpenIngInBrowser extends CommandHandler {

src/commands/ing/publish-ing.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { CommandHandler } from '@/commands/command-handler'
22
import { IngPublishModel, IngType } from '@/models/ing'
33
import { AlertService } from '@/services/alert.service'
4-
import { globalCtx } from '@/services/global-state'
4+
import { globalCtx } from '@/services/global-ctx'
55
import { IngApi } from '@/services/ing.api'
66
import { IngsListWebviewProvider } from '@/services/ings-list-webview-provider'
77
import { InputStep, MultiStepInput, QuickPickParameters } from '@/services/multi-step-input'

0 commit comments

Comments
 (0)