From 01397ee3966ad68edb5789305ef845e49b5aef2d Mon Sep 17 00:00:00 2001 From: Anatoly Piskunov Date: Tue, 11 Jul 2023 22:46:40 +0400 Subject: [PATCH] Add settings to auto save passphrase on publish, add auto try to decode all encoded objects from same account on decode by new passphrase, completed the manual --- app.js | 131 ++++++++++++++++++++++++++++++++++++++++++++++++++--- ltmp_en.js | 15 +++++- ltmp_ru.js | 17 +++++-- 3 files changed, 152 insertions(+), 11 deletions(-) diff --git a/app.js b/app.js index 2357c10..3cefaf9 100644 --- a/app.js +++ b/app.js @@ -1019,6 +1019,8 @@ var default_settings={ sync_size:100, nsfw_warning:true, nsfw_hashtags:['nsfw','sex','porn'], + + save_passphrase_on_publish:false, }; var settings=default_settings; @@ -1147,6 +1149,8 @@ function save_settings(view){ settings.energy=parseInt(parseFloat(energy_str)*100); settings.silent_award=tab.find('input[name="silent_award"]').prop("checked"); + settings.save_passphrase_on_publish=tab.find('input[name="save_passphrase_on_publish"]').prop("checked"); + let settings_json=JSON.stringify(settings); localStorage.setItem(storage_prefix+'settings',settings_json); @@ -4012,12 +4016,14 @@ function publish(view){ } //check passphrase and try encode let passphrase=view.find('.encode-passphrase input[name="encode-passphrase"]').val(); + let passphrase_comment=view.find('.encode-passphrase input[name="encode-comment"]').val(); if(''!=passphrase){ try{ new_object['d']['nt']=new_object['t'];//new type new_object['d']=JSON.stringify(new_object); new_object['d']=viz.aes.simpleEncoder(new_object['d'],passphrase); new_object['t']='e';//encoded + new_object['c']=passphrase_comment;//comment new_object['p']=previous; } catch(e){ @@ -4035,6 +4041,13 @@ function publish(view){ viz.broadcast.custom(users[current_user].regular_key,[],[current_user],publish_protocol,object_json,function(err,result){ if(result){ console.log(result); + + if(settings.save_passphrase_on_publish){ + if(''!=passphrase){ + add_passphrase(current_user,passphrase); + } + } + view.find('.success').html(ltmp_arr.publish_success); view.find('input').val(''); @@ -5097,6 +5110,27 @@ function app_mouse(e){ } else{//not editor buttons if(!ignore){ + if($(target).hasClass('delete-all-passphrases-action')){ + e.preventDefault(); + if(!$(target).hasClass('disabled')){ + $(target).addClass('disabled'); + let view=$(target).closest('.view'); + let tab=view.find('.content-view[data-tab="main"]'); + tab.find('.submit-button-ring').addClass('show'); + tab.find('.error').html(''); + tab.find('.success').html(''); + let t=db.transaction(['passphrases'],'readwrite'); + let q=t.objectStore('passphrases'); + let req=q.clear(); + req.onsuccess=function(){ + view.find('.button').removeClass('disabled'); + view.find('.submit-button-ring').removeClass('show'); + view.find('.error').html(''); + view.find('.success').html(ltmp_arr.app_passphrases_deleted); + }; + } + return; + } if($(target).hasClass('passphrase-remove-action')){ e.preventDefault(); let passphrase_id=$(target).closest('.passphrase-item').data('passphrase-id'); @@ -6597,12 +6631,14 @@ function app_mouse(e){ } //check passphrase and try encode let passphrase=$('.article-settings .encode-passphrase input[name="encode-passphrase"]').val(); + let passphrase_comment=$('.article-settings .encode-passphrase input[name="encode-comment"]').val(); if(''!=passphrase){ try{ new_object['d']['nt']=new_object['t'];//new type new_object['d']=JSON.stringify(new_object); new_object['d']=viz.aes.simpleEncoder(new_object['d'],passphrase); new_object['t']='e';//encoded + new_object['c']=passphrase_comment;//comment new_object['p']=previous; } catch(e){ @@ -6619,7 +6655,19 @@ function app_mouse(e){ viz.broadcast.custom(users[current_user].regular_key,[],[current_user],publish_protocol,object_json,function(err,result){ if(result){ console.log(result); + + if(settings.save_passphrase_on_publish){ + if(''!=passphrase){ + add_passphrase(current_user,passphrase); + } + } + if(false!==edit){ + if(settings.save_passphrase_on_publish){ + if(''!=passphrase){ + add_passphrase(current_user,passphrase); + } + } setTimeout(function(){ update_user_last_event(current_user,function(result){ if(false!==result){ @@ -8429,7 +8477,6 @@ function parse_object(account,block,feed_load_flag,callback){ update_short_date(); } else{ - let link='viz://@'+account+'/'+block+'/'; set_date_view($('.object[data-link="'+link+'"] .date-view'),true); } } @@ -8567,7 +8614,6 @@ function get_replies(object_account,object_block,callback){ } function add_passphrase(account,passphrase){ - console.log('!!! add_passphrase',account,passphrase); let t=db.transaction(['passphrases'],'readwrite'); let q=t.objectStore('passphrases'); req=q.index('account').openCursor(IDBKeyRange.only(account),'next'); @@ -8576,14 +8622,12 @@ function add_passphrase(account,passphrase){ req.onsuccess=function(event){ let cur=event.target.result; if(cur){ - console.log('!!! add_passphrase check',cur.value); if(cur.value.passphrase==passphrase){ find=true; } cur.continue(); } else{ - console.log('!!! add_passphrase find',find); if(!find){ /* passphrases struct: @@ -8595,6 +8639,8 @@ function add_passphrase(account,passphrase){ if(trx_need_commit){ t.commit(); } + //try decode all encoded objects from this account with new passphrase + try_decode_all_objects(account,passphrase); } } }; @@ -8624,6 +8670,64 @@ function get_passphrases(account,callback){ }; } +function try_decode_all_objects(account,passphrase){ + let t=db.transaction(['objects'],'readwrite'); + let q=t.objectStore('objects'); + let req=q.index('account').openCursor(IDBKeyRange.only(account),'next'); + req.onsuccess=function(event){ + let cur=event.target.result; + if(cur){ + let result=cur.value; + if('e'==result.data.t){//encoded + decode_object(account,result.block,passphrase,function(success){ + if(success){ + let block=result.block; + console.log('try_decode_all_objects success',account,block); + get_user(account,false,function(err,object_user){ + if(!err){ + get_object(account,block,false,function(err,object_result){ + if(!err){ + let link='viz://@'+account+'/'+block+'/'; + let view=$('.view[data-level="'+level+'"]'); + if(-1==path.indexOf('viz://')){//look in services views + let path_parts=path.split('/'); + view=$('.view[data-path="'+path_parts[0]+'"]'); + } + let find_object=view.find('.objects>.object[data-account="'+account+'"][data-block="'+block+'"]'); + if(find_object.length>0){ + find_object=view.find('.object[data-link="'+link+'"]'); + } + if(find_object.length>0){ + let object_preview=false; + if(find_object.hasClass('type-text-preview')){ + object_preview=true; + } + let object_type='default'; + if(object_preview){ + object_type='preview'; + } + new_render=render_object(object_user,object_result,object_type); + find_object.before(new_render); + find_object.remove();//remove old view + if(object_preview){ + update_short_date(); + } + else{ + set_date_view($('.object[data-link="'+link+'"] .date-view'),true); + } + } + } + }); + } + }); + } + }); + } + cur.continue(); + } + }; +} + function decode_object(account,block,passphrase,callback){ if(typeof callback==='undefined'){ callback=function(){}; @@ -8651,6 +8755,9 @@ function decode_object(account,block,passphrase,callback){ if(false!==new_object_data){ new_object_data=JSON.parse(new_object_data); delete result.data.t; + if(typeof result.data.c !== 'undefined'){ + delete result.data.c;//remove comment + } if(typeof new_object_data.d !== 'undefined'){ result.data.d=new_object_data.d; result.data.d.decoded=1; @@ -10878,7 +10985,8 @@ function view_app_settings(view,path_parts,query,title){ tab.find('input[name="nsfw_hashtags"]').val(settings.nsfw_hashtags.join(', ')); tab.find('input[name="energy"]').val(settings.energy/100); - $('input[name="silent_award"]').prop("checked",settings.silent_award); + tab.find('input[name="silent_award"]').prop("checked",settings.silent_award); + tab.find('input[name="save_passphrase_on_publish"]').prop("checked",settings.save_passphrase_on_publish); } if('feed'==current_tab){ tab.find('.button').removeClass('disabled'); @@ -13153,7 +13261,11 @@ function render_object(user,object,type,preset_level){ if(user.account==current_user){ more_view=ltmp(ltmp_arr.more_column,{account:user.account,block:object.block}); } - + let comment=''; + if(typeof object.data.c !== 'undefined'){ + comment=object.data.c; + comment=ltmp(ltmp_arr.object_type_encoded_comment,{comment:comment}); + } render=ltmp(ltmp_arr.object_type_encoded,{ author:'@'+user.account, account:user.account, @@ -13171,6 +13283,7 @@ function render_object(user,object,type,preset_level){ icon_share:ltmp_global.icon_share, }), more:more_view, + comment:comment, }); return render; } @@ -13422,6 +13535,11 @@ function render_object(user,object,type,preset_level){ } else{ if('encoded'==object_type){ + let comment=''; + if(typeof object.data.c !== 'undefined'){ + comment=object.data.c; + comment=ltmp(ltmp_arr.object_type_encoded_comment,{comment:comment}); + } render=ltmp(ltmp_arr.object_type_encoded_preview,{ author:'@'+user.account, account:user.account, @@ -13432,6 +13550,7 @@ function render_object(user,object,type,preset_level){ events:(typeof object.events !== 'undefined')?object.events.join(','):'', previous:object.data.p, timestamp:object.data.timestamp, + comment:comment, }); return render; } diff --git a/ltmp_en.js b/ltmp_en.js index 58739f8..18cc583 100644 --- a/ltmp_en.js +++ b/ltmp_en.js @@ -119,12 +119,18 @@ var ltmp_en_arr = {

(regenerates 20% per day)
+
+

By create encrypted object:

+

+
(turned off by default)
+

Save


Reset all settings

+

Remove all saved passphrases

Reset database state

@@ -273,7 +279,7 @@ var ltmp_en_arr = { encoding_description: `Type the password that will be used to encrypt the object.
Any user will be able to decrypt the object if he knows the password.
If the password is not specified, the object will be available to everyone.`, - encoding_form: ``, + encoding_form: `
`, beneficiaries_list_caption: `Beneficiaries`, beneficiaries_list_description: `Specify the users who will receive some of the rewards.`, beneficiaries_list_add: `%%beneficiaries_item%% %%beneficiaries_add_item%%`, @@ -413,6 +419,8 @@ var ltmp_en_arr = {

The editor allows you to design a complete publication with a header, subheadings, links, images and quotes. In the settings you need to specify an annotation, a link to a thumbnail and optionally add tags from your profile.

You can also specify the beneficiaries in the advanced settings by specifying the accounts that will share the reward you receive and the percentages to distribute it.

Extended Publications has a separate viewer in the PC version and feels like a popular blogging platform.

+

When creating new notes or publications, there is a section "%%open_publish_addons%%", where you can set a password to encrypt the note, as well as a list of beneficiaries (who will share the reward from users with you). When encrypting, the AES-256-CBC algorithm is used, you can set a public comment to the published object. Anyone you give the password to (or who guesses it) will be able to view the object.

+

If the object is published in the blockchain, then it is impossible to delete it. But with the Voice Events extension, it became possible to hide or edit past objects. The list of possible actions you will see on the page of viewing the object in the drop-down menu expanded by the icon %%icon_more%%.

`}, uri: { title: 'VIZ links', html: ` @@ -658,6 +666,7 @@ var ltmp_en_arr = { app_settings_caption: 'Application Settings', app_settings_saved: 'Settings saved', app_settings_reset: 'Settings reset', + app_passphrases_deleted: 'All passphrases deleted', app_settings_main_tab: 'General', app_settings_feed_tab: 'News Feed', app_settings_theme_tab: 'Color Theme', @@ -813,6 +822,7 @@ var ltmp_en_arr = { {more}
+ {comment}
%%decode_form%%
{actions}
@@ -825,10 +835,11 @@ var ltmp_en_arr = { + {comment}
%%decode_form%%
-
{text}
`, + object_type_encoded_comment: `
{comment}
`, decode_form: `
%%icon_locked%% Object is encoded
If you know the passphrase you can decode it.
All keys will be stored to specific account.
Press on me.
diff --git a/ltmp_ru.js b/ltmp_ru.js index 9fbcf8e..cad5e42 100644 --- a/ltmp_ru.js +++ b/ltmp_ru.js @@ -119,12 +119,18 @@ var ltmp_ru_arr = {

(регенерируется 20% за сутки)
+
+

При создании шифрованного объекта:

+

+
(по умолчанию отключено)
+

Сохранить


Сбросить все настройки

+

Удалить все сохраненные кодовые фразы

Сбросить состояние базы данных

@@ -273,7 +279,7 @@ var ltmp_ru_arr = { encoding_description: `Укажите пароль, который будет использован для шифрования объекта.
Любой пользователь сможет расшифровать объект, если он знает пароль.
Если пароль не указан, объект будет доступен всем.`, - encoding_form: ``, + encoding_form: `
`, beneficiaries_list_caption: `Бенефициары`, beneficiaries_list_description: `Укажите пользователей, которые будут получать часть награждений.`, beneficiaries_list_add: `%%beneficiaries_item%% %%beneficiaries_add_item%%`, @@ -413,6 +419,8 @@ var ltmp_ru_arr = {

Редактор позволяет оформить полноценную публикацию с заголовком, подзагаловками, ссылками, изображениями и цитатами. В настройках необходимо указать аннотацию, ссылку на миниатюру и опционально добавить тэги из вашего профиля.

Также можно указать бенефициаров в дополнительных настройках, для этого нужно задать аккаунты, которые будут делить получаемую награду и проценты для ее распределения.

Расширенные публикации имеют отдельный просмотрщик в версии для ПК и напоминают популярные блог-платформы.

+

При создании новой заметки или публикации есть раздел «%%open_publish_addons%%», где вы можете задать пароль для шифрования заметки, а также список бенефициаров (кто разделит с вами награду от пользователей). При шифровании используется алгоритм AES-256-CBC, вы можете задать публичный комментарий к публикуемому объекту. Любой, кому вы передадите пароль (или кто угадает его) — получит доступ к просмотру объекта.

+

Если объект опубликован в блокчейне, то удалить его невозможно. Но с расширением Voice Events стало возможным скрывать или редактировать прошлые объекты. Список возможных действий вы увидите на странице просмотра объекта в выпадающем меню при нажатии на иконку с тремя точками %%icon_more%%.

`}, uri: { title: 'Ссылки viz', html: ` @@ -658,6 +666,7 @@ var ltmp_ru_arr = { app_settings_caption: 'Настройки приложения', app_settings_saved: 'Настройки сохранены', app_settings_reset: 'Настройки сброшены', + app_passphrases_deleted: 'Все кодовые фразы удалены', app_settings_main_tab: 'Общие', app_settings_feed_tab: 'Лента новостей', app_settings_theme_tab: 'Оформление', @@ -813,6 +822,7 @@ var ltmp_ru_arr = { {more}
+ {comment}
%%decode_form%%
{actions}
@@ -825,10 +835,11 @@ var ltmp_ru_arr = { -
%%decode_form%%
-
{text}
+ {comment} +
%%decode_form%%
`, + object_type_encoded_comment: `
{comment}
`, decode_form: `
%%icon_locked%% Объект зашифрован
Если вы знаете кодовую фразу вы можете расшифровать его.
Все ключи будут храниться к конкретному аккаунту.
Нажми на мне.