Skip to content

Commit

Permalink
feat: 新版挂件-网页授权支持客户端自动读取Cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Jul 29, 2023
1 parent 98949eb commit b2501b3
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 12 deletions.
15 changes: 10 additions & 5 deletions src/components/set/PublishSetting.vue
Expand Up @@ -111,7 +111,7 @@ const handleSinglePlatformDelete = (cfg: DynamicConfig) => {
formData.dynamicConfigArray = deletePlatformByKey(formData.dynamicConfigArray, cfg.platformKey)
// 替换删除后的平台配置
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
// 删除配置
delete formData.setting[cfg.platformKey]
deleteKey(cfg.platformKey)
Expand All @@ -137,7 +137,7 @@ const handlePlatformEnabled = async (cfg: DynamicConfig) => {
formData.dynamicConfigArray = replacePlatformByKey(formData.dynamicConfigArray, cfg.platformKey, cfg)
// 替换删除后的平台配置
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
// 更新状态
await updateSetting(formData.setting)
}
Expand All @@ -160,9 +160,14 @@ const handleOpenBrowserAuth = async (cfg: DynamicConfig) => {
}
const handleValidateWebAuth = (cfg: DynamicConfig) => {
// ElMessage.info("验证中,请关注状态,没有授权表示不可用,已授权表示该平台可正常使用...")
ElMessage.success("验证成功,该平台可正常使用")
// ElMessage.error(("验证失败,该平台将不可用"))
const cookieCb = async (coo) => {
ElMessage.info("验证中,请关注状态,没有授权表示不可用,已授权表示该平台可正常使用...")
console.log("coo=>", coo)
// ElMessage.success("验证成功,该平台可正常使用")
// ElMessage.error(("验证失败,该平台将不可用"))
}
openBrowserWindow(cfg.authUrl, cookieCb)
}
const handleImportPre = () => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/set/publish/PlatformAddForm.vue
Expand Up @@ -132,7 +132,7 @@ const submitForm = async (formEl) => {
// 转换格式并保存
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
// 初始化一个空配置
formData.setting[newCfg.platformKey] = "{}"
await updateSetting(formData.setting)
Expand Down
2 changes: 1 addition & 1 deletion src/components/set/publish/PlatformUpdateForm.vue
Expand Up @@ -114,7 +114,7 @@ const submitForm = async (formEl) => {
// 转换格式并保存
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
// 更新配置
await updateSetting(formData.setting)
Expand Down
Expand Up @@ -122,7 +122,7 @@ const saveConf = async (hideTip?: any) => {
formData.setting[props.apiType] = formData.cfg
// 平台基本配置
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
await updateSetting(formData.setting)
if (hideTip !== true) {
Expand Down
Expand Up @@ -121,7 +121,7 @@ const saveConf = async (hideTip?: any) => {
formData.setting[props.apiType] = formData.cfg
// 平台基本配置
const dynJsonCfg = setDynamicJsonCfg(formData.dynamicConfigArray)
formData.setting[DYNAMIC_CONFIG_KEY] = JSON.stringify(dynJsonCfg)
formData.setting[DYNAMIC_CONFIG_KEY] = dynJsonCfg
await updateSetting(formData.setting)
if (hideTip !== true) {
Expand Down
136 changes: 134 additions & 2 deletions src/utils/widgetUtils.ts
Expand Up @@ -23,16 +23,148 @@
* questions.
*/
import { useSiyuanDevice } from "~/src/composables/useSiyuanDevice.ts"
import { StrUtil } from "zhi-common"
import { BrowserUtil, SiyuanDevice } from "zhi-device"
import { createAppLogger } from "~/src/utils/appLogger.ts"

const logger = createAppLogger("widget-utils")

/**
* 打开网页弹窗
*/
export const openBrowserWindow = (url: string) => {
export const openBrowserWindow = (url: string, cookieCb?: any) => {
const { isInSiyuanWidget } = useSiyuanDevice()

if (isInSiyuanWidget()) {
alert(`${url}=>当前挂件模式`)
const isDev = false
const isModel = false
const isShow = !cookieCb
doOpenBrowserWindow(url, undefined, undefined, isDev, isModel, isShow, cookieCb)
} else {
window.open(url)
}
}

/**
* 打开新窗口
*
* 示例:
*
* ```
* ## development
* openBrowserWindow("https://www.baidu.com", undefined, undefined, true, false)
* openBrowserWindow("https://www.baidu.com", { "key1": "value1", "key2": "value2" }, undefined, true, false)
*
* ## production
* openBrowserWindow("https://www.baidu.com")
* ```
*
* @param url - url
* @param params - 参数
* @param win - 父窗口
* @param isDev - 是否打开开发者工具
* @param modal - 是否模态
* @param isShow - 是否显示
* @param cookieCallback - 窗口关闭回调
*/
const doOpenBrowserWindow = (
url: string,
params?: Record<string, string>,
win?: any,
isDev = false,
modal = false,
isShow = true,
cookieCallback
) => {
try {
if (StrUtil.isEmptyString(url)) {
logger.error("Url cannot be empty")
return
}

const { isInSiyuanWidget } = useSiyuanDevice()
if (!BrowserUtil.isElectron() && !isInSiyuanWidget) {
logger.info("BrowserWindow can ony be available in siyuan Electron environment")
return
}

if (params) {
Object.keys(params).forEach((key: string) => {
const value = params[key]
url = BrowserUtil.setUrlParameter(url, key, value)
})
}

logger.info(StrUtil.f("Opening a new BrowserWindow from url => {0}", url))

const mainWin = win ?? SiyuanDevice.siyuanWindow()
const { app, BrowserWindow, getCurrentWindow } = mainWin.require("@electron/remote")
const remote = mainWin.require("@electron/remote").require("@electron/remote/main")
const mainWindow = getCurrentWindow()
const newWindow = new BrowserWindow({
parent: mainWindow,
width: 900,
height: 750,
show: isShow,
resizable: true,
modal: modal,
icon: SiyuanDevice.browserJoinPath(
SiyuanDevice.siyuanWindow().siyuan.config.system.appDir,
"stage",
"icon-large.png"
),
titleBarOverlay: {
color: "#cccccca5",
symbolColor: "black",
},
webPreferences: {
nativeWindowOpen: true,
nodeIntegration: true,
webviewTag: true,
webSecurity: false,
contextIsolation: false,
},
})

newWindow.webContents.userAgent = `SiYuan/${app.getVersion()} https://b3log.org/siyuan Electron`
// 允许
remote.enable(newWindow.webContents)
if (isDev) {
newWindow.webContents.openDevTools()
}

// 监听 close 事件
newWindow.on("close", (evt) => {
logger.info("窗口关闭事件触发")
})
newWindow.loadURL(url)

// 读取指定域的所有 Cookie
if (cookieCallback) {
const readCookies = () => {
// https://www.electronjs.org/zh/docs/latest/api/session
const ses = newWindow.webContents.session

// 设置将要读取的域名
const domain = "zhihu.com"

ses.cookies
.get({ domain })
.then((cookies) => {
logger.info(`读取cookie事件触发,准备读取 ${domain} 下的所有 Cookie`)
cookieCallback(cookies)
})
.catch((error) => {
console.error(`读取 Cookie 失败:${error}`)
})
}
readCookies()
// 将窗口隐藏起来
newWindow.once("ready-to-show", () => {
newWindow.hide()
})
}
} catch (e) {
logger.error("Open browser window failed", e)
}
}
2 changes: 1 addition & 1 deletion syp.config.ts
Expand Up @@ -29,7 +29,7 @@ interface ISypConfig {
// version?: ""
lang?: "zh_CN" | "en_US"
// 平台总的集合
[DYNAMIC_CONFIG_KEY]?: string
[DYNAMIC_CONFIG_KEY]?: any

// [平台key1]: {平台配置1}
// [平台key2]: {平台配置2}
Expand Down

0 comments on commit b2501b3

Please sign in to comment.