From 18f55e8386b05b6af6cf1a41a8d2fba0bb58323a Mon Sep 17 00:00:00 2001 From: godo Date: Thu, 12 Sep 2024 09:41:25 +0800 Subject: [PATCH] change update --- frontend/components.d.ts | 1 + .../components/desktop/DesktopBackground.vue | 2 +- frontend/src/stores/localchat.ts | 64 +++++++++---------- frontend/src/stores/message.ts | 34 ++++++++++ frontend/src/stores/upgrade.ts | 22 +++---- frontend/src/system/config.ts | 5 +- frontend/src/system/index.ts | 18 +++++- godo/localchat/server.go | 1 + godo/sys/update.go | 53 +++++++++++---- 9 files changed, 138 insertions(+), 62 deletions(-) create mode 100644 frontend/src/stores/message.ts diff --git a/frontend/components.d.ts b/frontend/components.d.ts index 33e7e69..9f7913a 100644 --- a/frontend/components.d.ts +++ b/frontend/components.d.ts @@ -53,6 +53,7 @@ declare module 'vue' { ElColorPicker: typeof import('element-plus/es')['ElColorPicker'] ElDatePicker: typeof import('element-plus/es')['ElDatePicker'] ElDialog: typeof import('element-plus/es')['ElDialog'] + ElDrawer: typeof import('element-plus/es')['ElDrawer'] ElEmpty: typeof import('element-plus/es')['ElEmpty'] ElForm: typeof import('element-plus/es')['ElForm'] ElFormItem: typeof import('element-plus/es')['ElFormItem'] diff --git a/frontend/src/components/desktop/DesktopBackground.vue b/frontend/src/components/desktop/DesktopBackground.vue index 3ddc442..9380e98 100644 --- a/frontend/src/components/desktop/DesktopBackground.vue +++ b/frontend/src/components/desktop/DesktopBackground.vue @@ -32,7 +32,7 @@ watch(rootState.options, (nv) => { }); function refershBack(val: string | undefined) { background.value = val || "#3A98CE"; - console.log(background.value) + //console.log(background.value) if (background.value || background.value.startsWith("/image/")) { backgroundType.value = "image"; } else { diff --git a/frontend/src/stores/localchat.ts b/frontend/src/stores/localchat.ts index b93330a..ec42304 100644 --- a/frontend/src/stores/localchat.ts +++ b/frontend/src/stores/localchat.ts @@ -2,12 +2,11 @@ import { defineStore } from 'pinia' import emojiList from "@/assets/emoji.json" import { ref, toRaw } from "vue"; import { db } from './db' -import { fetchPost, getChatUrl, getUrl, setSystemKey } from "@/system/config"; +import { getSystemConfig, setSystemKey } from "@/system/config"; import { isValidIP } from "@/util/common"; import { notifyError, notifySuccess } from "@/util/msg"; export const useLocalChatStore = defineStore('localChatStore', () => { - //const config = getSystemConfig(); - const chatUrl = getChatUrl(); + const config = getSystemConfig(); //const sys = inject("system"); const userList: any = ref([]) const msgList: any = ref([]) @@ -39,6 +38,7 @@ export const useLocalChatStore = defineStore('localChatStore', () => { setUserList(ips); } if(data.messages){ + const apiUrl = `${config.apiUrl}/localchat/viewimage?img=` for(let ip in data.messages){ const msgList:any = data.messages[ip] if(!msgList || msgList.length < 1)return; @@ -50,10 +50,7 @@ export const useLocalChatStore = defineStore('localChatStore', () => { addText(msg) } else if (msg.type === "image"){ - msg.message = msg.message.map((d: any) => { - const url = `/localchat/viewimage?img=${encodeURIComponent(d)}` - return getUrl(url) - }) + msg.message = msg.message.map((d: any) => `${apiUrl}${encodeURIComponent(d)}`) //console.log(msg) addText(msg) } @@ -321,27 +318,24 @@ export const useLocalChatStore = defineStore('localChatStore', () => { return } const content = toRaw(sendInfo.value) - let saveContent:any + let saves:any if (type === 'image') { - saveContent = content.map((d: any) => { - const url = `/localchat/viewimage?img=${encodeURIComponent(d)}` - return getUrl(url) - }) + const apiUrl = `${config.apiUrl}/localchat/viewimage?img=` + saves = content.map((d: any) => `${apiUrl}${encodeURIComponent(d)}`) }else{ - saveContent = content + saves = content } - console.log(saveContent) const saveMsg: any = { type: type, targetId: chatTargetId.value, targetIp: chatTargetIp.value, - content: saveContent, + content: saves, createdAt: Date.now(), isMe: true, isRead: false, status: 'sending' } - console.log(saveMsg) + //console.log(saveMsg) const msgId = await db.addOne('chatmsg', saveMsg) //await getMsgList() @@ -353,20 +347,23 @@ export const useLocalChatStore = defineStore('localChatStore', () => { ip: saveMsg.targetIp } if (targetUser.isOnline) { - let postUrl = `${chatUrl}/message` + let postUrl = `${config.apiUrl}/localchat/message` if(type === 'applyfile'){ messages.message = { fileList: messages.message, msgId: msgId, status: 'apply' } - postUrl = `${chatUrl}/applyfile` + postUrl = `${config.apiUrl}/localchat/applyfile` } if(type === 'image'){ - postUrl = `${chatUrl}/sendimage` + postUrl = `${config.apiUrl}/localchat/sendimage` } - const completion = await fetchPost(postUrl, JSON.stringify(messages)) + const completion = await fetch(postUrl, { + method: "POST", + body: JSON.stringify(messages), + }) //console.log(completion) if (!completion.ok) { console.log(completion) @@ -393,8 +390,11 @@ export const useLocalChatStore = defineStore('localChatStore', () => { message: item.content.msgId, ip: item.targetIp } - const postUrl = `${chatUrl}/cannelfile` - const coms = await fetchPost(postUrl, JSON.stringify(messages)) + const postUrl = `${config.apiUrl}/localchat/cannelfile` + const coms = await fetch(postUrl, { + method: "POST", + body: JSON.stringify(messages), + }) if (!coms.ok) { console.log(coms) notifyError("确认失败!") @@ -421,8 +421,11 @@ export const useLocalChatStore = defineStore('localChatStore', () => { message: item.content, ip: item.targetIp } - const postUrl = `${chatUrl}/accessfile` - const coms = await fetchPost(postUrl, JSON.stringify(messages)) + const postUrl = `${config.apiUrl}/localchat/accessfile` + const coms = await fetch(postUrl, { + method: "POST", + body: JSON.stringify(messages), + }) if (!coms.ok) { //console.log(coms) notifyError("确认失败!") @@ -439,18 +442,16 @@ export const useLocalChatStore = defineStore('localChatStore', () => { }else{ notifyError(res.message) } - // item.content.status = 'accessing' - // //console.log(item) - // await db.update('chatmsg', item.id, toRaw(item)) - // await getMsgList() - //notifySuccess("确认成功!") } } async function saveConfig(conf:any){ conf = toRaw(conf) //console.log(conf) - const postUrl = `${chatUrl}/setting` - const coms = await fetchPost(postUrl, JSON.stringify(conf)) + const postUrl = `${config.apiUrl}/localchat/setting` + const coms = await fetch(postUrl, { + method: "POST", + body: JSON.stringify(conf), + }) if (!coms.ok) { //console.log(coms) notifyError("保存失败!") @@ -461,7 +462,6 @@ export const useLocalChatStore = defineStore('localChatStore', () => { } } - return { userList, navList, diff --git a/frontend/src/stores/message.ts b/frontend/src/stores/message.ts new file mode 100644 index 0000000..fe924fc --- /dev/null +++ b/frontend/src/stores/message.ts @@ -0,0 +1,34 @@ +import { getUrl } from "@/system/config"; +import { defineStore } from "pinia"; +import { useUpgradeStore } from "./upgrade"; +export const useMessageStore = defineStore('messageStore', () => { + const upgradeStore = useUpgradeStore(); + function systemMessage(){ + const url = getUrl('/system/message',false); + const source = new EventSource(url); + + source.onmessage = function(event) { + const data = JSON.parse(event.data); + //console.log(data) + handleMessage(data); + }; + source.onerror = function(event) { + console.error('EventSource error:', event); + }; + } + async function handleMessage(message:any) { + switch (message.type) { + case 'update': + upgradeStore.checkUpdate(message.data) + break; + case 'chat': + + break; + default: + console.warn('Unknown message type:', message.type); + } + } + return { + systemMessage + } +}) \ No newline at end of file diff --git a/frontend/src/stores/upgrade.ts b/frontend/src/stores/upgrade.ts index 0a901e5..d5e3a83 100644 --- a/frontend/src/stores/upgrade.ts +++ b/frontend/src/stores/upgrade.ts @@ -1,6 +1,6 @@ import { defineStore } from "pinia"; import { ref } from "vue"; -import { setSystemKey, parseJson, getSystemConfig, getUrl } from '@/system/config' +import { setSystemKey, parseJson, getSystemConfig } from '@/system/config' import { RestartApp } from '@/util/goutil'; import { ElMessage } from 'element-plus' import { t } from '@/i18n'; @@ -37,9 +37,8 @@ export const useUpgradeStore = defineStore('upgradeStore', () => { return 0; } function systemMessage(){ - //const config = getSystemConfig(); - const apiUrl = getUrl('/system/message',false) - const source = new EventSource(apiUrl); + const config = getSystemConfig(); + const source = new EventSource(`${config.apiUrl}/system/message`); source.onmessage = function(event) { const data = JSON.parse(event.data); @@ -97,24 +96,19 @@ export const useUpgradeStore = defineStore('upgradeStore', () => { } } function changeUrl(list : any){ - const config = getSystemConfig(); list.forEach((item:any) => { if(item.img && item.img.indexOf('http') == -1){ - if(config.userType === 'person'){ - item.img = `https://godoos.com${item.img}` - }else{ - item.img = `${config.userInfo.url}${item.img}` - } + item.img = `https://godoos.com${item.img}` } }); return list } async function update() { - //const apiUrl = getApiUrl() - const upUrl = `/system/update?url=${updateUrl.value}` - const apiUrl = getUrl(upUrl,true) - const upRes = await fetch(apiUrl) + const config = getSystemConfig(); + const upUrl = `${config.apiUrl}/system/update?url=${updateUrl.value}` + + const upRes = await fetch(upUrl) if (!upRes.ok) return; const reader: any = upRes.body?.getReader(); if (!reader) { diff --git a/frontend/src/system/config.ts b/frontend/src/system/config.ts index a309e26..0b0f1dd 100644 --- a/frontend/src/system/config.ts +++ b/frontend/src/system/config.ts @@ -101,6 +101,9 @@ export const getSystemConfig = (ifset = false) => { password: '', }; } + if(config.userType == 'member'){ + config.account.ad = false + } if (!config.storenet) { config.storenet = { url: '', @@ -183,7 +186,7 @@ export function getChatUrl() { if (config.userType == 'person') { return config.apiUrl + '/localchat' } else { - return config.userInfo.url + '/localchat' + return config.userInfo.url + '/chat' } } export function getUrl(url: string, islast = true) { diff --git a/frontend/src/system/index.ts b/frontend/src/system/index.ts index ebc28cb..ca2f091 100644 --- a/frontend/src/system/index.ts +++ b/frontend/src/system/index.ts @@ -24,6 +24,7 @@ import { pick } from '../util/modash'; import { Tray, TrayOptions } from './menu/Tary'; import { getSystemConfig, getSystemKey, setSystemKey, setSystemConfig, clearSystemConfig, getFileUrl, fetchGet, getClientId } from './config' import { useUpgradeStore } from '@/stores/upgrade'; +import { useMessageStore } from '@/stores/message'; import { RestartApp } from '@/util/goutil'; import { notifyError } from '@/util/msg'; @@ -103,14 +104,25 @@ export class System { this.initBackground(); // 初始化壁纸 this.refershAppList(); + this.checkMessages(); + this.emit('start'); + this._ready && this._ready(this); + + } + private checkMessages() { + const config = getSystemConfig(); + if (config.userType == 'member') { + setTimeout(() => { + const messageStore = useMessageStore(); + messageStore.systemMessage() + }, 3000); + } setTimeout(() => { const upgradeStore = useUpgradeStore(); upgradeStore.systemMessage() }, 6000); - this.emit('start'); - this._ready && this._ready(this); - + } /** * @description: 判断是否登录 diff --git a/godo/localchat/server.go b/godo/localchat/server.go index 6300981..142dc32 100644 --- a/godo/localchat/server.go +++ b/godo/localchat/server.go @@ -48,6 +48,7 @@ type UserStatus struct { Hostname string `json:"hostname"` IP string `json:"ip"` Time time.Time `json:"time"` + Avatar string `json:"avatar"` } var OnlineUsers = make(map[string]UserStatus) diff --git a/godo/sys/update.go b/godo/sys/update.go index 16980bd..69ce8ae 100644 --- a/godo/sys/update.go +++ b/godo/sys/update.go @@ -26,10 +26,12 @@ package sys import ( "encoding/json" "fmt" + "godo/files" "godo/libs" "io" "log" "net/http" + "os" "path/filepath" "time" @@ -95,13 +97,25 @@ func (pr *ProgressReader) Read(p []byte) (n int, err error) { } func UpdateAppHandler(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") + if url == "" { + libs.ErrorMsg(w, "url is empty") + return + } + downloadDir := libs.GetCacheDir() + filePath := filepath.Join(downloadDir, filepath.Base(url)) resp, err := http.Get(url) if err != nil { return } defer resp.Body.Close() pr := &ProgressReader{reader: resp.Body} - + // 打开文件 + out, err := os.Create(filePath) + if err != nil { + libs.ErrorMsg(w, "open file error") + return + } + defer out.Close() ticker := time.NewTicker(200 * time.Millisecond) defer ticker.Stop() flusher, ok := w.(http.Flusher) @@ -142,10 +156,26 @@ func UpdateAppHandler(w http.ResponseWriter, r *http.Request) { } } }() - - var updateFile io.Reader = pr + // 复制数据 + if _, err := io.Copy(out, pr); err != nil { + libs.ErrorMsg(w, "copy error") + return + } + // 解压缩文件 + unzippedFilePath, err := files.Unzip(filePath, downloadDir) + if err != nil { + libs.ErrorMsg(w, "unzip error") + return + } + // 将解压缩后的文件读取为 io.Reader + unzipFile, err := os.Open(unzippedFilePath) + if err != nil { + libs.ErrorMsg(w, "open unzip file error") + return + } + defer unzipFile.Close() // apply update - err = selfupdate.Apply(updateFile, selfupdate.Options{}) + err = selfupdate.Apply(unzipFile, selfupdate.Options{}) if err != nil { if rerr := selfupdate.RollbackError(err); rerr != nil { http.Error(w, "update error:"+rerr.Error(), http.StatusInternalServerError) @@ -156,33 +186,34 @@ func UpdateAppHandler(w http.ResponseWriter, r *http.Request) { // 更新完成后发送响应给前端 json.NewEncoder(w).Encode(map[string]bool{"updateCompleted": true}) } -func GetUpdateInfo() (ServerRes, error) { +func GetUpdateInfo() (UpdateVersionReq, error) { + var errs UpdateVersionReq var updateInfo ServerRes info, err := libs.GetSystemInfo() if err != nil { - return updateInfo, fmt.Errorf("update error get info:" + err.Error()) + return errs, fmt.Errorf("update error get info:" + err.Error()) } updateUrl := "https://godoos.com/version?info=" + info //log.Printf("updateUrl:%v", updateUrl) res, err := http.Get(updateUrl) if err != nil { - return updateInfo, fmt.Errorf("update error get url:" + err.Error()) + return errs, fmt.Errorf("update error get url:" + err.Error()) } defer res.Body.Close() if res.StatusCode != 200 { - return updateInfo, fmt.Errorf("update error get url") + return errs, fmt.Errorf("update error get url") } body, err := io.ReadAll(res.Body) if err != nil { - return updateInfo, fmt.Errorf("update error read body:" + err.Error()) + return errs, fmt.Errorf("update error read body:" + err.Error()) } err = json.Unmarshal(body, &updateInfo) //log.Printf("updateInfo:%v", updateInfo) if err != nil { fmt.Println("Error unmarshalling JSON:", err) - return updateInfo, fmt.Errorf("update error unmarshal:" + err.Error()) + return errs, fmt.Errorf("update error unmarshal:" + err.Error()) } - return updateInfo, nil + return updateInfo.Data, nil } func GetUpdateUrlHandler(w http.ResponseWriter, r *http.Request) { updateInfo, err := GetUpdateInfo()