Skip to content

Commit

Permalink
暂存
Browse files Browse the repository at this point in the history
  • Loading branch information
luoluoTH committed Jan 8, 2025
1 parent 5b663b6 commit e7a27d7
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 27 deletions.
2 changes: 1 addition & 1 deletion app/renderer/src/main/src/apiUtils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export const httpUploadFile: APIFunc<httpUploadFileFileInfo, string> = (request,
/** @name 删除 OSS 资源 */
export const httpDeleteOSSResource: APIFunc<API.DeleteOssResource, API.ActionSucceeded> = (info, hiddenError) => {
return new Promise((resolve, reject) => {
// console.log("method:delete|api:oss/resource\n", JSON.stringify(info))
console.log("method:delete|api:oss/resource\n", JSON.stringify(info))
NetWorkApi<API.DeleteOssResource, API.ActionSucceeded>({
method: "delete",
url: "oss/resource",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
docTitle.observe((yTextEvent, transaction) => this.docObserveTitle(yTextEvent, transaction))

const url = wsUrl + "api/handle/tow/way/ws"
console.log("wsUrl", url)
// const url = "ws://localhost:1880/ws/my-room"
this.wsProvider = new WebsocketProvider(url, this.wsRequest.notepadHash, this.doc, {
connect: true,
Expand All @@ -94,6 +95,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
heardImg: this.user.heardImg
})
this.wsProvider.on("status", (payload) => {
console.log("wsProvider-status", payload)
// 获取当前所有用户的状态
const users = this.getOnlineUser()
this.setOnlineUsers([...users])
Expand All @@ -104,14 +106,18 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
}
})
this.wsProvider.on("connection-close", (payload) => {
console.log("wsProvider-close", payload)
this.emit("offline-after", [payload])
})
this.collabService.bindDoc(this.doc).setAwareness(this.wsProvider.awareness)
this.wsProvider.once("synced", (isSynced: boolean) => {
console.log("wsProvider-synced", isSynced)
this.setCollabStatus({...this.collabStatus, isSynced})
})

this.wsProvider.once("online-user-count", (onlineUserCount: number) => {
const users = this.getOnlineUser()
console.log("wsProvider-online-user-count----", users, onlineUserCount, this.collabStatus.isSynced)
if (onlineUserCount < 2 && this.collabStatus.isSynced) {
this.collabService.applyTemplate(template).connect()
} else if (this.collabStatus.isSynced) {
Expand All @@ -120,6 +126,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
})

this.wsProvider.on("saveStatus", ({saveStatus}) => {
console.log("wsProvider-saveStatus", saveStatus)
this.setCollabStatus({...this.collabStatus, saveStatus})
})
// 监听在线用户数据
Expand All @@ -131,6 +138,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
}

private docObserveTitle(yarrayEvent: YTextEvent, tr: Transaction) {
console.log("docTitle-docObserveTitle", yarrayEvent, tr)
if (tr.local) return
const value = (yarrayEvent.delta[0]?.insert as string) || ""
this.onSetTitle(value)
Expand All @@ -139,6 +147,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
private getOnlineUser() {
const awarenessMap = this.wsProvider.awareness.getStates()
const users = Array.from(awarenessMap, ([key, value]) => value.user)
console.log("wsProvider-getOnlineUser", users)
return users
}

Expand Down Expand Up @@ -171,6 +180,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
setTitle(value) {
const oldValue = this.doc.getText("title").toString()
if (isEqual(oldValue, value)) return
console.log("docTitle-setTitle", oldValue, value)
this.doc.getText("title").applyDelta([{insert: value}])
}

Expand All @@ -190,6 +200,7 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
}
if (this.wsProvider && this.wsProvider?.ws && this.wsProvider.ws?.readyState === WebSocket.OPEN) {
const sendValueString = JSON.stringify(v)
console.log("getSendData-sendContent", sendValueString)
this.wsProvider?.ws?.send(Buffer.from(sendValueString))
}
}
Expand All @@ -199,12 +210,18 @@ export class CollabManager extends ObservableV2<CollabManagerEvents> {
super.destroy()
}
connect() {
this.wsProvider?.connect()
this.collabService?.connect()
console.log("connect")
Promise.resolve().then(() => {
this.wsProvider?.connect()
this.collabService?.connect()
})
}

disconnect() {
this.collabService?.disconnect()
this.wsProvider?.disconnect()
console.log("disconnect")
Promise.resolve().then(() => {
this.collabService?.disconnect()
this.wsProvider?.disconnect()
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import * as url from "lib0/url"
import * as env from "lib0/environment"
import {
MessageHandlersProps,
NotepadSaveStatusProps,
NotepadWsRequest,
ObservableEvents,
WebsocketProviderAwarenessUpdateHandler,
Expand Down Expand Up @@ -114,6 +113,16 @@ const setupWS = (provider: WebsocketProvider) => {
const bytes = Buffer.from(event.data).toString()
const data: NotepadWsRequest = JSON.parse(bytes)
const yjsParams = Buffer.from(data.yjsParams, "base64")
console.log("websocket.onmessage-data", data)

provider.wsLastMessageReceived = time.getUnixTime()
const encoder = readMessage(provider, yjsParams, true)

if (encoding.length(encoder) > 1) {
const messageUint8Array = encoding.toUint8Array(encoder)
const value = provider?.getSendData({buf: messageUint8Array, docType: notepadActions.edit})
websocket.send(value)
}
if (!!data.params.userCount && data.params.docType === notepadActions.join) {
// 目前加入类型的消息会修改在线人数,用来做连接文档的初始化内容
provider.onlineUserCount = data.params.userCount
Expand All @@ -125,23 +134,19 @@ const setupWS = (provider: WebsocketProvider) => {
}
])
}
provider.wsLastMessageReceived = time.getUnixTime()
const encoder = readMessage(provider, yjsParams, true)

if (encoding.length(encoder) > 1) {
const messageUint8Array = encoding.toUint8Array(encoder)
const value = provider?.getSendData({buf: messageUint8Array, docType: notepadActions.edit})
websocket.send(value)
}
} catch (error) {}
}
websocket.onerror = (event) => {
console.log("websocket.onerror-event", event)
provider.emit("connection-error", [event, provider])
}
websocket.onclose = (event) => {
console.log("websocket.onclose-event", event, provider.data?.notepadHash)
console.log("closeWebsocketConnection------1", provider.data?.notepadHash)
closeWebsocketConnection(provider, websocket, event)
}
websocket.onopen = () => {
console.log("websocket.onopen")
provider.wsLastMessageReceived = time.getUnixTime()
provider.wsconnecting = false
provider.wsconnected = true
Expand Down Expand Up @@ -189,10 +194,12 @@ const setupWS = (provider: WebsocketProvider) => {
* @param {CloseEvent} event
*/
const closeWebsocketConnection = (provider: WebsocketProvider, ws: WebSocket, event?: CloseEvent) => {
console.log("closeWebsocketConnection---------2", provider.data?.notepadHash)
if (ws === provider.ws) {
console.log("closeWebsocketConnection------3", provider.data?.notepadHash, event)
if (event) provider.emit("connection-close", [event, provider])
provider.ws = null
ws.close()
// ws.close()
provider.wsconnecting = false
if (provider.wsconnected) {
provider.wsconnected = false
Expand Down Expand Up @@ -264,6 +271,7 @@ const broadcastMessage = (provider, buf) => {
export class WebsocketProvider extends ObservableV2<ObservableEvents> {
/**
* @param {string} serverUrl
* @param {string} room
* @param {Y.Doc} doc
* @param {object} opts
* @param {boolean} [opts.connect]
Expand Down Expand Up @@ -375,6 +383,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
if (resyncInterval > 0) {
this._resyncInterval = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
console.log("_resyncInterval")
// resend sync step 1
const encoder = encoding.createEncoder()
encoding.writeVarUint(encoder, messageSync)
Expand Down Expand Up @@ -408,6 +417,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
token
}
const jsonString = JSON.stringify(value)
console.log("getSendData", jsonString)
const finalArrayBuffer = Buffer.from(jsonString)
return finalArrayBuffer
} catch (error) {
Expand All @@ -434,6 +444,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
*/
this._updateHandler = (update: Uint8Array, origin: any, ydoc: Y.Doc, tr: Y.Transaction) => {
if (origin !== this) {
console.log("_updateHandler", origin, ydoc, tr)
const encoder = encoding.createEncoder()
encoding.writeVarUint(encoder, messageSync)
syncProtocol.writeUpdate(encoder, update)
Expand Down Expand Up @@ -463,6 +474,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
if (this.wsconnected && messageReconnectTimeout < time.getUnixTime() - this.wsLastMessageReceived) {
// no message received in a long time - not even your own awareness
// updates (which are updated every 15 seconds)
console.log("closeWebsocketConnection------5", this.data?.notepadHash)
if (this.ws) closeWebsocketConnection(this, /** @type {WebSocket} */ this.ws)
}
}, messageReconnectTimeout / 10)
Expand All @@ -485,6 +497,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
set synced(state) {
if (this._synced !== state) {
this._synced = state
console.log("synced", state)
this.emit("synced", [state])
this.emit("sync", [state])
}
Expand All @@ -499,6 +512,7 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
set onlineUserCount(count) {
if (this._onlineUserCount !== count) {
this._onlineUserCount = count
console.log("synced-_onlineUserCount", count)
this.emit("online-user-count", [count])
}
}
Expand Down Expand Up @@ -571,13 +585,15 @@ export class WebsocketProvider extends ObservableV2<ObservableEvents> {
if (!!this.ws && this.ws?.readyState === WebSocket.OPEN) {
const value = this.getSendData({buf: new Uint8Array(), docType: notepadActions.leave})
this.ws?.send(value)
console.log("closeWebsocketConnection-4", this.data?.notepadHash)
closeWebsocketConnection(this, this.ws)
}
}

connect(): void {
this.shouldConnect = true
if (!this.wsconnected && this.ws === null) {
console.log("connect-setupWS")
setupWS(this)
this.connectBc()
}
Expand Down
2 changes: 1 addition & 1 deletion app/renderer/src/main/src/pages/EnterpriseJudgeLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ const EnterpriseJudgeLogin: React.FC<EnterpriseJudgeLoginProps> = (props) => {
</div>
) : (
<>
{activateLicense ? (
{true ? (
<div style={{width: 480, margin: "0 auto", paddingTop: 200, height: "100%"}}>
<ConfigPrivateDomain
enterpriseLogin={true}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ export const MainOperatorContent: React.FC<MainOperatorContentProps> = React.mem
const addModifyNotepad = useMemoizedFn(async (data) => {
try {
let verbose = ""
console.log('addModifyNotepad',data?.notepadHash)
if (!!data?.notepadHash) {
const res = await apiGetNotepadDetail(data.notepadHash)
verbose = res?.title || ""
Expand All @@ -646,7 +647,9 @@ export const MainOperatorContent: React.FC<MainOperatorContentProps> = React.mem
}
}
)
} catch (error) {}
} catch (error) {

}
})
const addScanPort = useMemoizedFn((data) => {
openMenuPage(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const apiGetUserSearch: APIFunc<UserSearchQuery, API.UserOrdinaryResponse
*/
export const apiSetNotepadPermission: APIFunc<API.PostNotepadPermissionRequest, API.ActionSucceeded> = (query) => {
return new Promise((resolve, reject) => {
console.log("apiSetNotepadPermission-query", query)
try {
NetWorkApi<API.PostNotepadPermissionRequest, API.ActionSucceeded>({
method: "post",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export const apiGetNotepadList: APIFunc<GetNotepadRequestProps, API.GetNotepadRe
*/
export const apiSaveNotepad: APIFunc<API.PostNotepadRequest, string> = (params, hiddenError) => {
return new Promise((resolve, reject) => {
console.log("apiSaveNotepad", params)
NetWorkApi<API.PostNotepadRequest, string>({
method: "post",
url: "notepad",
Expand Down Expand Up @@ -118,12 +119,14 @@ export const apiGetNotepadDetail: APIFunc<string, API.GetNotepadList> = (hash, h
*/
export const apiDeleteNotepadDetail: APIFunc<API.DeleteNotepadRequest, API.ActionFailed> = (params, hiddenNotify) => {
return new Promise((resolve, reject) => {
console.log("apiDeleteNotepadDetail-params", params)
NetWorkApi<API.DeleteNotepadRequest, API.ActionFailed>({
method: "delete",
url: "notepad",
data: params
})
.then((res) => {
console.log("apiDeleteNotepadDetail-res", res)
// 后端返回的结构API.ActionFailed,根据ok判断失败还是成功
if (res.ok) {
if (!hiddenNotify) yakitNotify("success", res.reason)
Expand Down Expand Up @@ -159,8 +162,10 @@ export const onBaseNotepadDown: APIFunc<API.NotepadDownloadRequest, SaveDialogRe
const params: API.NotepadDownloadRequest = {
...value
}
console.log("onBaseNotepadDown-params", params)
apiDownloadNotepad(params)
.then((res) => {
console.log("onBaseNotepadDown-res", res)
saveDialogAndGetLocalFileInfo((res as string) || "")
.then(resolve)
.catch(reject)
Expand Down
19 changes: 9 additions & 10 deletions app/renderer/src/main/src/utils/webSocket/webSocket.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import emiter from "../eventBus/eventBus"
import {failed} from "@/utils/notification"
import { Uint8ArrayToString } from "../str"
import { API } from "@/services/swagger/resposeType"
import {Uint8ArrayToString} from "../str"
import {API} from "@/services/swagger/resposeType"
const {ipcRenderer} = window.require("electron")


/**@name webSocket是否开启 */
export let webSocketStatus = false

export const startWebSocket = () => {
ipcRenderer.on("client-socket-message", (e, data:Uint8Array) => {
ipcRenderer.on("client-socket-message", (e, data: Uint8Array) => {
try {
const obj = JSON.parse(Uint8ArrayToString(data))
console.log("client-socket-message", obj)
switch (obj.messageType) {
case "messageLog":
emiter.emit("onRefreshMessageSocket", JSON.stringify(obj.params))
break;
}

break
}
} catch (error) {}
})

Expand All @@ -34,7 +33,7 @@ export const startWebSocket = () => {
webSocketStatus = false
})

ipcRenderer.on("client-socket-error", (e, error:any) => {
ipcRenderer.on("client-socket-error", (e, error: any) => {
// console.log("webSocket错误",error);
})
}
Expand All @@ -47,6 +46,6 @@ export const closeWebSocket = () => {
ipcRenderer.removeAllListeners("client-socket-error")
}

export const sendWebSocket = (data:API.WsRequest) => {
ipcRenderer.invoke("socket-send",data)
export const sendWebSocket = (data: API.WsRequest) => {
ipcRenderer.invoke("socket-send", data)
}

0 comments on commit e7a27d7

Please sign in to comment.