blockbench/js/edit_sessions.js

430 lines
11 KiB
JavaScript
Raw Normal View History

2019-04-08 00:53:33 +08:00
const EditSession = {
active: false,
hosting: false,
BBKey: '1h3sq3hoj6vfkh',
2020-07-16 15:32:59 +08:00
ip: '104.248.38.177',
2019-04-13 00:44:18 +08:00
clients: {},
2019-07-18 00:02:07 +08:00
placeholder_names: ['R2D2', 'Tin Man', 'C3PO', 'WALL-E', 'EVE', 'BB-8', 'B1 Battle Droid', 'ASIMO', 'Atlas'],
start() {
2019-04-08 00:53:33 +08:00
if (EditSession.active) return;
2020-07-16 15:32:59 +08:00
var peer = EditSession.peer = new Peer({
key: 'edit_session',
host: EditSession.ip,
port: 9000,
2020-07-18 18:31:16 +08:00
path: '/sessions',
secure: false
2020-07-16 15:32:59 +08:00
});
2019-07-18 00:02:07 +08:00
EditSession.username = $('#edit_session_username').val() || EditSession.placeholder_names.random();
settings.username.value = EditSession.username;
2019-04-08 00:53:33 +08:00
peer.on('open', (token) => {
2019-04-13 00:44:18 +08:00
EditSession.hosting = true;
Prop.session = true;
EditSession.setState(true);
2020-05-31 21:54:04 +08:00
EditSession.self = new EditSession.Client({
2019-04-13 00:44:18 +08:00
id: EditSession.peer.id,
name: EditSession.username,
hosting: true
})
2019-04-08 00:53:33 +08:00
$('#edit_session_token').val(token)
EditSession.token = token;
Clipbench.setText(token)
Blockbench.dispatchEvent('create_session', {peer, token})
})
peer.on('connection', (conn) => {
conn.on('open', function() {
2019-04-13 00:44:18 +08:00
var client = new EditSession.Client({
id: conn.peer,
conn: conn,
name: conn.metadata.username,
hosting: false
})
Chat.processMessage({text: tl('edit_session.joined', [client.name]), color: 'green'})
Blockbench.showQuickMessage(tl('edit_session.joined', [client.name]))
//New Login
client.send({
type: 'chat_message',
data: {text: tl('edit_session.welcome', [EditSession.username]), color: 'yellow'}
})
var model = Codecs.project.compile({uuids: true, bitmaps: true, backup: true, history: true})
2019-04-13 00:44:18 +08:00
client.send({
2019-04-08 00:53:33 +08:00
type: 'init_model',
fromHost: EditSession.hosting,
sender: EditSession.peer.id,
data: model
})
})
})
2020-05-31 21:54:04 +08:00
peer.on('error', error => {
2020-07-16 15:32:59 +08:00
console.error('Error in edit session:', error)
2020-05-31 21:54:04 +08:00
})
2019-04-08 00:53:33 +08:00
},
2019-07-18 00:02:07 +08:00
join() {
2019-04-08 00:53:33 +08:00
if (EditSession.active) return;
var token = $('#edit_session_token').val()
2020-07-16 15:32:59 +08:00
EditSession.hosting = false;
EditSession.peer = new Peer({
key: 'edit_session',
host: EditSession.ip,
port: 9000,
2020-07-18 18:31:16 +08:00
path: '/sessions',
secure: false
2020-07-16 15:32:59 +08:00
});
EditSession.peer.on('open', function() {
EditSession.username = $('#edit_session_username').val() || EditSession.placeholder_names.random();
settings.username.value = EditSession.username;
if (!token || !EditSession._matchToken(token)) {
Blockbench.showMessageBox({
translateKey: 'invalid_session',
icon: 'cloud_off',
buttons: [tl('dialog.ok')],
}, result => {
showDialog('edit_sessions');
})
return;
}
EditSession.token = token;
var conn = EditSession.peer.connect(token, {metadata: {username: EditSession.username}});
2019-04-08 00:53:33 +08:00
2020-07-16 15:32:59 +08:00
conn.on('error', (err) => {
console.error('peer join error', err)
Blockbench.showMessageBox({
translateKey: 'invalid_session',
icon: 'cloud_off',
buttons: [tl('dialog.ok')],
})
EditSession.quit()
})
conn.on('open', () => {
hideDialog()
EditSession.host = conn;
EditSession.setState(true);
EditSession.initConnection(conn)
Blockbench.dispatchEvent('join_session', {conn})
2019-04-08 00:53:33 +08:00
})
})
2020-07-16 15:32:59 +08:00
EditSession.peer.on('error', error => {
console.error('Error in edit session:', error)
2019-04-08 00:53:33 +08:00
})
},
2019-07-18 00:02:07 +08:00
quit() {
2019-04-13 00:44:18 +08:00
if (!EditSession.active) return;
2019-04-08 00:53:33 +08:00
Blockbench.dispatchEvent('quit_session', {})
if (EditSession.hosting) {
EditSession.sendAll('command', 'quit_session')
} else {
EditSession.host.close()
}
setTimeout(function() {
EditSession.setState(false)
2019-04-13 00:44:18 +08:00
Chat.history.purge()
2019-04-08 00:53:33 +08:00
EditSession.peer.destroy()
Prop.session = false;
Prop.connections = 0;
Blockbench.showQuickMessage('edit_session.quit_session', 1500)
}, 400)
},
2019-07-18 00:02:07 +08:00
setState(active) {
2019-04-08 00:53:33 +08:00
EditSession.active = active;
$('#edit_session_username, #edit_session_token').attr('readonly', active)
if (active) {
$('.edit_session_inactive').hide()
$('.edit_session_active').show()
$('#edit_session_status').text(EditSession.hosting ? tl('edit_session.hosting') : tl('edit_session.connected'))
$('#edit_session_copy_button .tooltip').text(tl('action.copy'))
} else {
EditSession.hosting = false;
$('.edit_session_active').hide()
$('.edit_session_inactive').show()
$('#edit_session_copy_button .tooltip').text(tl('action.paste'))
$('#edit_session_token').val('')
}
2019-04-13 00:44:18 +08:00
updateInterface()
2019-04-08 00:53:33 +08:00
},
2019-07-18 00:02:07 +08:00
dialog() {
2019-04-08 00:53:33 +08:00
showDialog('edit_sessions');
2019-07-18 00:02:07 +08:00
if (!EditSession.active) {
var username = settings.username.value;
if (isApp) {
var token = clipboard.readText()
if (EditSession._matchToken(token) && !$('#edit_session_token').val()) {
$('#edit_session_token').val(token)
}
if (!username) {
username = process.env.USERNAME
}
2019-04-08 00:53:33 +08:00
}
2019-07-18 00:02:07 +08:00
if (!username) username = EditSession.placeholder_names.random()
2019-04-08 00:53:33 +08:00
if (username) {
$('#edit_session_username').val(username)
}
}
},
2019-07-18 00:02:07 +08:00
copyToken() {
2019-04-08 00:53:33 +08:00
var input = $('#edit_session_token')
if (EditSession.active) {
input.focus()
document.execCommand('selectAll')
document.execCommand('copy')
} else {
if (isApp) {
var token = clipboard.readText()
if (EditSession._matchToken(token)) {
$('#edit_session_token').val(token)
}
} else {
2019-07-18 00:02:07 +08:00
navigator.clipboard.readText().then((token) => {
if (EditSession._matchToken(token)) {
$('#edit_session_token').val(token)
}
})
2019-04-08 00:53:33 +08:00
}
}
},
2019-07-18 00:02:07 +08:00
initNewModel(force) {
2019-04-08 00:53:33 +08:00
if (EditSession.active && EditSession.hosting) {
var model = Codecs.project.compile({uuids: true, bitmaps: true, backup: true, flag: force ? 'force' : null})
2019-04-08 00:53:33 +08:00
if (force) {
model.flag = 'force'
}
2019-07-18 00:02:07 +08:00
EditSession.sendAll('init_model', model)
2019-04-08 00:53:33 +08:00
}
},
2019-07-18 00:02:07 +08:00
initConnection(conn) {
2019-04-08 00:53:33 +08:00
conn.on('data', EditSession.receiveData)
},
2019-07-18 00:02:07 +08:00
sendAll(type, data) {
2019-04-08 00:53:33 +08:00
var tag = {type, data}
Blockbench.dispatchEvent('send_session_data', tag)
2019-04-13 04:39:53 +08:00
for (var key in EditSession.peer.connections) {
var conns = EditSession.peer.connections[key];
conns.forEach(conn => {
conn.send({
2019-04-08 00:53:33 +08:00
type: tag.type,
fromHost: EditSession.hosting,
sender: EditSession.peer.id,
data: tag.data
2019-04-13 04:39:53 +08:00
});
})
2019-04-08 00:53:33 +08:00
}
if (Blockbench.hasFlag('log_session')) {
console.log('Sent Data:', type, data)
}
},
2019-07-18 00:02:07 +08:00
sendEdit(entry) {
2019-04-08 00:53:33 +08:00
var new_entry = {
before: omitKeys(entry.before, ['aspects']),
post: omitKeys(entry.post, ['aspects']),
save_history: entry.save_history,
action: entry.action
}
EditSession.sendAll('edit', JSON.stringify(new_entry))
},
2019-07-18 00:02:07 +08:00
receiveData(tag) {
2019-04-08 00:53:33 +08:00
if (Blockbench.hasFlag('log_session')) {
console.log('Received Data:', tag)
}
if (EditSession.hosting && !tag.hostOnly && Object.keys(EditSession.peer.connections).length > 1) {
//Redistribute
for (var id in EditSession.peer.connections) {
if (id !== tag.sender) {
EditSession.peer.connections[id][0].send(tag);
}
}
}
var data = tag.data;
if (typeof data === 'string' && (data.includes('"') || data.includes('['))) {
try {
data = tag.data = JSON.parse(data)
} catch (err) {
console.log(err)
return;
}
}
Blockbench.dispatchEvent('receive_session_data', tag)
if (tag.type === 'edit') {
Undo.remoteEdit(data)
2019-04-13 00:44:18 +08:00
2019-04-08 00:53:33 +08:00
} else if (tag.type === 'init_model') {
2019-07-18 00:02:07 +08:00
newProject(data.meta.type||'free', data.flag === 'force');
Codecs.project.parse(data);
2019-04-13 00:44:18 +08:00
2019-04-08 00:53:33 +08:00
} else if (tag.type === 'command') {
switch (data) {
case 'undo': Undo.undo(true); break;
case 'redo': Undo.redo(true); break;
case 'quit_session': EditSession.quit(); break;
}
2019-04-13 00:44:18 +08:00
2019-04-08 00:53:33 +08:00
} else if (tag.type === 'change_project_meta') {
for (var key in data) {
2019-04-13 00:44:18 +08:00
Project[key] = data[key];
2019-04-08 00:53:33 +08:00
}
2019-04-13 00:44:18 +08:00
} else if (tag.type === 'chat_input' && EditSession.hosting) {
Chat.processMessage(tag.data)
} else if (tag.type === 'chat_message') {
Chat.addMessage(tag.data)
2019-04-08 00:53:33 +08:00
}
},
2019-07-18 00:02:07 +08:00
updateClientCount() {
2019-04-13 00:44:18 +08:00
Prop.connections = Object.keys(EditSession.clients).length-1
},
2019-07-18 00:02:07 +08:00
_matchToken(token) {
2019-04-08 00:53:33 +08:00
return !!(token.length === 16 && token.match(/[a-z0-9]{16}/))
}
}
2019-04-13 00:44:18 +08:00
EditSession.Client = class {
constructor(data) {
var scope = this;
this.id = data.id;
this.hosting = data.hosting;
this.conn = data.conn;
this.name = data.name;
EditSession.clients[this.id] = this;
EditSession.updateClientCount()
if (this.conn) {
EditSession.initConnection(this.conn)
this.conn.on('close', () => {
scope.disconnect()
})
this.conn.on('error', (e) => {
scope.disconnect()
this.conn.close()
console.error(e)
})
2019-07-26 19:33:29 +08:00
Blockbench.dispatchEvent('user_joins_session', this)
2019-04-13 00:44:18 +08:00
}
}
send(tag) {
this.conn.send(tag)
}
disconnect(e) {
if (!EditSession.clients[this.id]) return;
2019-08-01 06:01:47 +08:00
Blockbench.dispatchEvent('user_leaves_session', this)
2019-04-13 00:44:18 +08:00
delete EditSession.peer.connections[this.conn.peer];
delete EditSession.clients[this.id];
EditSession.updateClientCount();
Chat.processMessage({text: tl('edit_session.left', [this.name]), color: 'red'})
Blockbench.showQuickMessage(tl('edit_session.left', [this.name]))
}
}
const Chat = {
history: [],
expanded: true,
maxlength: 512,
2019-07-18 00:02:07 +08:00
toggle() {
2019-04-13 00:44:18 +08:00
this.expanded = !this.expanded;
BarItems.toggle_chat.setIcon( Chat.expanded ? 'keyboard_arrow_down' : 'keyboard_arrow_up' )
},
2019-07-18 00:02:07 +08:00
send(text) {
2019-04-13 00:44:18 +08:00
if (typeof text !== 'string') {
text = $('input#chat_input').val()
$('input#chat_input').val('')
}
if (!text) return;
2019-08-01 06:01:47 +08:00
Chat.processMessage({
author: EditSession.username,
text: text,
sender: EditSession.peer.id
})
2019-04-13 00:44:18 +08:00
},
2019-07-18 00:02:07 +08:00
addMessage(message) {
2019-04-13 00:44:18 +08:00
if (!(message instanceof Chat.Message)) {
message = new Chat.Message(message)
}
2019-12-16 03:04:31 +08:00
if (!message.text) return;
2019-04-13 00:44:18 +08:00
Chat.history.push(message)
Vue.nextTick(() => {
$('#chat_history').scrollTop(10000)
})
2019-07-18 00:02:07 +08:00
if (!document.hasFocus() && !message.self) {
Blockbench.notification(message.author ? message.author+':' : 'Chat', message.text)
}
2019-04-13 00:44:18 +08:00
return message;
},
2019-07-18 00:02:07 +08:00
processMessage(data) {
2019-04-13 00:44:18 +08:00
if (!EditSession.hosting) {
2019-08-01 06:01:47 +08:00
EditSession.host.send({
type: 'chat_input',
data,
sender: EditSession.peer.id
})
2019-04-13 00:44:18 +08:00
return;
}
//Host Only
2019-12-16 03:04:31 +08:00
Blockbench.dispatchEvent('process_chat_message', data)
2019-04-13 00:44:18 +08:00
EditSession.sendAll('chat_message', data)
Chat.addMessage(data)
}
};
Chat.Message = class {
constructor(data) {
this.author = data.author||'';
this.author = this.author.substr(0, 64)
2019-08-01 06:01:47 +08:00
this.sender = data.sender
this.self = data.sender == EditSession.peer.id;
2019-04-13 00:44:18 +08:00
this.text = data.text.substr(0, Chat.maxlength)||'';
2019-07-18 00:02:07 +08:00
this.html = this.text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
this.html = this.html.replace(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g, (text, i) => {
return `<a href="${text}" class="open-in-browser">${text}</a>`;
})
2019-04-13 01:13:06 +08:00
var date = new Date();
this.timestamp = date.getTimestamp()
2019-04-13 00:44:18 +08:00
this.toString = () => (this.author + ': ' + this.content);
//Color
this.color = data.color
switch (this.color) {
case 'red': this.hex = '#ff4158'; break;
case 'orange': this.hex = '#ff6f10'; break;
case 'yellow': this.hex = '#ffd100'; break;
case 'green': this.hex = '#00eb3b'; break;
case 'blue': this.hex = '#08a3ff'; break;
}
}
toObject() {
return {
author: this.author,
text: this.text,
color: this.color,
}
}
showAuthor() {
if (!this.author) return false;
var this_i = Chat.history.indexOf(this);
var prev = Chat.history[this_i-1];
return (!prev) || (prev.author !== this.author);
}
}
2019-04-08 00:53:33 +08:00
BARS.defineActions(function() {
2019-08-18 00:26:14 +08:00
new Action('edit_session', {
2019-04-08 00:53:33 +08:00
icon: 'people',
category: 'blockbench',
click: EditSession.dialog
})
2019-08-18 00:26:14 +08:00
new Action('toggle_chat', {
2019-04-13 00:44:18 +08:00
icon: 'keyboard_arrow_down',
condition: () => EditSession.active,
category: 'blockbench',
click: () => (Chat.toggle())
})
2019-04-08 00:53:33 +08:00
})