We make a messenger for paranoid on Webix and DataBoom

  • Tutorial
For those who have not yet launched the web application production pipeline, I will show how simple and fast it is.
It was for speed that I took the “speedy” bunch of webix + databoom.

With webix, we will develop our front-end, and the databoom will serve as the back-end.

What should be the result? An application with which two (or more?) Users will be able to exchange information without feeding their paranoia.

The set of elements is as follows:
  • Message text field
  • Alias ​​field
  • Message Submission Button
  • The message list itself
  • Additional options


Let's start with the front end


We will connect webix and we will distribute markup of the future application
webix.ui(
		{rows:[
			{view:'toolbar', cols:[
				// Тулбар
			]},
			// Сообщения,
			{view: 'resizer'},
			{view:'form', elements:[
				{cols:[
					// Текстовое поле
					{rows:[
						// Псевдоним (никнейм),
						// Кнопка отправки
					]}
				]}
			]}
		]}
	)


So far, everything is simple. Using the code above, we create the markup for our application.
After connecting the webix library, initialization occurs in the ui () method of the webix object.
As a parameter, it takes an object with a description of the structure of the application.
All names are speaking: rows is an array of strings, cols is an array of columns, view is a webix component.

Now, instead of comments, we need to insert the components of the webix we need, let's go top to bottom.

A toolbar is a collection of toolbar elements. We only need buttons:
{view:'toolbar', cols:[
	{view:'button', value:'Удалить', align:'right', width:100, click:function(){}},
	{view:'button', value:'Расшифровать выделенные', width:200, click:function(){}}
]}

Later we will describe their functions, but for now we will display all the necessary elements on the screen.
The most suitable for displaying messages (given the bundle with the databoom) I considered the datatable component
{view:"datatable", id:'datatableCblp', url: data, select:'row', multiselect:true, columns:[
	{id:'from', header:['От кого']},
	{id:'msg', header:['Сообщение']}
]}

In the select parameter, we indicate the type of selection (row / cell / column, in our case, row), we will need this to implement the ability to delete messages and decrypt selectively.
The multiselect parameter is responsible for the ability to select multiple lines (with cipher).
The columns array describes which columns will be in our table. For our simplest option, we dwell on the name of the sender and the text of the message.

I will not paint the form elements (fields and buttons), everything is extremely simple
{view:'form', elements:[
	{cols:[
		{ view:"textarea", label:"Сообщение", id:'Message'},
		{rows:[
			{ view:"text", label:"Псевдоним", id:'NickName'},
			{ view:"text", label:"Ключ", id:'CryptoKey'},
			{ view:"button", value:"Отправить", click:function(){}}
		]}
	]}
]}


We’ll finish the markup on the visual part, and now we will move on to the implementation of the technical side of the issue.

DataBoom


To start using the database, you need to register on the site , after which you will receive a letter with a link to the administrative panel of your database.

Here we need to do a few manipulations:

  • Allow all users to read data from the database
  • All


To implement the first paragraph, we set the conditions for the anonymus user group
{"GET":{"*":true},"PUT":{"*":true},"DELETE":{"*":true}}

Everything is possible, everything is true.

To manage the database from our application, you need to connect a script
https://databoom.space/databoom.js

After connecting it, create a database object
db = databoom(config.baseHost, config.baseName);


The parameters that are required from you at this stage are the “host” and the “base name”.
In a letter, databoom sent you a link to your database, mine looks like this:
Database URL: https://t014.databoom.space/api1/b014


The host is a domain, including "http (s)". And the name of the base is written at the end, we have it "b014".
After the database object is initialized, we can describe the function of sending a message to the server:
{ view:"button", value:"Отправить", click:function(){
	var newData = {};
	newData.from = $$('NickName').getValue()
	newData.msg = $$('Message').getValue()
	db.save(config.collection, newData);
}}


Webix objects can be accessed using $$, making a selector by id, which we specify the component description (this id has nothing to do with the element's DOM id).

db.save () saves data to the database. The first parameter we specify is the “collection”. Consider this the name of the table in the database, if you will. The admiration is the fact that it does not need to be created either in the databoom admin panel or from the script, it just is. Any. As a collection, you can specify an arbitrary (almost) line, the main thing is to remember it, we will still refer to it.

Well, the message was sent to the server, it's time to read it. To do this, we use the url parameter of the datatable component
data = webix.proxy("databoomtree", config.basePath);
{view:"datatable", id:'datatableCblp', url: data, select:'row', multiselect:true, columns:[
	{id:'from', header:['От кого']},
	{id:'msg', header:['Сообщение']}
]}

In the url parameter, we specify a webix proxy object, the argument to which is the path to the desired collection (I called it crypto)
https://t014.databoom.space/api1/b014/collections/crypto

And now we already receive messages stored on the server. Let's confuse the enemies a bit by introducing a bit of cryptography. You can use any key encryption algorithm, I used one of the simple ones.
The code
define([''], function(){
	var сaesar = function (text, key, decode) {
	    var textLetter, keyLetter, result = "", conv = decode ? -1 : 1;
	    key = key ? key : " ";
	    for (textLetter = keyLetter = 0; textLetter < text.length; textLetter++, keyLetter++) {
	        if (keyLetter >= key.length) keyLetter = 0;
	            result += String.fromCharCode( text.charCodeAt(textLetter) + conv * key.charCodeAt(keyLetter) );
	    }
	    return result
	}
	var crypt = {
		on: function(text, key){
			return сaesar(text, key);
		},
		off: function(text, key){
			return сaesar(text, key, true);
		}
	}
	return crypt;
});


We will encrypt, of course, before sending to the server (saving to the database). We’ll make some changes by adding a key input field:
{ view:"button", value:"Отправить", click:function(){
	var newData = {};
	newData.from = crypt.on($$('NickName').getValue(), $$('CryptoKey').getValue()); // crypt
	newData.msg = crypt.on($$('Message').getValue(), $$('CryptoKey').getValue());  // crypt
	db.save(config.collection, newData);
}}


Please note that the keys that we write to the database (from / msg) coincide with the id's of the columns of our datatable.

Understand and read


Since we know which encryption key our interlocutor uses (this is the idea), we can read the encrypted messages received from the server. Let us describe the function of the “decrypt selected” button:
{view:'button', value:'Расшифровать выделенные',width:200, click:function(){
	var sel = $$("datatableCblp").getSelectedId(); // Выделенная ячейка
	if(!Array.isArray(sel)){
		var row = $$("datatableCblp").getItem(sel.row); // Вычисляем выделенную строку
		row['msg'] = crypt.off(row.msg); // Раскриптовываем
		row['from'] = crypt.off(row.from); // Раскриптовываем
		$$("datatableCblp").updateItem(sel.row, row); // Заменяем данные в наших строках на расшифрованные
	}else{
                 // Аналогично для каждой выделенной строки
	}
}}


Conclusion


I hope you are convinced that creating something not the most grandiose is very simple.
Among other things, we just made it possible for different people to communicate through one messenger and not interfere with each other. Unless everyone decides that their 1234 key is the coolest.

Practice for you a lot and different (for beginners).

Materials




Acknowledgments


  • @databoom for the most convenient implementation of a bundle with webix (I had to complicate it in view of the intermediate processing of information before saving)
  • @Skaner for the tutorial regarding the publication of this kind of application via google drive

Also popular now: