generated from vivid-lapin/ts
-
Notifications
You must be signed in to change notification settings - Fork 3
/
GDriveRenderer.tsx
601 lines (596 loc) · 21.8 KB
/
GDriveRenderer.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import $ from "@recoiljs/refine"
import clsx from "clsx"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { atom, useRecoilState, useRecoilValue, useSetRecoilState } from "recoil"
import { syncEffect } from "recoil-sync"
import { FileSelector } from "./components/FileSelector"
import {
GDRIVE_CALC_S256,
GDRIVE_GET_PORT,
GDRIVE_META,
GDRIVE_PREFIX,
GDRIVE_SET_ACCESS_TOKEN,
GDRIVE_SET_CRED,
GDRIVE_WINDOW_ID,
} from "./constants"
import { GDRIVE_CLIENT_ID, GDRIVE_CLIENT_SECRET } from "./cred"
import { generateRandomString } from "./utils"
import { ContentPlayerPlayingContent, InitPlugin } from "../@types/plugin"
import { DEFAULT_SERVICES } from "../shared/services"
import tailwind from "../tailwind.scss"
const INSUFFICIENT_MESSAGE =
"認証に必要な情報が不足しています。本体アプリケーションはv2.0.0-rc.2以上が必要です。"
const refine = $.withDefault(
$.object({
accessToken: $.string(),
refreshToken: $.string(),
clientId: $.string(),
clientSecret: $.string(),
}),
{
accessToken: "",
refreshToken: "",
clientId: "",
clientSecret: "",
}
)
export const GDriveRenderer: InitPlugin["renderer"] = ({
appInfo,
functions,
atoms,
rpc,
constants,
}) => {
const settingAtom = atom({
key: `${GDRIVE_PREFIX}.setting`,
default: {
accessToken: "",
refreshToken: "",
clientId: "",
clientSecret: "",
},
effects: [
syncEffect({
storeKey: constants?.recoil?.sharedKey,
refine,
}),
syncEffect({
storeKey: constants?.recoil?.storedKey,
refine,
}),
],
})
return {
...GDRIVE_META,
exposedAtoms: [],
sharedAtoms: [
{
type: "atom",
atom: settingAtom,
},
],
storedAtoms: [
{
type: "atom",
atom: settingAtom,
},
],
setup() {
return
},
components: [
{
id: `${GDRIVE_PREFIX}.settings`,
position: "onSetting",
label: "Google Drive",
component: () => {
const [setting, setSetting] = useRecoilState(settingAtom)
const [accessToken, setAccessToken] = useState(setting.accessToken)
const [refreshToken, setRefreshToken] = useState(setting.refreshToken)
const [clientId, setClientId] = useState(setting.clientId)
const [clientSecret, setClientSecret] = useState(setting.clientSecret)
const useClientId = clientId || GDRIVE_CLIENT_ID
const useClientSecret = clientSecret || GDRIVE_CLIENT_SECRET
const [port, setPort] = useState<number | null>(null)
useEffect(() => {
setAccessToken(setting.accessToken)
setRefreshToken(setting.refreshToken)
setClientId(setting.clientId)
setClientSecret(setting.clientSecret)
}, [setting])
useEffect(() => {
rpc.invoke(GDRIVE_GET_PORT).then((port) => setPort(port as number))
const off = rpc.onCustomIpcListener(GDRIVE_SET_CRED, (data) => {
setTimeout(() => {
const { access_token, refresh_token } = data as {
access_token?: string
refresh_token?: string
}
console.info("[gdrive] credential data:", data)
if (access_token) {
setAccessToken(access_token)
}
if (refresh_token) {
setRefreshToken(refresh_token)
}
}, 1000)
})
return () => {
off()
}
}, [])
const [focusingSensitive, setFocusingSensitive] = useState(false)
const isLoginButtonDisabled =
!port || !useClientId || !useClientSecret
return (
<>
<style>{tailwind}</style>
<div className="p-4">
<p className="text-xl">Google Drive</p>
<form
onSubmit={(e) => {
e.preventDefault()
setSetting({
accessToken,
refreshToken,
clientId,
clientSecret,
})
}}
>
<label className={clsx("block", "mt-4")}>
<span>クライアントID</span>
<input
type="text"
placeholder=""
className={clsx(
"block",
"mt-2",
"form-input",
"rounded-md",
"w-full",
"text-gray-900"
)}
value={clientId || ""}
onChange={(e) => setClientId(e.target.value)}
/>
</label>
<label className={clsx("block", "mt-4")}>
<span>クライアントシークレット</span>
<input
type={focusingSensitive ? "text" : "password"}
placeholder=""
className={clsx(
"block",
"mt-2",
"form-input",
"rounded-md",
"w-full",
"text-gray-900"
)}
value={clientSecret || ""}
onChange={(e) => setClientSecret(e.target.value)}
onFocus={() => setFocusingSensitive(true)}
onBlur={() => setFocusingSensitive(false)}
/>
</label>
<span
className={clsx(
"block",
"text-sm",
"text-gray-300",
"mt-2"
)}
>
クライアントIDとクライアントシークレットを空欄にするとデフォルトのものが使用されます。
カスタムのクライアント ID を使用する場合には、Google Drive
API を有効化してください。
</span>
<label className={clsx("block", "mt-4")}>
<span>リフレッシュトークン</span>
<input
type={focusingSensitive ? "text" : "password"}
placeholder=""
className={clsx(
"block",
"mt-2",
"form-input",
"rounded-md",
"w-full",
"text-gray-900"
)}
value={refreshToken || ""}
onChange={(e) => setRefreshToken(e.target.value)}
onFocus={() => setFocusingSensitive(true)}
onBlur={() => setFocusingSensitive(false)}
/>
</label>
<label className={clsx("block", "mt-4")}>
<span>アクセストークン</span>
<input
type={focusingSensitive ? "text" : "password"}
placeholder=""
className={clsx(
"block",
"mt-2",
"form-input",
"rounded-md",
"w-full",
"text-gray-900"
)}
value={accessToken || ""}
onChange={(e) => setAccessToken(e.target.value)}
onFocus={() => setFocusingSensitive(true)}
onBlur={() => setFocusingSensitive(false)}
/>
</label>
<span
className={clsx(
"block",
"text-sm",
"text-gray-300",
"mt-2"
)}
>
アクセストークンが失効した場合はリフレッシュトークンを用いて更新されるため、通常は変更する必要はありません。連携を解除するなどしてリフレッシュトークンを失効させた場合は、下のボタンから再度連携を行えます。
</span>
<button
type="submit"
className={clsx(
"bg-gray-100",
"text-gray-800",
"p-2",
"px-2",
"my-4",
"rounded-md",
"cursor-pointer",
"active:bg-gray-200"
)}
>
更新
</button>
</form>
<div className="mb-4">
<p className={clsx("text-lg", "mb-2")}>連携の更新</p>
<button
type="button"
className={clsx(
"p-2",
"rounded-md",
"bg-gray-200",
"text-gray-800",
"font-semibold",
isLoginButtonDisabled && [
"cursor-not-allowed",
"bg-gray-400",
]
)}
onClick={async () => {
if (isLoginButtonDisabled) {
alert(INSUFFICIENT_MESSAGE)
return
}
const url = new URL(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=$CLIENT_ID&redirect_uri=$REDIRECT_URI&scope=$SCOPE"
)
url.searchParams.set("client_id", useClientId)
const redirectUri = `http://127.0.0.1:${port}/oauth2redirect`
url.searchParams.set("redirect_uri", redirectUri)
url.searchParams.set(
"scope",
"https://www.googleapis.com/auth/drive.readonly"
)
const verifier = generateRandomString(43)
const challenge = await rpc.invoke(
GDRIVE_CALC_S256,
verifier
)
url.searchParams.set(
"code_challenge",
challenge as string
)
url.searchParams.set("code_challenge_method", "S256")
rpc.invoke(GDRIVE_SET_CRED, {
clientId: useClientId,
clientSecret: useClientSecret,
verifier,
redirectUri,
})
window.open(url.href, "_blank")
}}
>
Googleアカウントでログイン
</button>
</div>
<span
className={clsx("block", "text-sm", "text-gray-300", "mt-2")}
>
プロキシに使用しているポート:{" "}
{port ? (
port
) : (
<span className="text-red-500">
プロキシが起動していません
</span>
)}
</span>
</div>
</>
)
},
},
],
destroy() {
return
},
windows: {
[GDRIVE_WINDOW_ID]: () => {
const activeId = useRecoilValue(
atoms.globalActiveContentPlayerIdSelector
)
const setPlayingContent = useSetRecoilState(
atoms.globalContentPlayerPlayingContentFamily(activeId ?? 0)
)
const services = useRecoilValue(atoms.mirakurunServicesSelector)
const filledServices = useMemo(
() => services || DEFAULT_SERVICES,
[services]
)
useEffect(() => {
rpc.setWindowTitle(`Google Drive - ${appInfo.name}`)
}, [])
const [isSignedIn, setIsSignedIn] = useState(false)
const [settings, setSettings] = useRecoilState(settingAtom)
const [isReady, setIsReady] = useState(false)
const [accessToken, setAccessToken] = useState(settings.accessToken)
const [refreshToken, setRefreshToken] = useState(settings.refreshToken)
const [clientId, setClientId] = useState(settings.clientId)
const useClientId = clientId || GDRIVE_CLIENT_ID
const [clientSecret, setClientSecret] = useState(settings.clientSecret)
const useClientSecret = clientSecret || GDRIVE_CLIENT_SECRET
useEffect(() => {
setSettings({ accessToken, refreshToken, clientId, clientSecret })
}, [accessToken, refreshToken, clientId, clientSecret])
useEffect(() => {
setAccessToken(settings.accessToken)
setRefreshToken(settings.refreshToken)
setClientId(settings.clientId)
setClientSecret(settings.clientSecret)
}, [settings])
const [sessionError, setSessionError] = useState<string | null>(null)
const refreshAccessToken = useCallback(async () => {
if (!refreshToken || !useClientSecret) {
return
}
setSessionError(null)
const params = new URLSearchParams()
params.set("client_id", useClientId)
params.set("client_secret", useClientSecret)
params.set("grant_type", "refresh_token")
params.set("refresh_token", refreshToken)
const result = await fetch("https://oauth2.googleapis.com/token", {
body: params,
method: "POST",
})
if (result.ok) {
const data: { access_token: string } = await result.json()
setAccessToken(data.access_token)
} else {
setSessionError(await result.text())
}
}, [refreshToken])
useEffect(() => {
if (!accessToken.trim()) {
return
}
let timer: NodeJS.Timeout | null = null
fetch(
"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" +
accessToken
).then(async (res) => {
if (res.ok) {
const data: { expires_in: number } = await res.json()
setIsSignedIn(true)
setSessionError(null)
const renewAt = Date.now() + (data.expires_in - 10) * 1000
timer = setInterval(async () => {
if (Date.now() > renewAt) {
if (timer) {
clearInterval(timer)
timer = null
}
await refreshAccessToken()
}
}, 1000)
rpc.invoke(GDRIVE_SET_ACCESS_TOKEN, accessToken)
} else {
setIsSignedIn(false)
setSessionError(await res.text())
refreshAccessToken()
}
})
return () => {
if (timer) {
clearInterval(timer)
timer = null
}
}
}, [accessToken])
const [driveClient, setDriveClient] = useState<
typeof gapi.client.drive | false
>(false)
useEffect(() => {
const apiScript = document.createElement("script")
apiScript.src = "https://apis.google.com/js/api.js"
apiScript.async = true
apiScript.defer = true
apiScript.onload = () => {
gapi.load("client", () => {
gapi.client.load("drive", "v3", () => {
setDriveClient(gapi.client.drive)
})
})
}
document.body.appendChild(apiScript)
return () => {
document.body.removeChild(apiScript)
}
}, [])
useEffect(() => {
if (isSignedIn && accessToken && driveClient) {
// @ts-expect-error miss type
gapi.auth.setToken({ access_token: accessToken })
setIsReady(true)
} else {
setIsReady(false)
}
}, [driveClient, isSignedIn, accessToken])
const [port, setPort] = useState(0)
useEffect(() => {
rpc.invoke(GDRIVE_GET_PORT).then((port) => setPort(port as number))
const off = rpc.onCustomIpcListener(GDRIVE_SET_CRED, (data) => {
const { access_token, refresh_token } = data as {
access_token?: string
refresh_token?: string
}
console.info("[gdrive] credential data:", data)
if (access_token) {
setAccessToken(access_token)
}
if (refresh_token) {
setRefreshToken(refresh_token)
}
})
return () => {
off()
}
}, [])
const isLoginButtonDisabled = !port || !useClientId || !useClientSecret
return (
<>
<style>{tailwind}</style>
<div
className={clsx(
"w-full",
"h-screen",
"bg-gray-100",
"text-gray-900",
"flex",
"leading-loose"
)}
>
{port ? (
isReady && driveClient ? (
<FileSelector
api={driveClient}
services={filledServices}
setPlayingContent={setPlayingContent}
openContentPlayer={(
playingContent: ContentPlayerPlayingContent
) => {
return functions.openContentPlayerWindow({
playingContent,
})
}}
port={port}
accessToken={accessToken}
/>
) : (
<div
className={clsx(
"w-full",
"h-full",
"flex",
"items-center",
"justify-center"
)}
>
<div
className={clsx("text-gray-600", "px-4", "text-center")}
>
<button
type="button"
className={clsx(
"p-4",
"rounded-md",
"bg-gray-200",
"font-semibold",
isLoginButtonDisabled && [
"cursor-not-allowed",
"bg-gray-400",
]
)}
onClick={async () => {
if (isLoginButtonDisabled) {
alert(INSUFFICIENT_MESSAGE)
return
}
const url = new URL(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=$CLIENT_ID&redirect_uri=$REDIRECT_URI&scope=$SCOPE"
)
url.searchParams.set("client_id", useClientId)
const redirectUri = `http://127.0.0.1:${port}/oauth2redirect`
url.searchParams.set("redirect_uri", redirectUri)
url.searchParams.set(
"scope",
"https://www.googleapis.com/auth/drive.readonly"
)
const verifier = generateRandomString(43)
const challenge = await rpc.invoke(
GDRIVE_CALC_S256,
verifier
)
url.searchParams.set(
"code_challenge",
challenge as string
)
url.searchParams.set("code_challenge_method", "S256")
rpc.invoke(GDRIVE_SET_CRED, {
clientId: useClientId,
clientSecret: useClientSecret,
verifier,
redirectUri,
})
window.open(url.href, "_blank")
}}
>
Googleアカウントでログイン
</button>
{sessionError && (
<p
className={clsx(
"mt-2",
"text-red-600",
"font-semibold",
"break-words",
"font-medium"
)}
>
{sessionError}
</p>
)}
</div>
</div>
)
) : (
<div
className={clsx(
"w-full",
"h-full",
"flex",
"items-center",
"justify-center"
)}
>
<div className={clsx("text-gray-600", "px-4", "text-center")}>
<p>読み込み中</p>
</div>
</div>
)}
</div>
</>
)
},
},
}
}