refactor: abstract and simplify the communication between home page and vscode
* refactor the infertace in index.html * adapt the change of interface in home page and vscode
This commit is contained in:
		
							
								
								
									
										12
									
								
								src/home.ts
									
									
									
									
									
								
							
							
						
						
									
										12
									
								
								src/home.ts
									
									
									
									
									
								
							@@ -29,20 +29,22 @@ export default class DSHome {
 | 
			
		||||
 | 
			
		||||
    panel.webview.onDidReceiveMessage(
 | 
			
		||||
      async (message) => {
 | 
			
		||||
        const data = message.data
 | 
			
		||||
        switch (message.command) {
 | 
			
		||||
          case 'firstOpenRemoteFolder':
 | 
			
		||||
            await this.remoteContainer.firstConnect(message.host, message.username, message.port)
 | 
			
		||||
            const path = data.path
 | 
			
		||||
            await this.remoteContainer.firstConnect(data.host, data.username, data.port)
 | 
			
		||||
            .then((_res) => {
 | 
			
		||||
              if (_res == 'success') {
 | 
			
		||||
                //  only success then open folder
 | 
			
		||||
                this.remoteContainer.openRemoteFolder(message.host, message.path);
 | 
			
		||||
                this.remoteContainer.openRemoteFolder(data.host, path);
 | 
			
		||||
              }
 | 
			
		||||
            }).catch(error => {
 | 
			
		||||
              console.error(`Failed to connect ${message.host}: `, error)
 | 
			
		||||
              console.error(`Failed to connect ${data.host}: `, error)
 | 
			
		||||
            })
 | 
			
		||||
            break;
 | 
			
		||||
          case 'openRemoteFolder':
 | 
			
		||||
            this.remoteContainer.openRemoteFolder(message.host, message.path);
 | 
			
		||||
            this.remoteContainer.openRemoteFolder(data.host, data.path);
 | 
			
		||||
            break;
 | 
			
		||||
          case 'getUserToken':
 | 
			
		||||
            const userToken = this.context.globalState.get('devstarUserToken')
 | 
			
		||||
@@ -54,7 +56,7 @@ export default class DSHome {
 | 
			
		||||
              break;
 | 
			
		||||
            }
 | 
			
		||||
          case 'setUserToken':
 | 
			
		||||
            this.context.globalState.update('devstarUserToken', message.data.userToken)
 | 
			
		||||
            this.context.globalState.update('devstarUserToken', data.userToken)
 | 
			
		||||
            console.log(this.context.globalState.get('devstarUserToken'))
 | 
			
		||||
            console.log(message.data.userToken)
 | 
			
		||||
            if (message.data.userToken === this.context.globalState.get('devstarUserToken')) {
 | 
			
		||||
 
 | 
			
		||||
@@ -214,8 +214,8 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        async function getUserTokenFromVscode() {
 | 
			
		||||
            // const userToken = 'ecd9ceda7904f1f980b90f22be87329910cc6fb1'
 | 
			
		||||
            const data = await biCommunication2Webview('getUserToken', null)
 | 
			
		||||
            await communicateVSCodeByWebview('getUserToken', null)
 | 
			
		||||
            .then(async data => {
 | 
			
		||||
                const userToken = data.userToken
 | 
			
		||||
                if (userToken === 'none') {
 | 
			
		||||
                    // do nothing
 | 
			
		||||
@@ -229,6 +229,11 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
                            console.error('Error in verifying token:', error)
 | 
			
		||||
                        })
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
            })
 | 
			
		||||
            .catch(error => [
 | 
			
		||||
                console.log('Failed to get user token: ', error)
 | 
			
		||||
            ])
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        function verifyToken(token) {
 | 
			
		||||
@@ -306,7 +311,7 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
            .then(data => {
 | 
			
		||||
                // store token in global variable and vscode global state
 | 
			
		||||
                USERTOKEN = data.sha1;
 | 
			
		||||
                biCommunication2Webview('setUserToken', { userToken: USERTOKEN })
 | 
			
		||||
                communicateVSCodeByWebview('setUserToken', { userToken: USERTOKEN })
 | 
			
		||||
                .then(result => {
 | 
			
		||||
                    if (result.ok) {
 | 
			
		||||
                        console.log('User token has been set to vscode global state')
 | 
			
		||||
@@ -340,7 +345,7 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
        function logout() {
 | 
			
		||||
            // remove token from global variable and vscode global state
 | 
			
		||||
            USERTOKEN = null
 | 
			
		||||
            biCommunication2Webview('setUserToken', { userToken: 'none'})
 | 
			
		||||
            communicateVSCodeByWebview('setUserToken', { userToken: 'none'})
 | 
			
		||||
            .then(result => {
 | 
			
		||||
                if (result.ok) {
 | 
			
		||||
                    console.log('User token has been removed from vscode global state')
 | 
			
		||||
@@ -361,7 +366,7 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
            tableBody.innerHTML = '';
 | 
			
		||||
 | 
			
		||||
            // load new data
 | 
			
		||||
            var url = DEVSTAR_HOME + "/api/v1/user/repos?page=1&limit=10"  
 | 
			
		||||
            var url = DEVSTAR_HOME + "/api/v1/user/repos?page=1&limit=20"  
 | 
			
		||||
            var token = USERTOKEN
 | 
			
		||||
            fetch(url, {
 | 
			
		||||
                method: 'GET',
 | 
			
		||||
@@ -536,6 +541,8 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
                console.log("There has a problem when check if the repo has devContainer:", error)
 | 
			
		||||
            })
 | 
			
		||||
 | 
			
		||||
            console.log("opening project")
 | 
			
		||||
 | 
			
		||||
            // open devcontainer through repoId
 | 
			
		||||
            var url = DEVSTAR_HOME + "/api/devcontainer"  
 | 
			
		||||
            var token = USERTOKEN
 | 
			
		||||
@@ -572,8 +579,8 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
                    const devContainerPort = data.data.devContainerPort
 | 
			
		||||
                    const devContainerWorkDir = '/data/workspace'
 | 
			
		||||
 | 
			
		||||
                    // default: open with password
 | 
			
		||||
                    firstOpenRemoteFolder(devContainerHost, devContainerUsername, devContainerPassword, devContainerPort, devContainerWorkDir)
 | 
			
		||||
                    // default: open with key
 | 
			
		||||
                    communicateVSCodeByWebview('firstOpenRemoteFolder', {host: `${devContainerHost}`, username: `${devContainerUsername}`, port: `${devContainerPort}`, path: `${devContainerWorkDir}`})
 | 
			
		||||
                } else {
 | 
			
		||||
                    // TODO: show Error to User
 | 
			
		||||
                    showAlert("打开容器失败!", 1500)
 | 
			
		||||
@@ -670,7 +677,7 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
 | 
			
		||||
        async function getDefaultPublicKeyFromVSCode() {
 | 
			
		||||
            try {
 | 
			
		||||
                const data = await biCommunication2Webview('getDefaultPublicKey', null);
 | 
			
		||||
                const data = await communicateVSCodeByWebview('getDefaultPublicKey', null);
 | 
			
		||||
                const defaultPublicKey = data.defaultPublicKey;
 | 
			
		||||
 | 
			
		||||
                return defaultPublicKey;
 | 
			
		||||
@@ -720,17 +727,18 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
            }, duration); // 消息显示 duration/1000 秒后消失
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        async function biCommunication2Webview(action, data) {
 | 
			
		||||
        async function communicateVSCodeByWebview(action, data) {
 | 
			
		||||
            return new Promise((resolve, reject) => {
 | 
			
		||||
                // request to webview
 | 
			
		||||
                window.parent.postMessage({ action: action, data: data }, '*');
 | 
			
		||||
                window.parent.postMessage({ target: "vscode", action: action, data: data }, '*');
 | 
			
		||||
 | 
			
		||||
                // response from webview
 | 
			
		||||
                function handleResponse(event) {
 | 
			
		||||
                    const jsonData = event.data
 | 
			
		||||
                    if (jsonData.action === action) {
 | 
			
		||||
                        console.log("biCommunication2Webview", jsonData)
 | 
			
		||||
                        // return webview response
 | 
			
		||||
                        console.log("dataFromVSCodeByWebview", jsonData.data)
 | 
			
		||||
 | 
			
		||||
                        window.removeEventListener('message', handleResponse) // 清理监听器
 | 
			
		||||
                        resolve(jsonData.data)
 | 
			
		||||
                    }
 | 
			
		||||
 
 | 
			
		||||
@@ -52,7 +52,7 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        async function biCommunication2Vscode(command, data) {
 | 
			
		||||
        async function communicateVSCode(command, data) {
 | 
			
		||||
            return new Promise((resolve, reject) => {
 | 
			
		||||
                // request to vscode 
 | 
			
		||||
                vscode.postMessage({ command: command, data: data })
 | 
			
		||||
@@ -60,8 +60,9 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
                function handleResponse(event) {
 | 
			
		||||
                    const jsonData = event.data;
 | 
			
		||||
                    if (jsonData.command === command) {
 | 
			
		||||
                        // console.log("communicateVSCode", jsonData.data)
 | 
			
		||||
 | 
			
		||||
                        // return vscode response
 | 
			
		||||
                        console.log("biCommunication2Vscode", jsonData.data)
 | 
			
		||||
                        window.removeEventListener('message', handleResponse) // 清理监听器
 | 
			
		||||
                        resolve(jsonData.data)
 | 
			
		||||
                    }
 | 
			
		||||
@@ -84,40 +85,15 @@ header("Allow: GET, POST, OPTIONS, PUT, DELETE");
 | 
			
		||||
            // }
 | 
			
		||||
            try {
 | 
			
		||||
                const jsonData = event.data;
 | 
			
		||||
                if (jsonData.action === 'firstOpenRemoteFolder') {
 | 
			
		||||
                    console.log('Received message:', jsonData);
 | 
			
		||||
                    firstOpenRemoteFolderWithData(jsonData.host, jsonData.username, jsonData.password, jsonData.port, jsonData.path);
 | 
			
		||||
 | 
			
		||||
                } else if (jsonData.action === 'openRemoteFolder') {
 | 
			
		||||
                    console.log('Received message:', jsonData);
 | 
			
		||||
                    openRemoteFolderWithData(jsonData.host, jsonData.path);
 | 
			
		||||
                if (jsonData.target === 'vscode') {
 | 
			
		||||
                    const actionFromHome = jsonData.action
 | 
			
		||||
                    const dataFromHome = jsonData.data
 | 
			
		||||
                    const dataFromVSCodeResponse = await communicateVSCode(actionFromHome, dataFromHome)
 | 
			
		||||
                    
 | 
			
		||||
                } else if (jsonData.action === 'getUserToken') {
 | 
			
		||||
                    // request user token from vscode global state
 | 
			
		||||
                    const data = await biCommunication2Vscode('getUserToken', {})
 | 
			
		||||
                    var iframe = document.getElementById('embedded-devstar');
 | 
			
		||||
                    if(iframe && iframe.contentWindow) {
 | 
			
		||||
                        iframe.contentWindow.postMessage({ action: 'getUserToken', data: data}, '*');
 | 
			
		||||
                    }
 | 
			
		||||
                } else if (jsonData.action === 'setUserToken') {
 | 
			
		||||
                    // set user token to vscode global state
 | 
			
		||||
                    await biCommunication2Vscode('setUserToken', jsonData.data)
 | 
			
		||||
                    .then((data) => {
 | 
			
		||||
                        var iframe = document.getElementById('embedded-devstar');
 | 
			
		||||
                        if (iframe && iframe.contentWindow) {
 | 
			
		||||
                            iframe.contentWindow.postMessage({ action: 'setUserToken', data: data}, '*');
 | 
			
		||||
                        }
 | 
			
		||||
                    })
 | 
			
		||||
                    .catch((err) => {
 | 
			
		||||
                        if (iframe && iframe.contentWindow) {
 | 
			
		||||
                            iframe.contentWindow.postMessage({ action: 'setUserToken', data: {ok: false}}, '*');
 | 
			
		||||
                        }
 | 
			
		||||
                    });
 | 
			
		||||
                } else if (jsonData.action === 'getDefaultPublicKey') {
 | 
			
		||||
                    const data = await biCommunication2Vscode('getDefaultPublicKey', {})
 | 
			
		||||
                    var iframe = document.getElementById('embedded-devstar')
 | 
			
		||||
                    if (iframe && iframe.contentWindow) {
 | 
			
		||||
                        iframe.contentWindow.postMessage({ action: 'getDefaultPublicKey', data: data}, "*")
 | 
			
		||||
                        iframe.contentWindow.postMessage({action: actionFromHome, data: dataFromVSCodeResponse}, '*')
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            } catch (error) {
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user