Desktop.razor.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. using HyperCube.Models;
  2. using Microsoft.AspNetCore.Components;
  3. using Microsoft.AspNetCore.Components.Authorization;
  4. using Microsoft.AspNetCore.Components.Forms;
  5. using Microsoft.AspNetCore.Identity;
  6. using Microsoft.JSInterop;
  7. using Pullenti.Unitext;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel.DataAnnotations;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Xml;
  18. using Console = HyperCube.Utils.AdvConsole;
  19. namespace HyperCube.Pages
  20. {
  21. public partial class Desktop : ComponentBase
  22. {
  23. //[Parameter]
  24. //public int DocID { get; set; }
  25. [Inject]
  26. NavigationManager NavigationManager { get; set; }
  27. [Inject]
  28. AuthenticationStateProvider AuthenticationStateProvider { get; set; }
  29. [Inject]
  30. UserManager<IdentityUser> UserManager { get; set; }
  31. [Inject]
  32. RoleManager<IdentityRole> RoleManager { get; set; }
  33. [Inject]
  34. AppData AppData { get; set; }
  35. [Inject]
  36. public IJSRuntime JsRuntime { get; set; }
  37. const string STORAGE_FOLDER_NAME = "articles_storage";
  38. const long MAX_FILE_SIZE = 5120000; //bytes
  39. const string ACTIVE_BUTTON_CLASS = "btn_white tab-button active";
  40. const string ACTIVE_TAB_CLASS = "second-block__form visible";
  41. const string BUTTON_CLASS = "btn_white tab-button";
  42. const string TAB_CLASS = "second-block__form";
  43. string _uploadButtonClass = ACTIVE_BUTTON_CLASS;
  44. string _uploadTabClass = ACTIVE_TAB_CLASS;
  45. string _verifyButtonClass = BUTTON_CLASS;
  46. string _verifyTabClass = TAB_CLASS;
  47. string _otherButtonClass = BUTTON_CLASS;
  48. string _otherTabClass = TAB_CLASS;
  49. //int _counter = 1;
  50. //string _event = "";
  51. string _status;
  52. string _articleDropdownOption = "";
  53. //string _storageFolderPath;
  54. MemoryStream _memoryStream;
  55. ModalInfo _modalInfo { get; set; }
  56. ModalLoading _modalLoading { get; set; }
  57. ArticleModel _articleClone;
  58. ArticleModel _article;
  59. Dictionary<int, ArticleModel> _articles = new();
  60. ReportModel _report = new();
  61. UnitextDocument _document;
  62. AccountModel _currentAccount;
  63. VerificationPoint _verificationPoint = new();
  64. bool loadButtonDisable { get; set; }
  65. bool verifyButtonDisable { get; set; }
  66. bool rejectReasonDisable { get; set; } = true;
  67. protected override async Task OnInitializedAsync()
  68. {
  69. _currentAccount = (AppData.CurrentAccount != null) ? AppData.CurrentAccount : await GetCurrentAcc();
  70. _currentAccount.LoadRoles();
  71. Console.WriteLine($"Desktop OnInitializedAsync, CurrentAccount: {_currentAccount.Name}");
  72. ///tmp
  73. await LoadArticles();
  74. _article = AppData.CurrentArticle ?? (new());
  75. _articleClone = AppData.CurrentArticleClone ?? (new());
  76. }
  77. protected override void OnAfterRender(bool firstRender)
  78. {
  79. if (_verificationPoint.RulesViolation || _verificationPoint.NonExpert || _verificationPoint.AdditionalVerificationRequired || _verificationPoint.Rejected)
  80. {
  81. if (rejectReasonDisable)
  82. {
  83. rejectReasonDisable = false;
  84. StateHasChanged();
  85. }
  86. }
  87. if (!_verificationPoint.RulesViolation && !_verificationPoint.NonExpert && !_verificationPoint.AdditionalVerificationRequired && !_verificationPoint.Rejected)
  88. {
  89. if (!rejectReasonDisable)
  90. {
  91. rejectReasonDisable = true;
  92. StateHasChanged();
  93. }
  94. }
  95. }
  96. void SwitchDesktopTab(int tabIndex)
  97. {
  98. switch(tabIndex)
  99. {
  100. case 0:
  101. _uploadButtonClass = ACTIVE_BUTTON_CLASS;
  102. _uploadTabClass = ACTIVE_TAB_CLASS;
  103. _verifyButtonClass = BUTTON_CLASS;
  104. _verifyTabClass = TAB_CLASS;
  105. _otherButtonClass = BUTTON_CLASS;
  106. _otherTabClass = TAB_CLASS;
  107. break;
  108. case 1:
  109. _uploadButtonClass = BUTTON_CLASS;
  110. _uploadTabClass = TAB_CLASS;
  111. _verifyButtonClass = ACTIVE_BUTTON_CLASS;
  112. _verifyTabClass = ACTIVE_TAB_CLASS;
  113. _otherButtonClass = BUTTON_CLASS;
  114. _otherTabClass = TAB_CLASS;
  115. break;
  116. case 2:
  117. _uploadButtonClass = BUTTON_CLASS;
  118. _uploadTabClass = TAB_CLASS;
  119. _verifyButtonClass = BUTTON_CLASS;
  120. _verifyTabClass = TAB_CLASS;
  121. _otherButtonClass = ACTIVE_BUTTON_CLASS;
  122. _otherTabClass = ACTIVE_TAB_CLASS;
  123. break;
  124. }
  125. }
  126. async Task WidgetMenuClick(string menuname, string elementid)
  127. {
  128. await JsRuntime.InvokeVoidAsync("WidgetMenuClick", menuname, elementid);
  129. //_counter = 1;
  130. }
  131. async Task HandleUpload(InputFileChangeEventArgs e)
  132. {
  133. _modalLoading.Open();
  134. IBrowserFile file = e.File;
  135. if (file != null)
  136. {
  137. Stream stream = file.OpenReadStream(MAX_FILE_SIZE);
  138. _memoryStream = new();
  139. await stream.CopyToAsync(_memoryStream);
  140. _status = $"Finished loading {_memoryStream.Length} bytes from {file.Name}";
  141. Console.WriteLine(_status);
  142. /// calculating hash
  143. string hash = await CalculateHashSum(_memoryStream);
  144. Console.WriteLine($"Hash: {hash}");
  145. /// checking hash
  146. MySQLConnector dbCon = MySQLConnector.Instance();
  147. string stringSQL;
  148. stringSQL = $"SELECT COUNT(*) FROM articles WHERE file_hash='{hash}'";
  149. int count = await dbCon.SQLSelectCount(stringSQL);
  150. if (count < 1)
  151. {
  152. _report = new();
  153. _report.FileName = file.Name;
  154. _report.FileSize = _memoryStream.Length.ToString();
  155. _memoryStream.Position = 0;
  156. byte[] content = _memoryStream.ToArray();
  157. _document = UnitextService.CreateDocument(null, content, null);
  158. if (_document.ErrorMessage != null)
  159. {
  160. // скорее всего, этот формат не поддерживается на данный момент
  161. Console.WriteLine($"error, sorry: {_document.ErrorMessage}");
  162. _memoryStream.Close();
  163. stream.Close();
  164. _modalLoading.Close();
  165. _modalInfo.Open("Не удается прочитать документ, формат не поддерживается или файл поврежден.");
  166. return;
  167. }
  168. // восстанавливаем имя исходного файла, извлечённого из ресурсов
  169. _document.SourceFileName = file.Name;
  170. for (int i = file.Name.Length - 7; i > 0; i--)
  171. {
  172. if (file.Name[i] == '.')
  173. {
  174. _document.SourceFileName = file.Name.Substring(i + 1);
  175. break;
  176. }
  177. }
  178. //// записываем результат в XML
  179. //using (FileStream fs = new(doc.SourceFileName + ".xml", FileMode.Create, FileAccess.Write))
  180. //{
  181. // XmlWriterSettings xmlParams = new();
  182. // xmlParams.Encoding = Encoding.UTF8;
  183. // xmlParams.Indent = true;
  184. // xmlParams.IndentChars = " ";
  185. // using (XmlWriter xml = XmlWriter.Create(fs, xmlParams))
  186. // {
  187. // xml.WriteStartDocument();
  188. // doc.GetXml(xml);
  189. // xml.WriteEndDocument();
  190. // }
  191. //}
  192. //Console.WriteLine("XML write done");
  193. // получаем плоский текст
  194. string plainText = _document.GetPlaintextString(null);
  195. if (plainText == null)
  196. plainText = "Текст не выделен";
  197. /// todo обработка, если статус != новый
  198. _articleClone = DocParse.GetBaseProperties(plainText);
  199. _articleClone.Filename = file.Name;
  200. _articleClone.HashSum = hash;
  201. _articleClone.CharCount = plainText.Length;
  202. _article = (ArticleModel)_articleClone.Clone();
  203. ///tmp
  204. AppData.CurrentArticle = _article;
  205. Console.WriteLine($"Initializing SDK Pullenti ver {Pullenti.Sdk.Version} ({Pullenti.Sdk.VersionDate})... ");
  206. Pullenti.Sdk.InitializeAll();
  207. //Console.WriteLine($"OK (by ... ms), version {Pullenti.Ner.ProcessorService.Version}");
  208. List<string> npt_tokens = new();
  209. // запускаем обработку на пустом процессоре (без анализаторов NER)
  210. Pullenti.Ner.AnalysisResult are = Pullenti.Ner.ProcessorService.EmptyProcessor.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  211. //System.Console.Write("Noun groups: ");
  212. // перебираем токены
  213. for (Pullenti.Ner.Token t = are.FirstToken; t != null; t = t.Next)
  214. {
  215. // выделяем именную группу с текущего токена
  216. Pullenti.Ner.Core.NounPhraseToken npt = Pullenti.Ner.Core.NounPhraseHelper.TryParse(t, Pullenti.Ner.Core.NounPhraseParseAttr.No, 0, null);
  217. // не получилось
  218. if (npt == null)
  219. continue;
  220. // получилось, выводим в нормализованном виде
  221. //System.Console.Write($"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ");
  222. //_report.NounGroups += $"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ";
  223. _article.NounGroups += $"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ";
  224. npt_tokens.Add(npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false));
  225. // указатель на последний токен именной группы
  226. t = npt.EndToken;
  227. }
  228. using (Pullenti.Ner.Processor proc = Pullenti.Ner.ProcessorService.CreateProcessor())
  229. {
  230. // анализируем текст
  231. Pullenti.Ner.AnalysisResult ar = proc.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  232. // результирующие сущности
  233. //Console.WriteLine("\r\n==========================================\r\nEntities: ");
  234. foreach (Pullenti.Ner.Referent en in ar.Entities)
  235. {
  236. //Console.WriteLine($"{en.TypeName}: {en}");
  237. //_report.Entities += $"{en.TypeName}: {en}\r\n";
  238. _article.Entities += $"{en.TypeName}: {en}\r\n";
  239. foreach (Pullenti.Ner.Slot s in en.Slots)
  240. {
  241. //Console.WriteLine($" {s.TypeName}: {s.Value}");
  242. //_report.Entities += $" {s.TypeName}: {s.Value}<br>";
  243. _article.Entities += $" {s.TypeName}: {s.Value}<br>";
  244. }
  245. }
  246. // пример выделения именных групп
  247. //Console.WriteLine("\r\n==========================================\r\nNoun groups: ");
  248. for (Pullenti.Ner.Token t = ar.FirstToken; t != null; t = t.Next)
  249. {
  250. // токены с сущностями игнорируем
  251. if (t.GetReferent() != null)
  252. continue;
  253. // пробуем создать именную группу
  254. Pullenti.Ner.Core.NounPhraseToken npt = Pullenti.Ner.Core.NounPhraseHelper.TryParse(t, Pullenti.Ner.Core.NounPhraseParseAttr.AdjectiveCanBeLast, 0, null);
  255. // не получилось
  256. if (npt == null)
  257. continue;
  258. //Console.WriteLine(npt.ToString());
  259. //_report.EntitiesNounGroups += $"{npt}<br>";
  260. _article.Morph += $"{npt}<br>";
  261. // указатель перемещаем на последний токен группы
  262. t = npt.EndToken;
  263. }
  264. }
  265. using (Pullenti.Ner.Processor proc = Pullenti.Ner.ProcessorService.CreateSpecificProcessor(Pullenti.Ner.Keyword.KeywordAnalyzer.ANALYZER_NAME))
  266. {
  267. Pullenti.Ner.AnalysisResult ar = proc.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  268. //Console.WriteLine("\r\n==========================================\r\nKeywords1: ");
  269. foreach (Pullenti.Ner.Referent en in ar.Entities)
  270. {
  271. if (en is Pullenti.Ner.Keyword.KeywordReferent)
  272. //Console.WriteLine(en.ToString());
  273. //_report.Keywords1 += $"{en}<br>";
  274. _article.Keywords1 += $"{en}<br>";
  275. }
  276. //Console.WriteLine("\r\n==========================================\r\nKeywords2: ");
  277. for (Pullenti.Ner.Token t = ar.FirstToken; t != null; t = t.Next)
  278. {
  279. if (t is Pullenti.Ner.ReferentToken)
  280. {
  281. Pullenti.Ner.Keyword.KeywordReferent kw = t.GetReferent() as Pullenti.Ner.Keyword.KeywordReferent;
  282. if (kw == null)
  283. continue;
  284. string kwstr = Pullenti.Ner.Core.MiscHelper.GetTextValueOfMetaToken(t as Pullenti.Ner.ReferentToken, Pullenti.Ner.Core.GetTextAttr.FirstNounGroupToNominativeSingle | Pullenti.Ner.Core.GetTextAttr.KeepRegister);
  285. //Console.WriteLine($"{kwstr} = {kw}");
  286. //_report.Keywords2 += $"{kwstr} = {kw}<br>";
  287. _article.Keywords2 += $"{kwstr} = {kw}<br>";
  288. }
  289. }
  290. }
  291. int res = (from x in npt_tokens
  292. select x).Distinct().Count();
  293. Console.WriteLine($"npt_tokens.count={npt_tokens.Count}, distinct.Count={res}");
  294. Console.WriteLine("Analysis is over!");
  295. var query = from x in npt_tokens
  296. group x by x into g
  297. let count1 = g.Count()
  298. orderby count1 descending
  299. select new { Name = g.Key, Count = count1 };
  300. foreach (var result in query)
  301. {
  302. _report.NounGroupsSorted += $"{result.Name}, Count: {result.Count}<br>";
  303. //Console.WriteLine($"Name: {result.Name}, Count: {result.Count}");
  304. }
  305. //AppData.Report = _report;
  306. }
  307. else
  308. {
  309. _status = $"File duplicate founded, hash: {hash}.";
  310. Console.WriteLine(_status);
  311. _article = new();
  312. _articleClone = new();
  313. _document = null;
  314. _memoryStream.Close();
  315. _modalInfo.Open("Загрузка не удалась, такой документ уже есть в системе.");
  316. }
  317. file = null;
  318. stream.Close();
  319. }
  320. _modalLoading.Close();
  321. }
  322. async Task NewDocument()
  323. {
  324. _article = new();
  325. _articleClone = new();
  326. _document = null;
  327. _memoryStream = null;
  328. _status = "Blank document created";
  329. await JsRuntime.InvokeVoidAsync("WidgetMenuClick", ".block__dropbox", "desktop_menu");
  330. //_counter = 1;
  331. }
  332. async Task SaveDocument_OnClick(ArticleStatus articleNewStatus)
  333. {
  334. Console.WriteLine($"SaveDocument_OnClick. DocID: {_article.ID}, Status: {_article.Status}");
  335. if (_article.Name == null || _article.Name.Length == 0)
  336. {
  337. Console.WriteLine($"SaveDocument, empty article name. DocID: {_article.ID}, Status: {_article.Status}, filename: {_article.Filename}");
  338. _modalInfo.Open( $"Для сохранения документа необходимо ввести название.");
  339. return;
  340. }
  341. if (_article.Status == ArticleStatus.New && _memoryStream == null)
  342. {
  343. Console.WriteLine($"SaveDocument, empty source file. DocID: {_article.ID}, Status: {_article.Status}, filename: {_article.Filename}");
  344. _modalInfo.Open($"Для сохранения документа необходимо прикрепить исходный файл.");
  345. return;
  346. }
  347. if (_article.Status == ArticleStatus.New && articleNewStatus == ArticleStatus.Verifying
  348. || _article.Status == ArticleStatus.AwatingVerify && articleNewStatus == ArticleStatus.Saved
  349. || _article.Status == ArticleStatus.Verifying && articleNewStatus == ArticleStatus.Saved
  350. || _article.Status == ArticleStatus.Verified && articleNewStatus == ArticleStatus.Saved
  351. || _article.Status == ArticleStatus.Verified && articleNewStatus == ArticleStatus.Verifying)
  352. {
  353. Console.WriteLine($"SaveDocument, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  354. _modalInfo.Open($"Текущий статус документа не позволяет сохранение.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  355. }
  356. else
  357. {
  358. /// all is fine, continue
  359. MySQLConnector dbCon = MySQLConnector.Instance();
  360. long id;
  361. string stringSQL;
  362. if (_article.Status == ArticleStatus.New)
  363. {
  364. _modalLoading.Open();
  365. stringSQL = $"INSERT INTO articles (filename, article_name, authors, date_publish, annotation, keywords, file_hash, " +
  366. $"doc_noungroups, doc_entities, doc_morph, doc_keywords1, doc_keywords2, char_count) " +
  367. $"VALUES ('{_article.Filename}', '{_article.Name}', '{_article.Authors}', '{_article.PublishDate:yyyy-MM-dd}'," +
  368. $"'{_article.Annotation}', '{_article.Keywords}', '{_article.HashSum}'," +
  369. $"'{_article.NounGroups}', '{_article.Entities}', '{_article.Morph}', '{_article.Keywords1}', '{_article.Keywords2}', '{_article.CharCount}' )";
  370. id = await dbCon.SQLInsert(stringSQL);
  371. _article.ID = (int)id;
  372. ///todo добавлять новый док в массив AppData.Articles
  373. stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
  374. $"VALUES ('{id}', '{(int)articleNewStatus}', '{_currentAccount.UUID}')";
  375. await dbCon.SQLInsert(stringSQL);
  376. await SaveFiles((int)id);
  377. _article.Status = ArticleStatus.Saved;
  378. _articleClone = (ArticleModel)_article.Clone();
  379. /// reloading articles
  380. await LoadArticles();
  381. //_counter = 1;
  382. _modalLoading.Close();
  383. _modalInfo.Open("Документ успешно создан.");
  384. }
  385. else
  386. {
  387. await UpdateDocument(articleNewStatus);
  388. //await SaveFiles(_article.ID);
  389. if (_article.Status == ArticleStatus.AwatingVerify || _article.Status == ArticleStatus.Verifying)
  390. await _article.SaveLastVerificationPoint(_verificationPoint, _currentAccount.UUID);
  391. }
  392. }
  393. }
  394. async Task LoadDocument(int docid)
  395. {
  396. ///todo загружать из массива AppData.Articles
  397. Console.WriteLine($"LoadDocument, docid: {docid}.");
  398. _modalLoading.Open();
  399. if (docid > 0)
  400. {
  401. MySQLConnector dbCon = MySQLConnector.Instance();
  402. AppData.CurrentArticleClone = await dbCon.SQLSelectArticle(docid);
  403. await AppData.CurrentArticleClone.GetVerificationHistory(_currentAccount.UUID);
  404. if (AppData.CurrentArticleClone.VerificationHistory.Count > 0)
  405. _verificationPoint = AppData.CurrentArticleClone.VerificationHistory.Values.Last();
  406. else
  407. _verificationPoint = new();
  408. AppData.CurrentArticle = (ArticleModel)AppData.CurrentArticleClone.Clone();
  409. //string initiator = await _article.GetInitiatorUUID();
  410. //initiatorAcc = AccountModel.Find(initiator);
  411. //_status = $"Article ID={DocID} loaded, status: {_article.Status}, initiator: {initiatorAcc.Name}";
  412. _status = $"Article ID={docid} loaded, status: {AppData.CurrentArticle.Status}.";
  413. _article = AppData.CurrentArticle ?? (new());
  414. _articleClone = AppData.CurrentArticleClone ?? (new());
  415. }
  416. _modalLoading.Close();
  417. }
  418. async Task SendToVerify_OnClick()
  419. {
  420. if (_article.Status == ArticleStatus.New || _article.Status == ArticleStatus.Saved)
  421. {
  422. Console.WriteLine($"SendToVerify, DocID: {_article.ID}, Status: {_article.Status}");
  423. _modalLoading.Open();
  424. /// form validation
  425. List<string> errorFields = ValidateForm<ArticleModel>(_article);
  426. if (errorFields.Count > 0)
  427. {
  428. _modalLoading.Close();
  429. string invalid_fields = string.Join(", ", errorFields);
  430. _modalInfo.Open($"Не заполнены поля: {invalid_fields}");
  431. Console.WriteLine($"SendToVerify. Required fields: '{invalid_fields}' is not filled.");
  432. return;
  433. }
  434. await UpdateDocument(ArticleStatus.AwatingVerify);
  435. _modalLoading.Close();
  436. }
  437. else
  438. {
  439. Console.WriteLine($"SendToVerify, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  440. _modalInfo.Open($"Документ не может быть отправлен на верификацию.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  441. }
  442. }
  443. async Task Verify_OnClick()
  444. {
  445. //if (DocID > 0)
  446. //{
  447. // status = propDict.Count > 0 ? "All changes saved, article has veryfied." : "Article verifyed without any changes.";
  448. // transactionId = await Verify();
  449. // Console.WriteLine("transactionId found " + transactionId);
  450. // ///tmp
  451. // editsCount = await article.GetEditsCount(currentAcc.UUID);
  452. // modalInfo_transac.Open();
  453. //}
  454. if (_article.Status == ArticleStatus.AwatingVerify || _article.Status == ArticleStatus.Verifying)
  455. {
  456. Console.WriteLine($"Verify, DocID: {_article.ID}, Status: {_article.Status}");
  457. _modalLoading.Open();
  458. /// form validation
  459. List<string> errorFields = ValidateForm<ArticleModel>(_article);
  460. if (errorFields.Count > 0)
  461. {
  462. _modalLoading.Close();
  463. string invalid_fields = string.Join(", ", errorFields);
  464. _modalInfo.Open($"Не заполнены поля: {invalid_fields}");
  465. Console.WriteLine($"Verify. Required fields: '{invalid_fields}' is not filled.");
  466. return;
  467. }
  468. if (!rejectReasonDisable)
  469. {
  470. if (_verificationPoint.RejectReason == null || _verificationPoint.RejectReason.Length == 0)
  471. {
  472. _modalLoading.Close();
  473. _modalInfo.Open($"Не заполнена причина отклонения.");
  474. Console.WriteLine($"Verify. Reject reason is not filled.");
  475. return;
  476. }
  477. }
  478. var bcMain = await _currentAccount.GetSelectedBlockChain();
  479. var transactionId = await bcMain.Verify(_currentAccount, _article);
  480. Console.WriteLine("transactionId found " + transactionId);
  481. await UpdateDocument(ArticleStatus.Verified);
  482. _modalLoading.Close();
  483. }
  484. else
  485. {
  486. Console.WriteLine($"Verify, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  487. _modalInfo.Open($"Документ не может быть верифицирован.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  488. }
  489. }
  490. async Task UpdateDocument(ArticleStatus articleStatus)
  491. {
  492. _modalLoading.Open();
  493. MySQLConnector dbCon = MySQLConnector.Instance();
  494. string stringSQL;
  495. string rating = (_article.Rating == null) ? "NULL" : _article.Rating.ToString();
  496. stringSQL = $"UPDATE articles " +
  497. $"SET filename='{_article.Filename}', article_name='{_article.Name}', authors='{_article.Authors}', " +
  498. $"date_publish='{_article.PublishDate:yyyy-MM-dd}', annotation='{_article.Annotation}', " +
  499. $"keywords='{_article.Keywords}', rating={rating}, file_hash='{_article.HashSum}' " +
  500. $"WHERE id={_article.ID}";
  501. await dbCon.SQLInsert(stringSQL);
  502. ///todo обновлять док в массиве AppData.Articles
  503. stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
  504. $"VALUES ('{_article.ID}', '{(int)articleStatus}', '{_currentAccount.UUID}')";
  505. await dbCon.SQLInsert(stringSQL);
  506. ///если нужно фиксировать изменение статуса в поле (табл articles_edit_log)
  507. //_article.Status = articleStatus;
  508. Dictionary<string, PropertyInfo> propDict = Compare.SimpleCompare<ArticleModel>(_article, _articleClone);
  509. foreach (KeyValuePair<string, PropertyInfo> prop in propDict)
  510. {
  511. //Console.WriteLine($"property name: {prop.Key}, value: {prop.Value.GetValue(articleModel, null)}");
  512. stringSQL = $"INSERT INTO articles_edit_log (article_id, acc_id, field_name, field_prevvalue, field_newvalue) " +
  513. $"VALUES ('{_article.ID}', '{_currentAccount.UUID}', '{prop.Key}', '{prop.Value.GetValue(_articleClone, null)}', '{prop.Value.GetValue(_article, null)}')";
  514. await dbCon.SQLInsert(stringSQL);
  515. }
  516. _article.Status = articleStatus;
  517. _articleClone = (ArticleModel)_article.Clone();
  518. /// reloading articles
  519. await LoadArticles();
  520. _modalLoading.Close();
  521. string message = propDict.Count > 0 ? "Все изменения успешно сохранены." : "Изменения не были найдены при сохранении.";
  522. if (_article.Status == ArticleStatus.Verified)
  523. message = "Документ успешно валидирован";
  524. _modalInfo.Open(message);
  525. }
  526. async Task DocSelect_OnChange(ChangeEventArgs e)
  527. {
  528. int docid = int.Parse(e.Value.ToString());
  529. Console.WriteLine($"DocSelect_OnChange. docid: {docid}");
  530. await LoadDocument(docid);
  531. }
  532. async Task SaveFiles(int docid)
  533. {
  534. if (_document != null )
  535. {
  536. string fullpath;
  537. string htmldirectorypath;
  538. string docdirectorypath;
  539. #if DEBUG
  540. htmldirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  541. docdirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  542. #else
  543. htmldirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  544. docdirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  545. #endif
  546. try
  547. {
  548. /// получаем html, сохраняем файлы
  549. GetHtmlParam htmlParams = new();
  550. htmlParams.OutHtmlAndBodyTags = true;
  551. string html = _document.GetHtmlString(htmlParams);
  552. ///saving html
  553. fullpath = Path.Combine(htmldirectorypath, $"{docid}_{_document.SourceFileName}.html");
  554. Console.WriteLine($"Saving file [{fullpath}]");
  555. Directory.CreateDirectory(htmldirectorypath);
  556. File.WriteAllBytes(fullpath, Encoding.UTF8.GetBytes(html));
  557. }
  558. catch (Exception ex)
  559. {
  560. Console.WriteLine($"{ex.GetType()}\r\n{ex.Message}\r\n{ex.StackTrace}");
  561. }
  562. ///saving original files
  563. fullpath = Path.Combine(docdirectorypath, $"{docid}_{_article.Filename}");
  564. Console.WriteLine($"Saving file [{fullpath}]");
  565. Directory.CreateDirectory(docdirectorypath);
  566. FileStream fs = new(fullpath, FileMode.Create, FileAccess.Write);
  567. _memoryStream.Position = 0;
  568. await _memoryStream.CopyToAsync(fs);
  569. _status = $"User has saved new article data: [{docid}_{_article.Filename}], memory size:{_memoryStream.Length}b, file size: {fs.Length}b";
  570. Console.WriteLine(_status);
  571. _memoryStream.Close();
  572. fs.Close();
  573. _document = null;
  574. }
  575. }
  576. async Task GetArticleFile(string option)
  577. {
  578. string fullpath;
  579. string htmldirectorypath;
  580. string docdirectorypath;
  581. #if DEBUG
  582. htmldirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  583. docdirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  584. #else
  585. htmldirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  586. docdirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  587. #endif
  588. if (option == "source")
  589. {
  590. fullpath = Path.Combine(docdirectorypath, $"{_article.ID}_{_article.Filename}");
  591. if (fullpath.Length > 0 && File.Exists(fullpath))
  592. NavigationManager.NavigateTo($"{STORAGE_FOLDER_NAME}/source/{_article.ID}_{_article.Filename}", true);
  593. else
  594. {
  595. Console.WriteLine($"GetArticleFile, file not exists: [{fullpath}].");
  596. _modalInfo.Open("Файл документа не найден.");
  597. }
  598. }
  599. else if (option == "html")
  600. {
  601. fullpath = Path.Combine(docdirectorypath, $"{_article.ID}_{_article.Filename}.html");
  602. if (fullpath.Length > 0 && File.Exists(fullpath))
  603. NavigationManager.NavigateTo($"{STORAGE_FOLDER_NAME}/html/{_article.ID}_{_article.Filename}.html", true);
  604. else
  605. {
  606. Console.WriteLine($"GetArticleFile, file not exists: [{fullpath}].");
  607. _modalInfo.Open("Файл документа не найден.");
  608. }
  609. }
  610. else
  611. {
  612. Console.WriteLine($"GetArticleFile, unknown method option: [{option}].");
  613. //return;
  614. }
  615. }
  616. async Task LoadArticles()
  617. {
  618. /// reloading articles
  619. await AppData.LoadArticles();
  620. _articles = new();
  621. ///updating local articles and UI on role claims
  622. if (_currentAccount.Roles.Contains(Role.Admin))
  623. {
  624. loadButtonDisable = false;
  625. verifyButtonDisable = false;
  626. int counter = 1;
  627. foreach (ArticleModel article in AppData.Articles.Values) { _articles.Add(counter++, article); }
  628. }
  629. else if (_currentAccount.Roles.Contains(Role.Expert))
  630. {
  631. loadButtonDisable = true;
  632. verifyButtonDisable = false;
  633. int counter = 1;
  634. foreach (ArticleModel article in AppData.Articles.Values)
  635. {
  636. if (article.Status == ArticleStatus.AwatingVerify || article.Status == ArticleStatus.Verifying || article.Status == ArticleStatus.Verified)
  637. _articles.Add(counter++, article);
  638. }
  639. SwitchDesktopTab(1);
  640. }
  641. else if (_currentAccount.Roles.Contains(Role.Miner))
  642. {
  643. loadButtonDisable = false;
  644. verifyButtonDisable = true;
  645. int counter = 1;
  646. foreach (ArticleModel article in AppData.Articles.Values)
  647. {
  648. if (article.Status == ArticleStatus.New || article.Status == ArticleStatus.Saved || article.Status == ArticleStatus.Verified)
  649. _articles.Add(counter++, article);
  650. }
  651. }
  652. else
  653. {
  654. loadButtonDisable = true;
  655. verifyButtonDisable = true;
  656. int counter = 1;
  657. foreach (ArticleModel article in AppData.Articles.Values) { _articles.Add(counter++, article); }
  658. SwitchDesktopTab(2);
  659. }
  660. }
  661. async Task<string> CalculateHashSum(MemoryStream ms)
  662. {
  663. MD5CryptoServiceProvider md5Provider = new();
  664. ms.Position = 0;
  665. byte[] hash = await md5Provider.ComputeHashAsync(ms);
  666. return Convert.ToBase64String(hash);
  667. }
  668. List<string> ValidateForm<T>(T obj)
  669. {
  670. var props = typeof(T).GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(RequiredAttribute)));
  671. List<string> result = new();
  672. foreach (var prop in props)
  673. {
  674. var val = prop.GetValue(obj, null);
  675. if (val == null || val?.ToString().Length == 0)
  676. result.Add(prop.Name);
  677. //Console.WriteLine($"Required field '{prop.Name}' is not filled.");
  678. }
  679. return result;
  680. }
  681. static string GetDisplayName(Enum enumValue)
  682. {
  683. return enumValue.GetType()
  684. .GetMember(enumValue.ToString())
  685. .First()
  686. .GetCustomAttribute<DisplayAttribute>()
  687. .GetName();
  688. }
  689. async Task<AccountModel> GetCurrentAcc()
  690. {
  691. Console.WriteLine($"Desktop GetCurrentAcc");
  692. if (_currentAccount == null)
  693. {
  694. var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
  695. var user = authState.User;
  696. if (user.Identity.IsAuthenticated)
  697. {
  698. var currentUser = await UserManager.GetUserAsync(user);
  699. var acc = AccountModel.Find(currentUser.Id);
  700. if (acc != null)
  701. {
  702. _currentAccount = AccountModel.Loaded[currentUser.Id];
  703. }
  704. else
  705. {
  706. Dictionary<string, AccountModel> accounts = await MySQLConnector.Instance().SQLSelectASPUsers();
  707. if (accounts.ContainsKey(currentUser.Id))
  708. _currentAccount = accounts[currentUser.Id];
  709. }
  710. /// asp roles
  711. //var role1 = new IdentityRole { Name = "admin" };
  712. //var result = await RoleManager.CreateAsync(role1);
  713. //Console.WriteLine($"RoleManager create result: {result}");
  714. //result = await UserManager.AddToRoleAsync(currentUser, role1.Name);
  715. //Console.WriteLine($"RoleManager add role result: {result}");
  716. }
  717. }
  718. return _currentAccount;
  719. }
  720. }
  721. }