Compare commits
10 Commits
41b97301f7
...
adc822729c
| Author | SHA1 | Date | |
|---|---|---|---|
| adc822729c | |||
| 754d66e1d9 | |||
| 6e8b0c0544 | |||
| 24df60ca16 | |||
| ab2c05711b | |||
| 7e33976d51 | |||
| ece4943d2a | |||
| 7367d3cf37 | |||
|
|
781518976e | ||
|
|
c18fc24016 |
BIN
assets/images/logo.png
Normal file
BIN
assets/images/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
@@ -2,7 +2,7 @@
|
|||||||
"name": "devstar",
|
"name": "devstar",
|
||||||
"displayName": "%displayName%",
|
"displayName": "%displayName%",
|
||||||
"description": "%description%",
|
"description": "%description%",
|
||||||
"version": "0.3.8",
|
"version": "0.3.9",
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"publisher": "mengning",
|
"publisher": "mengning",
|
||||||
"engines": {
|
"engines": {
|
||||||
|
|||||||
361
src/home.ts
361
src/home.ts
@@ -1,5 +1,6 @@
|
|||||||
import * as vscode from 'vscode';
|
import * as vscode from 'vscode';
|
||||||
import * as os from 'os';
|
import * as os from 'os';
|
||||||
|
import * as path from 'path';
|
||||||
import RemoteContainer from './remote-container';
|
import RemoteContainer from './remote-container';
|
||||||
import User from './user';
|
import User from './user';
|
||||||
import * as utils from './utils'
|
import * as utils from './utils'
|
||||||
@@ -8,9 +9,7 @@ export default class DSHome {
|
|||||||
private context: vscode.ExtensionContext;
|
private context: vscode.ExtensionContext;
|
||||||
private remoteContainer: RemoteContainer;
|
private remoteContainer: RemoteContainer;
|
||||||
private user: User;
|
private user: User;
|
||||||
private devstarHomePageUrl: string;
|
private devstarDomain: string | undefined;
|
||||||
private devstarDomain: string | undefined
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 配置项提供devstarDomain
|
* 配置项提供devstarDomain
|
||||||
@@ -33,38 +32,34 @@ export default class DSHome {
|
|||||||
this.remoteContainer = new RemoteContainer(user);
|
this.remoteContainer = new RemoteContainer(user);
|
||||||
|
|
||||||
if (devstarDomain != undefined && devstarDomain != "") {
|
if (devstarDomain != undefined && devstarDomain != "") {
|
||||||
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain
|
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
|
||||||
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
|
|
||||||
} else {
|
} else {
|
||||||
const devstarDomainFromConfig = utils.devstarDomain()
|
const devstarDomainFromConfig = utils.devstarDomain();
|
||||||
if (devstarDomainFromConfig != undefined && devstarDomainFromConfig != "") {
|
if (devstarDomainFromConfig != undefined && devstarDomainFromConfig != "") {
|
||||||
this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig
|
this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig;
|
||||||
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
|
|
||||||
} else {
|
} else {
|
||||||
this.devstarDomain = "https://devstar.cn"
|
this.devstarDomain = "https://devstar.cn";
|
||||||
this.devstarHomePageUrl = "https://devstar.cn/devstar-home"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setUser(user: User) {
|
setUser(user: User) {
|
||||||
this.user = user
|
this.user = user;
|
||||||
}
|
}
|
||||||
|
|
||||||
setRemoteContainer(remoteContainer: RemoteContainer) {
|
setRemoteContainer(remoteContainer: RemoteContainer) {
|
||||||
this.remoteContainer = remoteContainer
|
this.remoteContainer = remoteContainer;
|
||||||
}
|
}
|
||||||
|
|
||||||
setDevstarDomainAndHomePageURL(devstarDomain: string) {
|
setDevstarDomainAndHomePageURL(devstarDomain: string) {
|
||||||
if (devstarDomain != undefined && devstarDomain != "") {
|
if (devstarDomain != undefined && devstarDomain != "") {
|
||||||
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain
|
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
|
||||||
this.devstarHomePageUrl = devstarDomain.endsWith('/') ? this.devstarDomain + "devstar-home" : devstarDomain + "/devstar-home"
|
|
||||||
} else {
|
} else {
|
||||||
console.error("devstarDomain is undefined or null")
|
console.error("devstarDomain is undefined or null");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async toggle(devstarHomePageUrl: string = this.devstarHomePageUrl) {
|
async toggle() {
|
||||||
const panel = vscode.window.createWebviewPanel(
|
const panel = vscode.window.createWebviewPanel(
|
||||||
'homeWebview',
|
'homeWebview',
|
||||||
vscode.l10n.t('Home'),
|
vscode.l10n.t('Home'),
|
||||||
@@ -72,15 +67,18 @@ export default class DSHome {
|
|||||||
{
|
{
|
||||||
enableScripts: true,
|
enableScripts: true,
|
||||||
retainContextWhenHidden: true,
|
retainContextWhenHidden: true,
|
||||||
|
localResourceRoots: [
|
||||||
|
vscode.Uri.file(path.join(this.context.extensionPath, 'assets'))
|
||||||
|
]
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
panel.webview.html = await this.getWebviewContent(devstarHomePageUrl);
|
panel.webview.html = await this.getWebviewContent(panel);
|
||||||
|
|
||||||
panel.webview.onDidReceiveMessage(
|
panel.webview.onDidReceiveMessage(
|
||||||
async (message) => {
|
async (message) => {
|
||||||
const data = message.data
|
const data = message.data;
|
||||||
const need_return = message.need_return
|
const need_return = message.need_return;
|
||||||
if (need_return) {
|
if (need_return) {
|
||||||
// ================= need return ====================
|
// ================= need return ====================
|
||||||
switch (message.command) {
|
switch (message.command) {
|
||||||
@@ -88,78 +86,71 @@ export default class DSHome {
|
|||||||
case 'getHomeConfig':
|
case 'getHomeConfig':
|
||||||
const config = {
|
const config = {
|
||||||
language: vscode.env.language
|
language: vscode.env.language
|
||||||
}
|
};
|
||||||
panel.webview.postMessage({ command: 'getHomeConfig', data: { homeConfig: config } })
|
panel.webview.postMessage({ command: 'getHomeConfig', data: { homeConfig: config } });
|
||||||
break;
|
break;
|
||||||
case 'getUserToken':
|
case 'getUserToken':
|
||||||
const userToken = this.user.getUserTokenFromLocal()
|
const userToken = this.user.getUserTokenFromLocal();
|
||||||
if (userToken === undefined) {
|
if (userToken === undefined) {
|
||||||
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } })
|
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } });
|
||||||
break;
|
|
||||||
} else {
|
} else {
|
||||||
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } })
|
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } });
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'getUsername':
|
case 'getUsername':
|
||||||
const username = this.user.getUsernameFromLocal()
|
const username = this.user.getUsernameFromLocal();
|
||||||
if (username === undefined) {
|
if (username === undefined) {
|
||||||
panel.webview.postMessage({ command: 'getUsername', data: { username: '' } })
|
panel.webview.postMessage({ command: 'getUsername', data: { username: '' } });
|
||||||
break;
|
|
||||||
} else {
|
} else {
|
||||||
panel.webview.postMessage({ command: 'getUsername', data: { username: username } })
|
panel.webview.postMessage({ command: 'getUsername', data: { username: username } });
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'firstOpenRemoteFolder':
|
case 'firstOpenRemoteFolder':
|
||||||
// data.host - project name
|
// data.host - project name
|
||||||
await this.remoteContainer.firstOpenProject(data.host, data.hostname, data.port, data.username, data.path, this.context)
|
await this.remoteContainer.firstOpenProject(data.host, data.hostname, data.port, data.username, data.path, this.context);
|
||||||
break;
|
break;
|
||||||
case 'openRemoteFolder':
|
case 'openRemoteFolder':
|
||||||
this.remoteContainer.openRemoteFolder(data.host, data.port, data.username, data.path);
|
this.remoteContainer.openRemoteFolder(data.host, data.port, data.username, data.path);
|
||||||
break;
|
break;
|
||||||
case 'getDevstarDomain':
|
case 'getDevstarDomain':
|
||||||
panel.webview.postMessage({ command: 'getDevstarDomain', data: { devstarDomain: this.devstarDomain } })
|
panel.webview.postMessage({ command: 'getDevstarDomain', data: { devstarDomain: this.devstarDomain } });
|
||||||
break;
|
break;
|
||||||
// ----------------- not frequent -----------------------
|
// ----------------- not frequent -----------------------
|
||||||
case 'setUserToken':
|
case 'setUserToken':
|
||||||
this.user.setUserTokenToLocal(data.userToken)
|
this.user.setUserTokenToLocal(data.userToken);
|
||||||
if (data.userToken === this.user.getUserTokenFromLocal()) {
|
if (data.userToken === this.user.getUserTokenFromLocal()) {
|
||||||
panel.webview.postMessage({ command: 'setUserToken', data: { ok: true } })
|
panel.webview.postMessage({ command: 'setUserToken', data: { ok: true } });
|
||||||
break;
|
|
||||||
} else {
|
} else {
|
||||||
panel.webview.postMessage({ command: 'setUserToken', data: { ok: false } })
|
panel.webview.postMessage({ command: 'setUserToken', data: { ok: false } });
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'setUsername':
|
case 'setUsername':
|
||||||
this.user.setUsernameToLocal(data.username);
|
this.user.setUsernameToLocal(data.username);
|
||||||
if (data.username === this.user.getUsernameFromLocal()) {
|
if (data.username === this.user.getUsernameFromLocal()) {
|
||||||
panel.webview.postMessage({ command: 'setUsername', data: { ok: true } });
|
panel.webview.postMessage({ command: 'setUsername', data: { ok: true } });
|
||||||
break;
|
|
||||||
} else {
|
} else {
|
||||||
panel.webview.postMessage({ command: 'setUsername', data: { ok: false } });
|
panel.webview.postMessage({ command: 'setUsername', data: { ok: false } });
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'getUserPublicKey':
|
case 'getUserPublicKey':
|
||||||
var userPublicKey = '';
|
let userPublicKey = '';
|
||||||
if (this.user.existUserPrivateKey()) {
|
if (this.user.existUserPrivateKey()) {
|
||||||
userPublicKey = this.user.getUserPublicKey();
|
userPublicKey = this.user.getUserPublicKey();
|
||||||
panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } });
|
||||||
|
break;
|
||||||
case 'createUserPublicKey':
|
case 'createUserPublicKey':
|
||||||
await this.user.createUserSSHKey();
|
await this.user.createUserSSHKey();
|
||||||
if (this.user.existUserPublicKey()) {
|
if (this.user.existUserPublicKey()) {
|
||||||
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: true } })
|
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: true } });
|
||||||
break;
|
|
||||||
} else {
|
} else {
|
||||||
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: false } })
|
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: false } });
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'getMachineName':
|
case 'getMachineName':
|
||||||
const machineName = os.hostname();
|
const machineName = os.hostname();
|
||||||
panel.webview.postMessage({ command: 'getMachineName', data: { machineName: machineName } })
|
panel.webview.postMessage({ command: 'getMachineName', data: { machineName: machineName } });
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// ================= don't need return ==============
|
// ================= don't need return ==============
|
||||||
@@ -170,10 +161,26 @@ export default class DSHome {
|
|||||||
vscode.window.showInformationMessage(data.message);
|
vscode.window.showInformationMessage(data.message);
|
||||||
break;
|
break;
|
||||||
case 'showWarningNotification':
|
case 'showWarningNotification':
|
||||||
vscode.window.showWarningMessage(data.message)
|
vscode.window.showWarningMessage(data.message);
|
||||||
break;
|
break;
|
||||||
case 'showErrorNotification':
|
case 'showErrorNotification':
|
||||||
await utils.showErrorNotification(data.message)
|
await utils.showErrorNotification(data.message);
|
||||||
|
break;
|
||||||
|
case 'openExternalUrl':
|
||||||
|
// 修复:直接从 message 中获取 url,而不是从 data
|
||||||
|
const url = message.url || (data && data.url);
|
||||||
|
if (url) {
|
||||||
|
try {
|
||||||
|
await vscode.env.openExternal(vscode.Uri.parse(url));
|
||||||
|
vscode.window.showInformationMessage(`已在浏览器中打开: ${url}`);
|
||||||
|
} catch (error) {
|
||||||
|
vscode.window.showErrorMessage(`打开链接失败: ${url}`);
|
||||||
|
console.error('打开外部链接失败:', error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('openExternalUrl: url is undefined', message);
|
||||||
|
vscode.window.showErrorMessage('打开链接失败: 链接地址无效');
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,105 +189,233 @@ export default class DSHome {
|
|||||||
this.context.subscriptions
|
this.context.subscriptions
|
||||||
);
|
);
|
||||||
|
|
||||||
this.context.subscriptions.push(panel)
|
this.context.subscriptions.push(panel);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getWebviewContent(panel?: vscode.WebviewPanel): Promise<string> {
|
||||||
|
// 获取图片的 Webview URI
|
||||||
|
let logoUri = '';
|
||||||
|
if (panel) {
|
||||||
|
const logoPath = vscode.Uri.file(
|
||||||
|
path.join(this.context.extensionPath, 'assets', 'images', 'logo.png')
|
||||||
|
);
|
||||||
|
logoUri = panel.webview.asWebviewUri(logoPath).toString();
|
||||||
|
}
|
||||||
|
|
||||||
async getWebviewContent(devstarHomePageUrl: string): Promise<string> {
|
|
||||||
return `
|
return `
|
||||||
<?php
|
|
||||||
header("Access-Control-Allow-Origin: *");
|
|
||||||
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
|
|
||||||
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
|
|
||||||
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
|
|
||||||
?>
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>DevStar Home</title>
|
<title>DevStar Home</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 20px;
|
||||||
|
font-family: var(--vscode-font-family);
|
||||||
|
background-color: var(--vscode-editor-background);
|
||||||
|
color: var(--vscode-editor-foreground);
|
||||||
|
}
|
||||||
|
.header {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
}
|
||||||
|
.logo {
|
||||||
|
width: auto;
|
||||||
|
height: 30px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.feature-list {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.feature-item {
|
||||||
|
padding: 10px;
|
||||||
|
margin: 10px 0;
|
||||||
|
background-color: var(--vscode-button-background);
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.feature-item:hover {
|
||||||
|
background-color: var(--vscode-button-hoverBackground);
|
||||||
|
}
|
||||||
|
.login-status {
|
||||||
|
padding: 10px;
|
||||||
|
margin: 10px 0;
|
||||||
|
border-radius: 4px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.logged-in {
|
||||||
|
background-color: var(--vscode-inputValidation-infoBackground);
|
||||||
|
border: 1px solid var(--vscode-inputValidation-infoBorder);
|
||||||
|
}
|
||||||
|
.logged-out {
|
||||||
|
background-color: var(--vscode-inputValidation-warningBackground);
|
||||||
|
border: 1px solid var(--vscode-inputValidation-warningBorder);
|
||||||
|
}
|
||||||
|
.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<iframe id="embedded-devstar" src="${devstarHomePageUrl}" sandbox="allow-popups allow-same-origin allow-scripts allow-forms allow-top-navigation-by-user-activation" width="100%" height="100%" frameborder="0"
|
<div class="header">
|
||||||
style="border: 0; left: 0; right: 0; bottom: 0; top: 0; position:absolute;">
|
${logoUri ? `<img src="${logoUri}" alt="DevStar Logo" class="logo">` : '🚀'}
|
||||||
</iframe>
|
<p>欢迎使用 DevStar 扩展</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 登录状态显示 -->
|
||||||
|
<div id="loginStatus" class="login-status hidden">
|
||||||
|
<span id="statusText"></span>
|
||||||
|
<span id="usernameDisplay"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul class="feature-list">
|
||||||
|
<li class="feature-item" onclick="handleMainAction()" id="mainActionButton">
|
||||||
|
主要功能
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const vscode = acquireVsCodeApi();
|
const vscode = acquireVsCodeApi();
|
||||||
|
let isLoggedIn = false;
|
||||||
|
let username = '';
|
||||||
|
|
||||||
function firstOpenRemoteFolder() {
|
function vscodePostMessage(command, data) {
|
||||||
vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
|
vscode.postMessage({
|
||||||
|
command: command,
|
||||||
|
need_return: false,
|
||||||
|
data: data
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function openRemoteFolder() {
|
|
||||||
vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstOpenRemoteFolderWithData(host, username, password, port, path) {
|
|
||||||
vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
|
|
||||||
}
|
|
||||||
|
|
||||||
function openRemoteFolderWithData(host, path) {
|
|
||||||
vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async function communicateVSCode(command, data) {
|
async function communicateVSCode(command, data) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// request to vscode
|
vscode.postMessage({ command: command, need_return: true, data: data });
|
||||||
vscode.postMessage({ command: command, need_return: true, data: data })
|
|
||||||
|
|
||||||
function handleResponse(event) {
|
function handleResponse(event) {
|
||||||
const jsonData = event.data;
|
const jsonData = event.data;
|
||||||
if (jsonData.command === command) {
|
if (jsonData.command === command) {
|
||||||
// console.log("communicateVSCode", jsonData.data)
|
window.removeEventListener('message', handleResponse);
|
||||||
|
resolve(jsonData.data);
|
||||||
// return vscode response
|
|
||||||
window.removeEventListener('message', handleResponse) // 清理监听器
|
|
||||||
resolve(jsonData.data)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('message', handleResponse)
|
window.addEventListener('message', handleResponse);
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.removeEventListener('message', handleResponse)
|
window.removeEventListener('message', handleResponse);
|
||||||
reject('timeout')
|
reject('timeout');
|
||||||
}, 5000); // 5秒超时
|
}, 5000);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 监听子页面的消息
|
// 检查登录状态
|
||||||
window.addEventListener('message', async (event) => {
|
async function checkLoginStatus() {
|
||||||
// 出于安全考虑,检查 event.origin 是否是你预期的源
|
|
||||||
// if (event.origin !== "http://expected-origin.com") {
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
try {
|
try {
|
||||||
const jsonData = event.data;
|
const userTokenResult = await communicateVSCode('getUserToken', {});
|
||||||
|
const usernameResult = await communicateVSCode('getUsername', {});
|
||||||
|
|
||||||
if (jsonData.target === 'vscode') {
|
const userToken = userTokenResult.userToken;
|
||||||
const actionFromHome = jsonData.action
|
username = usernameResult.username;
|
||||||
const dataFromHome = jsonData.data
|
|
||||||
const dataFromVSCodeResponse = await communicateVSCode(actionFromHome, dataFromHome)
|
|
||||||
|
|
||||||
var iframe = document.getElementById('embedded-devstar');
|
isLoggedIn = !!(userToken && userToken.trim() !== '' && username && username.trim() !== '');
|
||||||
if (iframe && iframe.contentWindow) {
|
|
||||||
iframe.contentWindow.postMessage({ action: actionFromHome, data: dataFromVSCodeResponse }, '*')
|
updateUI();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('检查登录状态失败:', error);
|
||||||
|
isLoggedIn = false;
|
||||||
|
updateUI();
|
||||||
}
|
}
|
||||||
} else if (jsonData.target === 'vscode_no_return') {
|
}
|
||||||
vscode.postMessage({ command: jsonData.action, need_return: false, data: jsonData.data })
|
|
||||||
|
// 更新UI显示
|
||||||
|
function updateUI() {
|
||||||
|
const loginStatus = document.getElementById('loginStatus');
|
||||||
|
const statusText = document.getElementById('statusText');
|
||||||
|
const usernameDisplay = document.getElementById('usernameDisplay');
|
||||||
|
const mainActionButton = document.getElementById('mainActionButton');
|
||||||
|
|
||||||
|
loginStatus.classList.remove('hidden');
|
||||||
|
|
||||||
|
if (isLoggedIn) {
|
||||||
|
loginStatus.classList.remove('logged-out');
|
||||||
|
loginStatus.classList.add('logged-in');
|
||||||
|
statusText.textContent = '已登录';
|
||||||
|
usernameDisplay.textContent = username ? ' - 用户: ' + username : '';
|
||||||
|
mainActionButton.textContent = '跳转到个人主页';
|
||||||
|
} else {
|
||||||
|
loginStatus.classList.remove('logged-in');
|
||||||
|
loginStatus.classList.add('logged-out');
|
||||||
|
statusText.textContent = '未登录';
|
||||||
|
usernameDisplay.textContent = '';
|
||||||
|
mainActionButton.textContent = '跳转到 DevStar 官网';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理主要功能点击 - 修复消息发送格式
|
||||||
|
function handleMainAction() {
|
||||||
|
if (isLoggedIn) {
|
||||||
|
// 已登录:跳转到 hostname/username
|
||||||
|
// 使用 async 函数处理异步操作
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
// 获取必要的用户信息
|
||||||
|
const devstarDomainResult = await communicateVSCode('getDevstarDomain', {});
|
||||||
|
const usernameResult = await communicateVSCode('getUsername', {});
|
||||||
|
|
||||||
|
const devstarDomain = devstarDomainResult.devstarDomain;
|
||||||
|
const username = usernameResult.username;
|
||||||
|
|
||||||
|
if (devstarDomain && username) {
|
||||||
|
const targetUrl = \`\${devstarDomain}/\${username}\`;
|
||||||
|
|
||||||
|
vscodePostMessage('showInformationNotification', {
|
||||||
|
message: \`跳转到 \${targetUrl}\`
|
||||||
|
});
|
||||||
|
|
||||||
|
vscode.postMessage({
|
||||||
|
command: 'openExternalUrl',
|
||||||
|
need_return: false,
|
||||||
|
url: targetUrl
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
vscodePostMessage('showErrorNotification', {
|
||||||
|
message: '无法获取域名或用户名信息'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error parsing message:', error);
|
console.error('跳转失败:', error);
|
||||||
}
|
vscodePostMessage('showErrorNotification', {
|
||||||
|
message: '跳转失败,请重试'
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
} else {
|
||||||
|
// 未登录:跳转到 DevStar 官网
|
||||||
|
vscodePostMessage('showInformationNotification', {message: '跳转到 DevStar 官网'});
|
||||||
|
vscode.postMessage({
|
||||||
|
command: 'openExternalUrl',
|
||||||
|
need_return: false,
|
||||||
|
url: 'https://devstar.cn'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载时检查登录状态
|
||||||
|
window.addEventListener('load', async () => {
|
||||||
|
await checkLoginStatus();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 可选:添加重新检查登录状态的功能
|
||||||
|
function refreshLoginStatus() {
|
||||||
|
checkLoginStatus();
|
||||||
|
vscodePostMessage('showInformationNotification', {message: '登录状态已刷新'});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
</html>`;
|
||||||
</html>`
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
28
src/main.ts
28
src/main.ts
@@ -28,9 +28,17 @@ export class DevStarExtension {
|
|||||||
|
|
||||||
// 如果global state中devstarDomain的值不为空,则在global state中存储一个键值对为devstarDomain_<sessionId>和devstar domain,并把devstarDomain的值置空.
|
// 如果global state中devstarDomain的值不为空,则在global state中存储一个键值对为devstarDomain_<sessionId>和devstar domain,并把devstarDomain的值置空.
|
||||||
// 这时如果remote窗口需要打开项目,且global state中的devstarDomain_<sessionId>键存在、值不为空,
|
// 这时如果remote窗口需要打开项目,且global state中的devstarDomain_<sessionId>键存在、值不为空,
|
||||||
// 则取出并清掉devstarDomain_<sessionId>键值对,并通过参数将devstar domain传递给/openProjectSkippingLoginCheck,由其将devstar domain继续存储在devstarDomain中
|
// 则取出其值,并通过参数将devstar domain传递给/openProjectSkippingLoginCheck
|
||||||
|
//
|
||||||
|
// 如果global state中devstarDomain_<sessionId>存在,直接使用
|
||||||
|
|
||||||
|
const devstarDomain_sessionId: string | undefined = context.globalState.get('devstarDomain_' + vscode.env.sessionId)
|
||||||
const devstarDomain: string | undefined = context.globalState.get('devstarDomain')
|
const devstarDomain: string | undefined = context.globalState.get('devstarDomain')
|
||||||
if (devstarDomain != undefined && devstarDomain != "") {
|
if (devstarDomain_sessionId != undefined && devstarDomain_sessionId != "") {
|
||||||
|
this.user = new User(context, devstarDomain_sessionId)
|
||||||
|
this.remoteContainer = new RemoteContainer(this.user);
|
||||||
|
this.dsHome = new DSHome(context, this.user, devstarDomain_sessionId)
|
||||||
|
} else if (devstarDomain != undefined && devstarDomain != "") {
|
||||||
console.log('domain in global state', devstarDomain)
|
console.log('domain in global state', devstarDomain)
|
||||||
// global state中存在devstarDomain
|
// global state中存在devstarDomain
|
||||||
this.user = new User(context, devstarDomain)
|
this.user = new User(context, devstarDomain)
|
||||||
@@ -72,10 +80,9 @@ export class DevStarExtension {
|
|||||||
// 修改user、remote-container、home中的devstar domain和hostname
|
// 修改user、remote-container、home中的devstar domain和hostname
|
||||||
this.user.setDevstarDomain(devstarDomain)
|
this.user.setDevstarDomain(devstarDomain)
|
||||||
this.remoteContainer.setUser(this.user)
|
this.remoteContainer.setUser(this.user)
|
||||||
this.dsHome.setDevstarDomain(devstarDomain)
|
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
|
||||||
this.dsHome.setUser(this.user)
|
this.dsHome.setUser(this.user)
|
||||||
this.dsHome.setRemoteContainer(this.remoteContainer)
|
this.dsHome.setRemoteContainer(this.remoteContainer)
|
||||||
vscode.commands.executeCommand('devstar.showHome');
|
|
||||||
|
|
||||||
// 将devstar domain存在global state中
|
// 将devstar domain存在global state中
|
||||||
context.globalState.update('devstarDomain', devstarDomain)
|
context.globalState.update('devstarDomain', devstarDomain)
|
||||||
@@ -136,7 +143,6 @@ export class DevStarExtension {
|
|||||||
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
|
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
|
||||||
this.dsHome.setUser(this.user)
|
this.dsHome.setUser(this.user)
|
||||||
this.dsHome.setRemoteContainer(this.remoteContainer)
|
this.dsHome.setRemoteContainer(this.remoteContainer)
|
||||||
vscode.commands.executeCommand('devstar.showHome');
|
|
||||||
|
|
||||||
// 将devstar domain存在global state中
|
// 将devstar domain存在global state中
|
||||||
context.globalState.update('devstarDomain', devstarDomain)
|
context.globalState.update('devstarDomain', devstarDomain)
|
||||||
@@ -162,19 +168,15 @@ export class DevStarExtension {
|
|||||||
|
|
||||||
this.registerGlobalCommands(context);
|
this.registerGlobalCommands(context);
|
||||||
|
|
||||||
this.startDevStarHome();
|
//防止进入HOME页面
|
||||||
}
|
// this.startDevStarHome();
|
||||||
|
|
||||||
|
|
||||||
async startDevStarHome() {
|
|
||||||
vscode.commands.executeCommand('devstar.showHome');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
registerGlobalCommands(context: vscode.ExtensionContext) {
|
registerGlobalCommands(context: vscode.ExtensionContext) {
|
||||||
context.subscriptions.push(
|
context.subscriptions.push(
|
||||||
vscode.commands.registerCommand('devstar.showHome', (url: string) =>
|
vscode.commands.registerCommand('devstar.showHome', () =>
|
||||||
this.dsHome.toggle(url)
|
this.dsHome.toggle()
|
||||||
),
|
),
|
||||||
vscode.commands.registerCommand('devstar.clean', () => {
|
vscode.commands.registerCommand('devstar.clean', () => {
|
||||||
// 先清除ssh key
|
// 先清除ssh key
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// remote-container.ts
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import * as os from 'os';
|
import * as os from 'os';
|
||||||
@@ -32,10 +33,16 @@ export default class RemoteContainer {
|
|||||||
* @param context 用于支持远程项目环境
|
* @param context 用于支持远程项目环境
|
||||||
*/
|
*/
|
||||||
async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
|
async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
|
||||||
|
console.log(`[RemoteContainer] firstOpenProject called with:`, { host, hostname, port, username, path });
|
||||||
|
|
||||||
if (vscode.env.remoteName) {
|
if (vscode.env.remoteName) {
|
||||||
// 远程环境
|
// 远程环境
|
||||||
vscode.commands.executeCommand('workbench.action.terminal.newLocal').then(() => {
|
console.log(`[RemoteContainer] Running in remote environment: ${vscode.env.remoteName}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await vscode.commands.executeCommand('workbench.action.terminal.newLocal');
|
||||||
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
|
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
|
||||||
|
|
||||||
if (terminal) {
|
if (terminal) {
|
||||||
let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId)
|
let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId)
|
||||||
if (devstarDomain == undefined || devstarDomain == "")
|
if (devstarDomain == undefined || devstarDomain == "")
|
||||||
@@ -47,39 +54,66 @@ export default class RemoteContainer {
|
|||||||
const powershellVersion = context.globalState.get('powershellVersion')
|
const powershellVersion = context.globalState.get('powershellVersion')
|
||||||
const powershell_semver_compatible_version = semver.coerce(powershellVersion)
|
const powershell_semver_compatible_version = semver.coerce(powershellVersion)
|
||||||
|
|
||||||
|
let command = '';
|
||||||
if (devstarDomain === undefined) {
|
if (devstarDomain === undefined) {
|
||||||
// 不传递devstarDomain
|
// 不传递devstarDomain
|
||||||
if (powershellVersion === undefined)
|
if (powershellVersion === undefined) {
|
||||||
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`)
|
command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
|
||||||
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
|
} else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
|
||||||
// win & powershell >= 5.1.26100.0
|
// win & powershell >= 5.1.26100.0
|
||||||
terminal.sendText(`code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`)
|
command = `code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
|
||||||
} else {
|
} else {
|
||||||
// win & powershell < 5.1.26100.0
|
// win & powershell < 5.1.26100.0
|
||||||
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`)
|
command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (powershellVersion === undefined)
|
if (powershellVersion === undefined) {
|
||||||
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`)
|
command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
|
||||||
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
|
} else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
|
||||||
// win & powershell >= 5.1.26100.0
|
// win & powershell >= 5.1.26100.0
|
||||||
terminal.sendText(`code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`)
|
command = `code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
|
||||||
} else {
|
} else {
|
||||||
// win & powershell < 5.1.26100.0
|
// win & powershell < 5.1.26100.0
|
||||||
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`)
|
command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
})
|
console.log(`[RemoteContainer] Sending command to terminal: ${command}`);
|
||||||
|
terminal.sendText(command);
|
||||||
} else {
|
} else {
|
||||||
|
console.error(`[RemoteContainer] Failed to create or access terminal`);
|
||||||
|
vscode.window.showErrorMessage('无法创建终端,请检查终端是否可用。');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error(`[RemoteContainer] Error in remote environment:`, error);
|
||||||
|
vscode.window.showErrorMessage(`远程环境操作失败: ${errorMessage}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[RemoteContainer] Running in local environment, attempting firstConnect`);
|
||||||
|
try {
|
||||||
|
//传入真实IP
|
||||||
await this.firstConnect(host, hostname, username, port)
|
await this.firstConnect(host, hostname, username, port)
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (res === 'success') {
|
if (res === 'success') {
|
||||||
|
console.log(`[RemoteContainer] firstConnect succeeded, opening remote folder`);
|
||||||
// only success then open folder
|
// only success then open folder
|
||||||
this.openRemoteFolder(host, port, username, path);
|
this.openRemoteFolder(host, port, username, path);
|
||||||
|
} else {
|
||||||
|
console.error(`[RemoteContainer] firstConnect returned: ${res}`);
|
||||||
|
vscode.window.showErrorMessage('首次连接容器失败,请检查网络和容器状态。');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
.catch(error => {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error(`[RemoteContainer] firstConnect failed:`, error);
|
||||||
|
vscode.window.showErrorMessage(`首次连接容器时发生错误: ${errorMessage}`);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error(`[RemoteContainer] Error in local environment firstOpenProject:`, error);
|
||||||
|
vscode.window.showErrorMessage(`打开项目失败: ${errorMessage}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,48 +127,82 @@ export default class RemoteContainer {
|
|||||||
*/
|
*/
|
||||||
// connect with key
|
// connect with key
|
||||||
async firstConnect(host: string, hostname: string, username: string, port: number): Promise<string> {
|
async firstConnect(host: string, hostname: string, username: string, port: number): Promise<string> {
|
||||||
return new Promise(async (resolve) => {
|
console.log(`[RemoteContainer] firstConnect called with:`, { host, hostname, username, port });
|
||||||
|
|
||||||
|
return new Promise(async (resolve, reject) => {
|
||||||
const ssh = new NodeSSH();
|
const ssh = new NodeSSH();
|
||||||
|
|
||||||
vscode.window.withProgress({
|
vscode.window.withProgress({
|
||||||
location: vscode.ProgressLocation.Notification,
|
location: vscode.ProgressLocation.Notification,
|
||||||
title: vscode.l10n.t("Installing vscode-server and devstar extension in container"),
|
title: vscode.l10n.t("Installing vscode-server and devstar extension in container"),
|
||||||
cancellable: false
|
cancellable: false
|
||||||
}, async (progress) => {
|
}, async (progress) => {
|
||||||
try {
|
try {
|
||||||
|
console.log(`[RemoteContainer] Checking SSH keys existence`);
|
||||||
|
|
||||||
// 检查公私钥是否存在,如果不存在,需要创建
|
// 检查公私钥是否存在,如果不存在,需要创建
|
||||||
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
|
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
|
||||||
|
console.log(`[RemoteContainer] SSH keys not found, creating new keys`);
|
||||||
await this.user.createUserSSHKey()
|
await this.user.createUserSSHKey()
|
||||||
|
|
||||||
// 上传公钥
|
// 上传公钥
|
||||||
|
console.log(`[RemoteContainer] Uploading public key`);
|
||||||
const devstarAPIHandler = new DevstarAPIHandler()
|
const devstarAPIHandler = new DevstarAPIHandler()
|
||||||
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user)
|
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user)
|
||||||
if (uploadResult !== "ok") {
|
if (uploadResult !== "ok") {
|
||||||
throw new Error('Upload public key failed.')
|
throw new Error('Upload public key failed.')
|
||||||
}
|
}
|
||||||
|
console.log(`[RemoteContainer] Public key uploaded successfully`);
|
||||||
|
} else {
|
||||||
|
console.log(`[RemoteContainer] SSH keys already exist`);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to first connect container: ", error)
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error("[RemoteContainer] Failed to first connect container - SSH key setup: ", error)
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 本地环境
|
// 本地环境
|
||||||
try {
|
try {
|
||||||
|
console.log(`[RemoteContainer] Attempting SSH connection to ${hostname}:${port} as ${username}`);
|
||||||
|
|
||||||
// connect with key
|
// connect with key
|
||||||
await ssh.connect({
|
await ssh.connect({
|
||||||
host: hostname,
|
host: hostname,
|
||||||
username: username,
|
username: 'root',
|
||||||
port: port,
|
port: port,
|
||||||
privateKeyPath: this.user.getUserPrivateKeyPath()
|
privateKeyPath: this.user.getUserPrivateKeyPath(),
|
||||||
|
readyTimeout: 30000, // 增加超时时间到30秒
|
||||||
|
onKeyboardInteractive: (
|
||||||
|
_name: string,
|
||||||
|
_instructions: string,
|
||||||
|
_instructionsLang: string,
|
||||||
|
_prompts: any[],
|
||||||
|
finish: (responses: string[]) => void
|
||||||
|
) => {
|
||||||
|
console.log(`[RemoteContainer] Keyboard interactive authentication required`);
|
||||||
|
finish([]);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log(`[RemoteContainer] SSH connection established successfully`);
|
||||||
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
|
progress.report({ message: vscode.l10n.t("Connected! Start installation") });
|
||||||
|
|
||||||
// install vscode-server and devstar extension
|
// install vscode-server and devstar extension
|
||||||
|
console.log(`[RemoteContainer] Getting VSCode commit ID`);
|
||||||
const vscodeCommitId = await utils.getVsCodeCommitId()
|
const vscodeCommitId = await utils.getVsCodeCommitId()
|
||||||
|
|
||||||
if ("" != vscodeCommitId) {
|
if ("" != vscodeCommitId) {
|
||||||
|
console.log(`[RemoteContainer] VSCode commit ID: ${vscodeCommitId}`);
|
||||||
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`
|
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`
|
||||||
const installVscodeServerScript = `
|
const installVscodeServerScript = `
|
||||||
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
|
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
|
||||||
if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then
|
if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then
|
||||||
|
echo "VSCode server already exists, installing extension only"
|
||||||
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
|
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
|
||||||
else
|
else
|
||||||
|
echo "Downloading and installing VSCode server"
|
||||||
wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\
|
wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\
|
||||||
mv vscode-server-linux-x64.tar.gz ~/.vscode-server/bin/${vscodeCommitId} && \\
|
mv vscode-server-linux-x64.tar.gz ~/.vscode-server/bin/${vscodeCommitId} && \\
|
||||||
cd ~/.vscode-server/bin/${vscodeCommitId} && \\
|
cd ~/.vscode-server/bin/${vscodeCommitId} && \\
|
||||||
@@ -143,20 +211,45 @@ export default class RemoteContainer {
|
|||||||
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
|
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
|
||||||
fi
|
fi
|
||||||
`;
|
`;
|
||||||
await ssh.execCommand(installVscodeServerScript);
|
|
||||||
console.log("vscode-server and extension installed");
|
console.log(`[RemoteContainer] Executing installation script`);
|
||||||
|
const installResult = await ssh.execCommand(installVscodeServerScript);
|
||||||
|
|
||||||
|
if (installResult.code === 0) {
|
||||||
|
console.log("[RemoteContainer] VSCode server and extension installed successfully");
|
||||||
|
console.log("[RemoteContainer] Installation stdout:", installResult.stdout);
|
||||||
|
if (installResult.stderr) {
|
||||||
|
console.warn("[RemoteContainer] Installation stderr:", installResult.stderr);
|
||||||
|
}
|
||||||
|
|
||||||
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
|
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
|
||||||
|
} else {
|
||||||
|
console.error("[RemoteContainer] Installation failed with code:", installResult.code);
|
||||||
|
console.error("[RemoteContainer] Installation stderr:", installResult.stderr);
|
||||||
|
throw new Error(`Installation failed with exit code ${installResult.code}: ${installResult.stderr}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error('Failed to get VSCode commit ID');
|
||||||
}
|
}
|
||||||
|
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
|
console.log(`[RemoteContainer] SSH connection disposed`);
|
||||||
|
|
||||||
// only connect successfully then save the host info
|
// only connect successfully then save the host info
|
||||||
await this.storeProjectSSHInfo(host, hostname, port, username)
|
console.log(`[RemoteContainer] Storing project SSH info`);
|
||||||
|
await this.storeProjectSSHInfo(host, hostname, port, 'root')
|
||||||
|
|
||||||
resolve('success')
|
resolve('success')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to install vscode-server and extension: ', error);
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error('[RemoteContainer] Failed to install vscode-server and extension: ', error);
|
||||||
|
try {
|
||||||
await ssh.dispose();
|
await ssh.dispose();
|
||||||
|
} catch (disposeError) {
|
||||||
|
const disposeErrorMessage = disposeError instanceof Error ? disposeError.message : '未知错误';
|
||||||
|
console.error('[RemoteContainer] Error disposing SSH connection: ', disposeError);
|
||||||
|
}
|
||||||
|
reject(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -170,31 +263,48 @@ export default class RemoteContainer {
|
|||||||
* @param username
|
* @param username
|
||||||
*/
|
*/
|
||||||
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
|
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
|
||||||
|
console.log(`[RemoteContainer] storeProjectSSHInfo called with:`, { host, hostname, port, username });
|
||||||
|
|
||||||
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
|
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
|
||||||
|
console.log(`[RemoteContainer] SSH config path: ${sshConfigPath}`);
|
||||||
|
|
||||||
// check if the host and related info exist in local ssh config file before saving
|
// check if the host and related info exist in local ssh config file before saving
|
||||||
var canAppendSSHConfig = true
|
let canAppendSSHConfig = true;
|
||||||
if (fs.existsSync(sshConfigPath)) {
|
if (fs.existsSync(sshConfigPath)) {
|
||||||
var reader = rd.createInterface(fs.createReadStream(sshConfigPath))
|
console.log(`[RemoteContainer] SSH config file exists, checking for existing host`);
|
||||||
|
|
||||||
|
const reader = rd.createInterface(fs.createReadStream(sshConfigPath));
|
||||||
|
|
||||||
for await (const line of reader) {
|
for await (const line of reader) {
|
||||||
if (line.includes(`Host ${host}`)) {
|
if (line.includes(`Host ${host}`)) {
|
||||||
// the container ssh info exists
|
// the container ssh info exists
|
||||||
canAppendSSHConfig = false
|
console.log(`[RemoteContainer] Host ${host} already exists in SSH config`);
|
||||||
|
canAppendSSHConfig = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[RemoteContainer] SSH config file does not exist, will create it`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (canAppendSSHConfig) {
|
if (canAppendSSHConfig) {
|
||||||
// save the host to the local ssh config file
|
// save the host to the local ssh config file
|
||||||
const privateKeyPath = this.user.getUserPrivateKeyPath();
|
const privateKeyPath = this.user.getUserPrivateKeyPath();
|
||||||
|
console.log(`[RemoteContainer] Using private key path: ${privateKeyPath}`);
|
||||||
|
|
||||||
const newSShConfigContent =
|
const newSShConfigContent =
|
||||||
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
|
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
|
||||||
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
|
|
||||||
console.log('Host registered in local ssh config');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
|
||||||
|
console.log('[RemoteContainer] Host registered in local ssh config');
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error('[RemoteContainer] Failed to write SSH config:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* local env
|
* local env
|
||||||
@@ -203,13 +313,25 @@ export default class RemoteContainer {
|
|||||||
* @host 表示project name
|
* @host 表示project name
|
||||||
*/
|
*/
|
||||||
openRemoteFolder(host: string, port: number, username: string, path: string): void {
|
openRemoteFolder(host: string, port: number, username: string, path: string): void {
|
||||||
|
console.log(`[RemoteContainer] openRemoteFolder called with:`, { host, port, username, path });
|
||||||
|
|
||||||
|
try {
|
||||||
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
||||||
terminal.show(true);
|
terminal.show(true);
|
||||||
// 在原窗口打开
|
|
||||||
terminal.sendText(`code --remote ssh-remote+${username}@${host}:${port} ${path} --reuse-window`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const command = `code --remote ssh-remote+root@${host}:${port} ${path} --reuse-window`;
|
||||||
|
console.log(`[RemoteContainer] Sending command to terminal: ${command}`);
|
||||||
|
|
||||||
|
// 在原窗口打开
|
||||||
|
terminal.sendText(command);
|
||||||
|
console.log(`[RemoteContainer] Command sent successfully`);
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error(`[RemoteContainer] Error in openRemoteFolder:`, error);
|
||||||
|
vscode.window.showErrorMessage(`打开远程文件夹失败: ${errorMessage}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 打开项目(无须插件登录)
|
* 打开项目(无须插件登录)
|
||||||
@@ -219,8 +341,19 @@ export default class RemoteContainer {
|
|||||||
* @param path
|
* @param path
|
||||||
*/
|
*/
|
||||||
export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> {
|
export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> {
|
||||||
|
console.log(`[RemoteContainer] openProjectWithoutLogging called with:`, { hostname, port, username, path });
|
||||||
|
|
||||||
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`
|
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`
|
||||||
|
console.log(`[RemoteContainer] Command: ${command}`);
|
||||||
|
|
||||||
|
try {
|
||||||
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
|
||||||
terminal.show(true);
|
terminal.show(true);
|
||||||
terminal.sendText(command);
|
terminal.sendText(command);
|
||||||
|
console.log(`[RemoteContainer] openProjectWithoutLogging completed successfully`);
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage = error instanceof Error ? error.message : '未知错误';
|
||||||
|
console.error(`[RemoteContainer] Error in openProjectWithoutLogging:`, error);
|
||||||
|
vscode.window.showErrorMessage(`无登录打开项目失败: ${errorMessage}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user