Files
webssh/webssh/static/js/main.js
T

1143 lines
31 KiB
JavaScript
Executable File

/*jslint browser:true */
var jQuery;
var wssh = {};
(function() {
// For FormData without getter and setter
var proto = FormData.prototype,
data = {};
if (!proto.get) {
proto.get = function (name) {
if (data[name] === undefined) {
var input = document.querySelector('input[name="' + name + '"]'),
value;
if (input) {
if (input.type === 'file') {
value = input.files[0];
} else {
value = input.value;
}
data[name] = value;
}
}
return data[name];
};
}
if (!proto.set) {
proto.set = function (name, value) {
data[name] = value;
};
}
}());
jQuery(function($){
var status = $('#status'),
button = $('#connect .btn-primary'),
form_container = $('.form-container'),
waiter = $('#waiter'),
saved_connections_select = $('#saved-connections'),
load_connection_button = $('#load-connection'),
delete_connection_button = $('#delete-connection'),
show_password_checkbox = $('#show-password'),
term_type = $('#term'),
quickbar = $('#quickbar'),
terminal_toast = $('#terminal-toast'),
toast_timer,
style = {},
default_title = 'WebSSH',
title_element = document.querySelector('title'),
form_id = '#connect',
debug = document.querySelector(form_id).noValidate,
custom_font = document.fonts ? document.fonts.values().next().value : undefined,
default_fonts,
current_terminal,
DISCONNECTED = 0,
CONNECTING = 1,
CONNECTED = 2,
state = DISCONNECTED,
messages = {1: '正在连接,请稍候 ...', 2: '当前客户端已经连接。'},
key_max_size = 16384,
directory_max_size = 1024,
fields = ['hostname', 'port', 'username'],
form_keys = fields.concat(['password', 'totp', 'directory']),
opts_keys = ['bgcolor', 'title', 'encoding', 'command', 'term', 'fontsize', 'fontcolor', 'cursor'],
url_form_data = {},
url_opts_data = {},
saved_connections = [],
saved_connection_map = {},
validated_form_data,
pending_connection,
event_origin,
hostname_tester = /((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))|(^\s*((?=.{1,255}$)(?=.*[A-Za-z].*)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?)*)\s*$)/;
function store_items(names, data) {
var i, name, value;
for (i = 0; i < names.length; i++) {
name = names[i];
value = data.get(name);
if (value){
window.localStorage.setItem(name, value);
}
}
}
function restore_items(names) {
var i, name, value;
for (i=0; i < names.length; i++) {
name = names[i];
value = window.localStorage.getItem(name);
if (value) {
$('#'+name).val(value);
}
}
}
function get_xsrf_token() {
var input = document.querySelector('input[name="_xsrf"]');
return input ? input.value : '';
}
function set_saved_connections(connections) {
var i, profile;
saved_connections = connections || [];
saved_connection_map = {};
for (i = 0; i < saved_connections.length; i++) {
profile = saved_connections[i];
saved_connection_map[profile.id] = profile;
}
var group = $('#connection-group').val(), groups = [];
$('#connection-group').empty().append($('<option>').val('').text('全部分组'));
saved_connections.forEach(function(profile) {
if (profile.group && groups.indexOf(profile.group) < 0) { groups.push(profile.group); }
});
groups.sort().forEach(function(value) { $('#connection-group').append($('<option>').val(value).text(value)); });
$('#connection-group').val(groups.indexOf(group) >= 0 ? group : '');
render_saved_connections();
}
function render_saved_connections(selected) {
var i, profile, option;
saved_connections_select.empty();
saved_connections_select.append(
$('<option>').val('').text('未选择保存的连接')
);
for (i = 0; i < saved_connections.length; i++) {
profile = saved_connections[i];
var query = ($('#connection-search').val() || '').toLowerCase(), group = $('#connection-group').val();
if ((group && profile.group !== group) ||
[profile.name, profile.group, profile.notes, profile.title].join(' ').toLowerCase().indexOf(query) < 0) { continue; }
option = $('<option>').val(profile.id).text((profile.group ? '[' + profile.group + '] ' : '') + (profile.name || profile.title));
saved_connections_select.append(option);
}
if (selected) {
saved_connections_select.val(selected);
}
}
function upsert_saved_connection(profile) {
var i, found = false;
if (!profile || !profile.id) {
return;
}
for (i = 0; i < saved_connections.length; i++) {
if (saved_connections[i].id === profile.id) {
saved_connections[i] = profile;
found = true;
break;
}
}
if (!found) {
saved_connections.unshift(profile);
}
saved_connection_map[profile.id] = profile;
set_saved_connections(saved_connections);
render_saved_connections(profile.id);
update_saved_key_hint(profile);
}
function load_saved_connections() {
$.ajax({
url: 'connections',
type: 'get',
success: function(data) {
set_saved_connections(data.connections);
},
error: function(resp) {
if (resp.status !== 404) {
console.error(resp.status + ': ' + resp.statusText);
}
}
});
}
function selected_connection() {
var profile_id = saved_connections_select.val();
return saved_connection_map[profile_id];
}
function update_password_visibility() {
$('#password').attr(
'type',
show_password_checkbox.prop('checked') ? 'text' : 'password'
);
}
function apply_saved_connection() {
var profile = selected_connection();
if (!profile) {
apply_saved_password_hint(false);
update_saved_key_hint(null);
return;
}
$('#hostname').val(profile.hostname);
$('#port').val(profile.port);
$('#username').val(profile.username);
$('#privatekey').val('');
$('#passphrase').val('');
$('#totp').val('');
$('#directory').val(profile.directory || '');
$('#connection-name').val(profile.name || '');
$('#connection-group-name').val(profile.group || '');
$('#connection-notes').val(profile.notes || '');
term_type.val(profile.term || 'xterm-256color');
apply_saved_password_hint(profile.has_password);
$('#save-credentials').prop(
'checked', !!(profile.has_password || profile.has_privatekey)
);
$('#save-passphrase').prop('checked', !!profile.has_passphrase);
update_saved_key_hint(profile);
status.text('');
}
function update_saved_key_hint(profile) {
$('#privatekey-hint').text(
profile && profile.has_privatekey ?
'已保存私钥,无需上传;上传新文件可替换' : ''
);
$('#passphrase').attr('placeholder',
profile && profile.has_passphrase ? '已保存口令,留空即可使用' : ''
);
}
function apply_saved_password_hint(has_password) {
// the server never sends saved passwords to the browser; an empty
// field just tells it to use the one it already has on disk
var password = $('#password');
password.val('');
password.attr(
'placeholder',
has_password ? '已保存密码,留空即可直接连接' : ''
);
}
function delete_saved_connection() {
var profile = selected_connection();
if (!profile) {
return;
}
$.ajax({
url: 'connections/' + profile.id,
type: 'delete',
headers: {'X-XSRFToken': get_xsrf_token()},
success: function() {
set_saved_connections(
saved_connections.filter(function(item) {
return item.id !== profile.id;
})
);
apply_saved_password_hint(false);
update_saved_key_hint(null);
},
error: function(resp) {
log_status(resp.status + ': ' + resp.statusText);
}
});
}
function populate_form(data) {
var names = form_keys.concat(['passphrase']),
i, name;
for (i=0; i < names.length; i++) {
name = names[i];
$('#'+name).val(data.get(name));
}
}
function get_object_length(object) {
return Object.keys(object).length;
}
function decode_uri_component(uri) {
try {
return decodeURIComponent(uri);
} catch(e) {
console.error(e);
}
return '';
}
function decode_password(encoded) {
try {
return window.atob(encoded);
} catch (e) {
console.error(e);
}
return null;
}
function parse_url_data(string, form_keys, opts_keys, form_map, opts_map) {
var i, pair, key, val,
arr = string.split('&');
for (i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
key = pair[0].trim().toLowerCase();
val = pair.slice(1).join('=').trim();
if (form_keys.indexOf(key) >= 0) {
form_map[key] = val;
} else if (opts_keys.indexOf(key) >=0) {
opts_map[key] = val;
}
}
if (form_map.password) {
form_map.password = decode_password(form_map.password);
}
}
function parse_xterm_style() {
var text = $('.xterm-helpers style').text();
var arr = text.split('xterm-normal-char{width:');
style.width = parseFloat(arr[1]);
arr = text.split('div{height:');
style.height = parseFloat(arr[1]);
}
function get_cell_size(term) {
style.width = term._core._renderService._renderer.dimensions.actualCellWidth;
style.height = term._core._renderService._renderer.dimensions.actualCellHeight;
}
function toggle_fullscreen(term) {
$('#terminal').toggleClass('terminal-fullscreen');
term.fitAddon.fit();
resize_terminal(term);
}
function terminal_size() {
var terminal = document.getElementById('terminal'),
rect = terminal.getBoundingClientRect(),
width = rect.width || window.innerWidth,
height = rect.height || window.innerHeight;
return {'width': width, 'height': height};
}
function current_geometry(term) {
if (!style.width || !style.height) {
try {
get_cell_size(term);
} catch (TypeError) {
parse_xterm_style();
}
}
var size = terminal_size(),
cols = Math.max(2, parseInt(size.width / style.width, 10)),
rows = Math.max(1, parseInt(size.height / style.height, 10));
return {'cols': cols, 'rows': rows};
}
function resize_terminal(term) {
var geometry = current_geometry(term);
term.on_resize(geometry.cols, geometry.rows);
}
function set_backgound_color(term, color) {
term.setOption('theme', {
background: color
});
}
function set_font_color(term, color) {
term.setOption('theme', {
foreground: color
});
}
function custom_font_is_loaded() {
if (!custom_font) {
console.log('No custom font specified.');
} else {
console.log('Status of custom font ' + custom_font.family + ': ' + custom_font.status);
if (custom_font.status === 'loaded') {
return true;
}
if (custom_font.status === 'unloaded') {
return false;
}
}
}
function update_font_family(term) {
if (term.font_family_updated) {
console.log('Already using custom font family');
return;
}
if (!default_fonts) {
default_fonts = term.getOption('fontFamily');
}
if (custom_font_is_loaded()) {
var new_fonts = custom_font.family + ', ' + default_fonts;
term.setOption('fontFamily', new_fonts);
term.font_family_updated = true;
console.log('Using custom font family ' + new_fonts);
}
}
function reset_font_family(term) {
if (!term.font_family_updated) {
console.log('Already using default font family');
return;
}
if (default_fonts) {
term.setOption('fontFamily', default_fonts);
term.font_family_updated = false;
console.log('Using default font family ' + default_fonts);
}
}
function format_geometry(cols, rows) {
return JSON.stringify({'cols': cols, 'rows': rows});
}
function show_terminal_toast(text) {
terminal_toast.text(text).addClass('visible');
window.clearTimeout(toast_timer);
toast_timer = window.setTimeout(function() {
terminal_toast.removeClass('visible');
}, 1500);
}
function fallback_copy_text(text) {
var textarea = document.createElement('textarea'),
copied = false;
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.top = '-9999px';
document.body.appendChild(textarea);
textarea.select();
try {
copied = document.execCommand('copy');
} catch (e) {
console.error(e);
}
document.body.removeChild(textarea);
return copied;
}
function copy_text_to_clipboard(text, callback) {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(
function() { callback(true); },
function() { callback(fallback_copy_text(text)); }
);
} else {
callback(fallback_copy_text(text));
}
}
function read_clipboard_text(on_text, on_error) {
if (navigator.clipboard && navigator.clipboard.readText) {
navigator.clipboard.readText().then(on_text, on_error);
return true;
} else {
return false;
}
}
function read_as_text_with_decoder(file, callback, decoder) {
var reader = new window.FileReader();
if (decoder === undefined) {
decoder = new window.TextDecoder('utf-8', {'fatal': true});
}
reader.onload = function() {
var text;
try {
text = decoder.decode(reader.result);
} catch (TypeError) {
console.log('Decoding error happened.');
} finally {
if (callback) {
callback(text);
}
}
};
reader.onerror = function (e) {
console.error(e);
};
reader.readAsArrayBuffer(file);
}
function read_as_text_with_encoding(file, callback, encoding) {
var reader = new window.FileReader();
if (encoding === undefined) {
encoding = 'utf-8';
}
reader.onload = function() {
if (callback) {
callback(reader.result);
}
};
reader.onerror = function (e) {
console.error(e);
};
reader.readAsText(file, encoding);
}
function read_file_as_text(file, callback, decoder) {
if (!window.TextDecoder) {
read_as_text_with_encoding(file, callback, decoder);
} else {
read_as_text_with_decoder(file, callback, decoder);
}
}
function reset_wssh() {
var name;
for (name in wssh) {
if (wssh.hasOwnProperty(name) && name !== 'connect') {
delete wssh[name];
}
}
}
function clear_terminal() {
if (current_terminal) {
try {
current_terminal.dispose();
} catch (e) {
console.error(e);
}
current_terminal = undefined;
}
$('#terminal').removeClass('terminal-fullscreen').empty();
quickbar.hide();
$('body').removeClass('quickbar-open');
}
function write_disconnect_message(term, reason) {
var text = translate_status(reason) || '连接已断开。';
if (term) {
try {
term.write('\r\n\r\n\x1b[33m' + text + '\x1b[0m\r\n');
term.setOption('disableStdin', true);
} catch (e) {
console.error(e);
}
}
return text;
}
function log_status(text, to_populate) {
text = translate_status(text);
if (to_populate) { $('#workspace').removeClass('workspace-fullscreen'); }
if (text) {
console.log(text);
}
status.text(text);
if (to_populate && validated_form_data) {
populate_form(validated_form_data);
validated_form_data = undefined;
}
if (waiter.css('display') !== 'none') {
waiter.hide();
}
if (form_container.css('display') === 'none') {
form_container.show();
}
}
function translate_status(text) {
if (!text) {
return text;
}
var replacements = [
['Authentication failed.', '认证失败。'],
['Bad authentication type.', '认证方式不被服务器支持。'],
['Bad host key.', '主机密钥校验失败。'],
['Too many live connections.', '当前客户端连接数过多。'],
['Cross origin operation is not allowed.', '不允许跨来源操作。'],
['Missing value hostname', '请输入主机地址。'],
['Missing value username', '请输入 SSH 用户名。'],
['Missing argument hostname', '缺少主机地址。'],
['Missing argument username', '缺少 SSH 用户名。'],
['Need a verification code for 2fa.', '需要输入动态验证码。'],
['Login required.', '登录状态已失效,请重新登录。'],
['Websocket authentication failed.', 'WebSocket 认证失败。'],
['websocket closed', 'WebSocket 连接已关闭。'],
['client disconnected', '客户端连接已断开。'],
['chan closed', 'SSH 会话已关闭。'],
['chan error on reading', '读取 SSH 会话时连接中断。'],
['chan error on writing', '写入 SSH 会话时连接中断。'],
['worker recycled', '连接等待超时,已被回收。'],
['Worker closed', 'SSH 工作连接已关闭。'],
['No worker found', '未找到活动的 SSH 连接。']
];
var i, item;
for (i = 0; i < replacements.length; i++) {
item = replacements[i];
if (text === item[0]) {
return item[1];
}
}
if (text.indexOf('Unable to connect to ') === 0) {
return '无法连接到 ' + text.slice('Unable to connect to '.length);
}
if (text.indexOf('Invalid hostname: ') === 0) {
return '主机地址无效:' + text.slice('Invalid hostname: '.length);
}
if (text.indexOf('Invalid port: ') === 0) {
return '端口无效:' + text.slice('Invalid port: '.length);
}
if (text.indexOf('Invalid private key: ') === 0) {
return '私钥文件无效:' + text.slice('Invalid private key: '.length);
}
if (text.indexOf('Invalid directory: ') === 0) {
return '初始目录无效:' + text.slice('Invalid directory: '.length);
}
return text;
}
function ajax_complete_callback(resp) {
button.prop('disabled', false);
state = DISCONNECTED;
waiter.hide();
var msg = resp.responseJSON;
if (resp.status !== 200 || !msg || !msg.id) {
log_status(msg && msg.status || resp.status + ': ' + resp.statusText, true);
return;
}
if (msg.profile) { upsert_saved_connection(msg.profile); }
status.text('');
wssh.workspace.create(msg, pending_connection || {}, $.extend({}, url_opts_data), {
toast: show_terminal_toast, translate: translate_status,
copy: copy_text_to_clipboard, clipboard: read_clipboard_text,
font: update_font_family,
reconnect: function(connection) {
$('#workspace').removeClass('workspace-fullscreen');
$('#hostname').val(connection.hostname);
$('#port').val(connection.port);
$('#username').val(connection.username);
$('#directory').val(connection.directory || '');
$('#connection-name').val(connection.name || '');
$('#connection-group-name').val(connection.group || '');
$('#connection-notes').val(connection.notes || '');
$('#password, #privatekey, #passphrase, #totp').val('');
var id, profile;
for (id in saved_connection_map) {
profile = saved_connection_map[id];
if (profile.hostname === connection.hostname &&
Number(profile.port) === Number(connection.port || 22) &&
profile.username === connection.username) {
saved_connections_select.val(profile.id);
$('#connection-search').val('');
$('#connection-group').val('');
render_saved_connections(profile.id);
apply_saved_connection();
if (!profile.requires_totp && (profile.has_password ||
(profile.has_privatekey && (!profile.key_requires_passphrase || profile.has_passphrase)))) {
connect();
} else {
form_container.show();
log_status('连接已载入,可直接连接;加密私钥需补充口令,双因素认证需填写验证码。');
}
return;
}
}
form_container.show();
log_status('请补充密码、私钥或动态验证码后连接。');
}
});
delete url_opts_data.command;
$('#password, #privatekey, #passphrase, #totp').val('');
validated_form_data = undefined;
pending_connection = undefined;
}
function wrap_object(opts) {
var obj = {};
obj.get = function(attr) {
return opts[attr] || '';
};
obj.set = function(attr, val) {
opts[attr] = val;
};
return obj;
}
function clean_data(data) {
var i, attr, val;
var attrs = form_keys.concat(['privatekey', 'passphrase']);
for (i = 0; i < attrs.length; i++) {
attr = attrs[i];
val = data.get(attr);
if (typeof val === 'string') {
data.set(attr, val.trim());
}
}
}
function validate_form_data(data) {
clean_data(data);
var hostname = data.get('hostname'),
port = data.get('port'),
username = data.get('username'),
pk = data.get('privatekey'),
directory = data.get('directory'),
result = {
valid: false,
data: data,
title: ''
},
errors = [], size;
if (!hostname) {
errors.push('请输入主机地址。');
} else {
if (!hostname_tester.test(hostname)) {
errors.push('主机地址无效:' + hostname);
}
}
if (!port) {
port = 22;
} else {
if (!(port > 0 && port <= 65535)) {
errors.push('端口无效:' + port);
}
}
if (!username) {
errors.push('请输入 SSH 用户名。');
}
if (pk) {
size = pk.size || pk.length;
if (size > key_max_size) {
errors.push('私钥文件无效:' + pk.name || '');
}
}
if (directory) {
if (directory.length > directory_max_size ||
/[\x00-\x1f\x7f]/.test(directory)) {
errors.push('初始目录无效:' + directory);
}
}
if (!errors.length || debug) {
result.valid = true;
result.title = username + '@' + hostname + ':' + port;
}
result.errors = errors;
return result;
}
// Fix empty input file ajax submission error for safari 11.x
function disable_file_inputs(inputs) {
var i, input;
for (i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.files.length === 0) {
input.setAttribute('disabled', '');
}
}
}
function enable_file_inputs(inputs) {
var i;
for (i = 0; i < inputs.length; i++) {
inputs[i].removeAttribute('disabled');
}
}
function connect_without_options() {
// use data from the form
var form = document.querySelector(form_id),
inputs = form.querySelectorAll('input[type="file"]'),
url = form.action,
data, pk;
disable_file_inputs(inputs);
data = new FormData(form);
pk = data.get('privatekey');
enable_file_inputs(inputs);
function ajax_post() {
status.text('');
button.prop('disabled', true);
$.ajax({
url: url,
type: 'post',
data: data,
complete: ajax_complete_callback,
cache: false,
contentType: false,
processData: false
});
}
var result = validate_form_data(data);
if (!result.valid) {
log_status(result.errors.join('\n'));
return;
}
if (pk && pk.size && !debug) {
read_file_as_text(pk, function(text) {
if (text === undefined) {
state = DISCONNECTED;
log_status('私钥文件无效:' + pk.name);
} else {
ajax_post();
}
});
} else {
ajax_post();
}
return result;
}
function connect_with_options(data) {
// use data from the arguments
var form = document.querySelector(form_id),
url = data.url || form.action,
_xsrf = form.querySelector('input[name="_xsrf"]');
var result = validate_form_data(wrap_object(data));
if (!result.valid) {
log_status(result.errors.join('\n'));
return;
}
data.term = term_type.val();
data._xsrf = _xsrf.value;
if (event_origin) {
data._origin = event_origin;
}
status.text('');
button.prop('disabled', true);
$.ajax({
url: url,
type: 'post',
data: data,
complete: ajax_complete_callback
});
return result;
}
function connect(hostname, port, username, password, privatekey, passphrase, totp, directory) {
// for console use
var result, opts;
if (state === CONNECTING) {
console.log(messages[state]);
return;
}
if (hostname === undefined) {
result = connect_without_options();
} else {
if (typeof hostname === 'string') {
opts = {
hostname: hostname,
port: port,
username: username,
password: password,
privatekey: privatekey,
passphrase: passphrase,
totp: totp,
directory: directory
};
} else {
opts = hostname;
}
result = connect_with_options(opts);
}
if (result && result.valid) {
pending_connection = {};
['hostname', 'port', 'username', 'directory', 'term', 'name', 'group', 'notes'].forEach(function(key) {
pending_connection[key] = result.data.get(key) || '';
});
pending_connection.requires_totp = !!result.data.get('totp');
state = CONNECTING;
default_title = result.title;
if (hostname) {
validated_form_data = result.data;
}
store_items(fields, result.data);
}
}
wssh.connect = connect;
$(form_id).submit(function(event){
event.preventDefault();
connect();
});
$(form_id).on('reset', function() {
window.setTimeout(function() {
update_password_visibility();
saved_connections_select.val('');
apply_saved_password_hint(false);
update_saved_key_hint(null);
}, 0);
});
$('#connection-search').on('input', function() { render_saved_connections(saved_connections_select.val()); });
$('#connection-group').on('change', function() { render_saved_connections(); });
wssh.refresh_connections = function(connections) { set_saved_connections(connections); };
$('#edit-connection').on('click', function() {
var profile = selected_connection();
if (!profile) { log_status('请先选择连接。'); return; }
$.ajax({url: 'connections/' + profile.id + '/metadata', type: 'POST',
contentType: 'application/json', headers: {'X-XSRFToken': get_xsrf_token()},
data: JSON.stringify({name: $('#connection-name').val(), group: $('#connection-group-name').val(), notes: $('#connection-notes').val()}),
success: function(data) { upsert_saved_connection(data.profile); set_saved_connections(saved_connections); saved_connections_select.val(data.profile.id); show_terminal_toast('备注已保存'); },
error: function() { log_status('保存备注失败。'); }
});
});
load_connection_button.click(function() {
apply_saved_connection();
});
saved_connections_select.change(function() {
apply_saved_connection();
});
$('#hostname, #port, #username').on('input', function() {
$('#password').attr('placeholder', '');
update_saved_key_hint(null);
});
$('#privatekey').on('change', function() {
$('#passphrase').val('').attr('placeholder', '');
$('#privatekey-hint').text(
this.files.length ? '成功连接并勾选保存凭据后替换已保存私钥' : ''
);
});
delete_connection_button.click(function() {
delete_saved_connection();
});
show_password_checkbox.change(function() {
update_password_visibility();
});
function is_connect_options(data) {
return data && typeof data === 'object' && !Array.isArray(data) && (
data.hostname ||
data.port ||
data.username ||
data.password ||
data.privatekey ||
data.passphrase ||
data.totp ||
data.url
);
}
function parse_connect_message(data) {
var args;
if (typeof data === 'string') {
try {
args = JSON.parse(data);
} catch (e) {
args = data.split('|');
}
} else {
args = data;
}
if (Array.isArray(args) || typeof args === 'string') {
return args;
}
if (is_connect_options(args)) {
return args;
}
}
function cross_origin_connect(event)
{
var prop = 'connect',
args = parse_connect_message(event.data);
if (args === undefined) {
return;
}
if (!Array.isArray(args)) {
args = [args];
}
console.log(event.origin);
try {
event_origin = event.origin;
wssh[prop].apply(wssh, args);
} finally {
event_origin = undefined;
}
}
window.addEventListener('message', cross_origin_connect, false);
if (document.fonts) {
document.fonts.ready.then(
function () {
if (custom_font_is_loaded() === false) {
document.body.style.fontFamily = custom_font.family;
}
}
);
}
parse_url_data(
decode_uri_component(window.location.search.substring(1)) + '&' + decode_uri_component(window.location.hash.substring(1)),
form_keys, opts_keys, url_form_data, url_opts_data
);
// console.log(url_form_data);
// console.log(url_opts_data);
if (url_opts_data.term) {
term_type.val(url_opts_data.term);
}
if (url_form_data.password === null) {
log_status('URL 中的密码必须使用 base64 编码。');
} else {
if (get_object_length(url_form_data)) {
waiter.show();
connect(url_form_data);
} else {
load_saved_connections();
restore_items(fields);
form_container.show();
}
}
});