Skip to content

Commit

Permalink
feat: check server config on create (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
monkeyWie authored Mar 28, 2024
1 parent c1cf48a commit 95e68d6
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 19 deletions.
39 changes: 29 additions & 10 deletions background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,34 @@ import { Storage } from "@plasmohq/storage"
import { STORAGE_SERVER_STATUS, STORAGE_SERVERS } from "~constants"
import { getSelectedServer } from "~util"

export {}
export { }

export type CheckResult = "success" | "network_error" | "token_error"

export async function checkServer(server: Server): Promise<CheckResult> {
return new Promise(async (resolve) => {
setTimeout(() => {
resolve("network_error")
}, 5000)
try {
console.log(server.url)
const resp = await fetch(`${server.url}/api/v1/tasks/0`, {
headers: {
"X-Api-Token": server.token
}
})
const json = await resp.json()
// When the server is available, it should return 2001 (task not found)
if (json.code !== 2001) {
resolve("token_error")
return
}
resolve("success")
} catch (e) {
resolve("network_error")
}
})

async function checkServer(server: Server) {
try {
await fetch(server.url)
return true
} catch (e) {
return false
}
}

/* function initContextMenus() {
Expand All @@ -33,7 +52,7 @@ async function checkServer(server: Server) {
})
} */

;(async function () {
; (async function () {
// initContextMenus()

const storage = new Storage()
Expand All @@ -49,7 +68,7 @@ async function checkServer(server: Server) {
)
await storage.set(STORAGE_SERVER_STATUS, {
...prev,
[server.url]: status
[server.url]: status === "success"
})
})
)
Expand Down
13 changes: 13 additions & 0 deletions background/messages/api/check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { PlasmoMessaging } from "@plasmohq/messaging"

import { checkServer, type CheckResult } from "~background"

const handler: PlasmoMessaging.MessageHandler<Server, CheckResult> = async (
req,
res
) => {
const result = await checkServer(req.body)
res.send(result)
}

export default handler
18 changes: 18 additions & 0 deletions locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"cancel": {
"message": "CANCEL"
},
"confirm": {
"message": "CONFIRM"
},
"server": {
"message": "SERVER"
},
Expand All @@ -31,5 +34,20 @@
},
"delete": {
"message": "DELETE"
},
"check": {
"message": "CHECK"
},
"tip_create_error": {
"message": "Configuration error"
},
"tip_create_still_save": {
"message": ",do you still want to save?"
},
"tip_create_network_error": {
"message": "Server connection failed"
},
"tip_create_token_error": {
"message": "Api token error or server not configured correctly"
}
}
15 changes: 15 additions & 0 deletions locales/zh/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"cancel": {
"message": "取消"
},
"confirm": {
"message": "确认"
},
"server": {
"message": "服务器"
},
Expand All @@ -31,5 +34,17 @@
},
"delete": {
"message": "删除"
},
"tip_create_error": {
"message": "配置有误"
},
"tip_create_still_save": {
"message": ",是否仍要保存?"
},
"tip_create_network_error": {
"message": "服务器无法连接"
},
"tip_create_token_error": {
"message": "接口令牌不正确或服务器未正确配置"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "gopeed-browser-extension",
"displayName": "Gopeed",
"version": "0.0.1",
"version": "0.0.2",
"description": "Gopeed browser extension",
"homepage": "https://gopeed.com",
"author": "Levi",
Expand Down
91 changes: 83 additions & 8 deletions popup/create-server.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
import { ArrowBack, Save } from "@mui/icons-material"
import { ArrowBack, Save, Speed } from "@mui/icons-material"
import { LoadingButton } from "@mui/lab"
import {
Alert,
AppBar,
Backdrop,
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
IconButton,
Snackbar,
Stack,
Toolbar,
Typography
} from "@mui/material"
import { useTheme } from "@mui/material/styles"
import { useState } from "react"
import {
FormContainer,
SelectElement,
TextFieldElement,
useForm
} from "react-hook-form-mui"

import { sendToBackground } from "@plasmohq/messaging"
import { useStorage } from "@plasmohq/storage/hook"

import type { CheckResult } from "~background"
import { STORAGE_SERVER_SELECTED, STORAGE_SERVERS } from "~constants"

const ERROR_TIPS: Record<CheckResult, string> = {
success: "",
network_error: chrome.i18n.getMessage("tip_create_network_error"),
token_error: chrome.i18n.getMessage("tip_create_token_error")
}

function CreateServer(props: { onClose: () => void }) {
const theme = useTheme()
const [_, setSelected] = useStorage<string>(STORAGE_SERVER_SELECTED)
Expand All @@ -32,17 +52,46 @@ function CreateServer(props: { onClose: () => void }) {
token: ""
}
})
const [loading, setLoading] = useState(false)
const [error, setError] = useState<CheckResult | null>(null)

function handleSave() {
function buildServer() {
const server = formContext.getValues()
server.url = `${server.scheme}://${server.host}:${server.port}`
// Check if the server is already in the list
const exists = servers.some((s) => s.url === server.url)
if (exists) {
props.onClose()
return
return server
}

async function handleSave() {
setLoading(true)

try {
const server = buildServer()
// Check if the server is already in the list
const exists = servers.some((s) => s.url === server.url)
if (exists) {
props.onClose()
return
}

// Check if the server is available
const result = await sendToBackground<Server, CheckResult>({
name: "api/check",
body: server
})
if (result !== "success") {
setError(result)
return
}

doSave()
} catch (e) {
} finally {
setLoading(false)
}
}

function doSave() {
const server = buildServer()
if (servers.length === 0) {
setSelected(server.url)
}
Expand All @@ -53,10 +102,36 @@ function CreateServer(props: { onClose: () => void }) {
return (
<Box
sx={{ backgroundColor: theme.palette.background.paper, height: "100%" }}>
<Backdrop
open={loading}
sx={{ color: "#fff", zIndex: (theme) => theme.zIndex.drawer + 1 }}>
<CircularProgress color="inherit" />
</Backdrop>
<Dialog
open={!!error}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description">
<DialogTitle id="alert-dialog-title">
{chrome.i18n.getMessage("tip_create_error")}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
{`${ERROR_TIPS[error]}${chrome.i18n.getMessage(
"tip_create_still_save"
)}`}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={() => setError(null)}>
{chrome.i18n.getMessage("cancel")}
</Button>
<Button onClick={doSave}>{chrome.i18n.getMessage("confirm")}</Button>
</DialogActions>
</Dialog>
<AppBar position="static">
<Toolbar>
<IconButton
aria-label="save"
aria-label="back"
size="large"
edge="start"
onClick={props.onClose}>
Expand Down

0 comments on commit 95e68d6

Please sign in to comment.