blockbench/js/edit_sessions.js

527 lines
13 KiB
JavaScript
Raw Normal View History

class EditSession {
constructor() {
this.active = false;
this.hosting = false;
this.clients = {};
this.client_count = 1;
this.data_queue = [];
this.chat_history = [];
this.Project = Project || null;
Interface.Panels.chat.inside_vue.chat_history = this.chat_history;
if (Project) Project.EditSession = this;
}
updateClientCount() {
this.client_count = Math.clamp(Object.keys(this.clients).length, 1, 999);
}
start(username) {
if (this.active) return;
2019-04-08 00:53:33 +08:00
var peer = this.peer = new Peer({
2020-07-16 15:32:59 +08:00
key: 'edit_session',
host: EditSession.defaults.ip,
2020-07-16 15:32:59 +08:00
port: 9000,
2020-07-18 18:31:16 +08:00
path: '/sessions',
secure: true
2020-07-16 15:32:59 +08:00
});
this.username = username || EditSession.defaults.placeholder_names.random();
settings.username.value = this.username;
2019-04-08 00:53:33 +08:00
peer.on('open', (token) => {
this.hosting = true;
this.setState(true);
2019-04-13 00:44:18 +08:00
this.self = new EditSession.Client(this, {
id: this.peer.id,
name: this.username,
2019-04-13 00:44:18 +08:00
hosting: true
})
2019-04-08 00:53:33 +08:00
$('#edit_session_token').val(token)
this.token = token;
2019-04-08 00:53:33 +08:00
Clipbench.setText(token)
Blockbench.dispatchEvent('create_session', {peer, token})
})
peer.on('connection', (conn) => {
conn.on('open', () => {
2019-04-13 00:44:18 +08:00
var client = new EditSession.Client(this, {
2019-04-13 00:44:18 +08:00
id: conn.peer,
conn: conn,
name: conn.metadata.username,
hosting: false
})
this.processChatMessage({text: tl('edit_session.joined', [client.name]), color: 'green'})
2019-04-13 00:44:18 +08:00
Blockbench.showQuickMessage(tl('edit_session.joined', [client.name]))
//New Login
client.send({
type: 'chat_message',
data: {text: tl('edit_session.welcome', [this.username]), color: 'yellow'}
2019-04-13 00:44:18 +08:00
})
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: this.hosting,
sender: this.peer.id,
2019-04-08 00:53:33 +08:00
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
})
}
join(username, token) {
if (this.active) return;
2019-04-08 00:53:33 +08:00
this.hosting = false;
this.peer = new Peer({
2020-07-16 15:32:59 +08:00
key: 'edit_session',
host: EditSession.defaults.ip,
2020-07-16 15:32:59 +08:00
port: 9000,
2020-07-18 18:31:16 +08:00
path: '/sessions',
secure: true
2020-07-16 15:32:59 +08:00
});
this.peer.on('open', () => {
2020-07-16 15:32:59 +08:00
this.username = username || EditSession.defaults.placeholder_names.random();
settings.username.value = this.username;
if (!token || !EditSession.matchToken(token)) {
2020-07-16 15:32:59 +08:00
Blockbench.showMessageBox({
translateKey: 'invalid_session',
icon: 'cloud_off',
}, result => {
showDialog('edit_sessions');
})
return;
}
this.token = token;
var conn = this.peer.connect(token, {metadata: {username: this.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',
})
this.quit()
2020-07-16 15:32:59 +08:00
})
conn.on('open', () => {
hideDialog()
this.host = conn;
this.setState(true);
this.initConnection(conn)
2020-07-16 15:32:59 +08:00
Blockbench.dispatchEvent('join_session', {conn})
2019-04-08 00:53:33 +08:00
})
})
this.peer.on('error', error => {
2020-07-16 15:32:59 +08:00
console.error('Error in edit session:', error)
2019-04-08 00:53:33 +08:00
})
}
2019-07-18 00:02:07 +08:00
quit() {
if (!this.active) return;
2019-04-13 00:44:18 +08:00
2019-04-08 00:53:33 +08:00
Blockbench.dispatchEvent('quit_session', {})
if (this.hosting) {
this.sendAll('command', 'quit_session')
2019-04-08 00:53:33 +08:00
} else {
this.host.close()
2019-04-08 00:53:33 +08:00
}
ModelProject.all.forEach(project => {
if (project.EditSession == this) {
delete project.EditSession;
}
})
setTimeout(() => {
this.setState(false)
this.chat_history.purge()
this.peer.destroy()
2019-04-08 00:53:33 +08:00
Blockbench.showQuickMessage('edit_session.quit_session', 1500)
}, 400)
}
2019-07-18 00:02:07 +08:00
setState(active) {
this.active = active;
if (!active) {
this.hosting = false;
2019-04-08 00:53:33 +08:00
}
2019-04-13 00:44:18 +08:00
updateInterface()
}
2019-07-18 00:02:07 +08:00
copyToken() {
2019-04-08 00:53:33 +08:00
var input = $('#edit_session_token')
if (this.active) {
2019-04-08 00:53:33 +08:00
input.focus()
document.execCommand('selectAll')
document.execCommand('copy')
} else {
if (isApp) {
var token = clipboard.readText()
if (EditSession.matchToken(token)) {
2019-04-08 00:53:33 +08:00
$('#edit_session_token').val(token)
}
} else {
2019-07-18 00:02:07 +08:00
navigator.clipboard.readText().then((token) => {
if (EditSession.matchToken(token)) {
2019-07-18 00:02:07 +08:00
$('#edit_session_token').val(token)
}
})
2019-04-08 00:53:33 +08:00
}
}
}
2019-07-18 00:02:07 +08:00
initNewModel(force) {
if (this.active && this.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'
}
this.sendAll('init_model', model)
2019-04-08 00:53:33 +08:00
}
}
2019-07-18 00:02:07 +08:00
initConnection(conn) {
conn.on('data', (...args) => this.receiveData(...args))
}
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)
for (var key in this.peer.connections) {
var conns = this.peer.connections[key];
2019-04-13 04:39:53 +08:00
conns.forEach(conn => {
conn.send({
2019-04-08 00:53:33 +08:00
type: tag.type,
fromHost: this.hosting,
sender: this.peer.id,
2019-04-08 00:53:33 +08:00
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
}
this.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 (this.hosting && !tag.hostOnly && Object.keys(this.peer.connections).length > 1) {
2019-04-08 00:53:33 +08:00
//Redistribute
for (var id in this.peer.connections) {
2019-04-08 00:53:33 +08:00
if (id !== tag.sender) {
this.peer.connections[id][0].send(tag);
2019-04-08 00:53:33 +08:00
}
}
}
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 === 'chat_input' && this.hosting) {
this.processChatMessage(tag.data);
} else if (tag.type === 'chat_message') {
this.addChatMessage(tag.data);
} else {
if (Project.EditSession == this || (!this.Project)) {
this.processData(tag);
} else {
this.data_queue.push(tag);
}
}
2019-04-08 00:53:33 +08:00
}
processData(tag) {
let {data} = tag;
2019-04-08 00:53:33 +08:00
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);
this.Project = Project;
this.Project.EditSession = this;
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': this.quit(); break;
2019-04-08 00:53:33 +08:00
}
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
}
}
catchUp() {
while (this.data_queue.length) {
let tag = this.data_queue.shift();
try {
this.processData(tag);
} catch (err) {
console.error(err);
}
}
}
2019-04-13 00:44:18 +08:00
sendChat(text) {
if (typeof text !== 'string') {
text = $('input#chat_input').val()
$('input#chat_input').val('')
2019-04-08 00:53:33 +08:00
}
if (!text) return;
this.processChatMessage({
author: this.username,
text: text,
sender: this.peer.id
})
2019-04-08 00:53:33 +08:00
}
addChatMessage(message) {
if (!(message instanceof EditSession.ChatMessage)) {
message = new EditSession.ChatMessage(this, message)
}
if (!message.text) return;
this.chat_history.push(message)
Vue.nextTick(() => {
$('#chat_history').scrollTop(10000)
})
if (!document.hasFocus() && !message.self) {
Blockbench.notification(message.author ? message.author+':' : 'Chat', message.text)
}
return message;
}
processChatMessage(data) {
if (!this.hosting) {
this.host.send({
type: 'chat_input',
data,
sender: this.peer.id
})
return;
}
//Host Only
Blockbench.dispatchEvent('process_chat_message', data)
this.sendAll('chat_message', data)
this.addChatMessage(data)
}
}
EditSession.matchToken = function(token) {
return !!(token.length === 16 && token.match(/[a-z0-9]{16}/))
}
EditSession.defaults = {
max_chat_length: 512,
ip: 'blckbn.ch',
placeholder_names: ['R2D2', 'Tin Man', 'C3PO', 'WALL-E', 'EVE', 'BB-8', 'B1 Battle Droid', 'ASIMO', 'Atlas'],
2019-04-08 00:53:33 +08:00
}
2019-04-13 00:44:18 +08:00
EditSession.Client = class {
constructor(session, data) {
2019-04-13 00:44:18 +08:00
var scope = this;
this.id = data.id;
this.hosting = data.hosting;
this.conn = data.conn;
this.name = data.name;
this.session = session;
2019-04-13 00:44:18 +08:00
this.session.clients[this.id] = this;
this.session.updateClientCount()
2019-04-13 00:44:18 +08:00
if (this.conn) {
this.session.initConnection(this.conn)
2019-04-13 00:44:18 +08:00
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 (!this.session.clients[this.id]) return;
2019-08-01 06:01:47 +08:00
Blockbench.dispatchEvent('user_leaves_session', this)
delete this.session.peer.connections[this.conn.peer];
delete this.session.clients[this.id];
this.session.updateClientCount();
2019-04-13 00:44:18 +08:00
this.processChatMessage({text: tl('edit_session.left', [this.name]), color: 'red'})
2019-04-13 00:44:18 +08:00
Blockbench.showQuickMessage(tl('edit_session.left', [this.name]))
}
};
EditSession.ChatMessage = class {
constructor(session, data) {
this.session = session;
2019-04-13 00:44:18 +08:00
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 == this.session.peer.id;
this.text = data.text.substr(0, EditSession.defaults.max_chat_length)||'';
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 = this.session.chat_history.indexOf(this);
var prev = this.session.chat_history[this_i-1];
2019-04-13 00:44:18 +08:00
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: () => {
let session = Project && Project.EditSession;
var username, token;
if (session) {
username = session.username;
token = session.token;
} else {
username = settings.username.value;
if (!username && isApp) {
username = process.env.USERNAME
}
token = EditSession.token;
if (!token && isApp) {
let clipboard_token = clipboard.readText()
if (EditSession.matchToken(clipboard_token) && !$('#edit_session_token').val()) {
token = clipboard_token;
}
}
}
new Dialog({
id: 'edit_session',
title: 'dialog.edit_session.title',
form: {
username: {type: 'text', label: 'edit_session.username', value: username},
token: {type: 'text', label: 'edit_session.token', value: token, readonly: !!session},
about: {type: 'info', text: 'edit_session.about', condition: !session},
status: {type: 'info', text: `**${tl('edit_session.status')}**: ${(session && session.hosting) ? tl('edit_session.hosting') : tl('edit_session.connected')}`, condition: !!session},
},
buttons: session
? ['edit_session.quit', 'dialog.close']
: ['edit_session.join', 'edit_session.create', 'dialog.close'],
onButton(button) {
let result = this.getFormResult();
if (session && button == 0) {
session.quit();
} else if (!session && button != 2) {
if (button == 0) {
// Join
session = new EditSession();
session.join(result.username, result.token);
} else {
// Create
if (!Project) {
Formats.free.new();
}
session = new EditSession();
session.start(result.username);
}
}
}
}).show();
}
2019-04-08 00:53:33 +08:00
})
2020-09-22 05:23:42 +08:00
})
EditSession.initNewModel = function() {}
2020-09-22 05:23:42 +08:00
Interface.definePanels(function() {
Interface.Panels.chat = new Panel({
id: 'chat',
icon: 'chat',
condition: {method() {return Project.EditSession && Project.EditSession.active}},
2020-09-22 05:23:42 +08:00
toolbars: {},
onResize: t => {
},
component: {
data() {return {
chat_history: [],
chat_input: ''
}},
methods: {
sendMessage() {
if (Project && Project.EditSession) {
Project.EditSession.sendChat(this.chat_input);
this.chat_input = '';
}
}
},
2020-09-22 05:23:42 +08:00
template: `
<div>
2021-01-23 04:31:57 +08:00
<ul id="chat_history">
<li v-for="msg in chat_history">
2020-09-22 05:23:42 +08:00
<b v-if="msg.showAuthor()" v-bind:class="{self: msg.self}">{{ msg.author }}:</b>
<span class="text" v-bind:style="{color: msg.hex || 'inherit'}" v-html="msg.html"></span>
<span class="timestamp">{{ msg.timestamp }}</span>
</li>
</ul>
<div id="chat_bar">
<input type="text" id="chat_input" class="dark_bordered f_left" maxlength="512" v-model="chat_input">
<i class="material-icons" @click="sendMessage()">send</i>
2020-09-22 05:23:42 +08:00
</div>
</div>
`
}
})
2020-10-05 05:44:06 +08:00
})