Desktop.razor.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. AppData AppData { get; set; }
  33. [Inject]
  34. public IJSRuntime JsRuntime { get; set; }
  35. const string STORAGE_FOLDER_NAME = "articles_storage";
  36. const long MAX_FILE_SIZE = 5120000; //bytes
  37. const string ACTIVE_BUTTON_CLASS = "btn_white tab-button active";
  38. const string ACTIVE_TAB_CLASS = "second-block__form visible";
  39. const string BUTTON_CLASS = "btn_white tab-button";
  40. const string TAB_CLASS = "second-block__form";
  41. string _uploadButtonClass = ACTIVE_BUTTON_CLASS;
  42. string _uploadTabClass = ACTIVE_TAB_CLASS;
  43. string _verifyButtonClass = BUTTON_CLASS;
  44. string _verifyTabClass = TAB_CLASS;
  45. string _otherButtonClass = BUTTON_CLASS;
  46. string _otherTabClass = TAB_CLASS;
  47. int _counter = 1;
  48. //string _event = "";
  49. string _status;
  50. string _articleDropdownOption = "";
  51. //string _storageFolderPath;
  52. MemoryStream _memoryStream;
  53. ModalInfo _modalInfo_error { get; set; }
  54. ModalLoading _modalLoading { get; set; }
  55. ArticleModel _articleClone;
  56. ArticleModel _article;
  57. ReportModel _report = new();
  58. UnitextDocument _document;
  59. AccountModel _currentAccount;
  60. protected override async Task OnInitializedAsync()
  61. {
  62. ///tmp
  63. await AppData.LoadArticles();
  64. _article = AppData.CurrentArticle ?? (new());
  65. _articleClone = AppData.CurrentArticleClone ?? (new());
  66. _currentAccount = (AppData.CurrentAccount != null) ? AppData.CurrentAccount : await GetCurrentAcc();
  67. Console.WriteLine($"Desktop OnInitializedAsync, CurrentAccount: {_currentAccount.Name}");
  68. }
  69. protected override void OnAfterRender(bool firstRender) => _counter = 1;
  70. void SwitchDesktopTab(int tabIndex)
  71. {
  72. switch(tabIndex)
  73. {
  74. case 0:
  75. _uploadButtonClass = ACTIVE_BUTTON_CLASS;
  76. _uploadTabClass = ACTIVE_TAB_CLASS;
  77. _verifyButtonClass = BUTTON_CLASS;
  78. _verifyTabClass = TAB_CLASS;
  79. _otherButtonClass = BUTTON_CLASS;
  80. _otherTabClass = TAB_CLASS;
  81. break;
  82. case 1:
  83. _uploadButtonClass = BUTTON_CLASS;
  84. _uploadTabClass = TAB_CLASS;
  85. _verifyButtonClass = ACTIVE_BUTTON_CLASS;
  86. _verifyTabClass = ACTIVE_TAB_CLASS;
  87. _otherButtonClass = BUTTON_CLASS;
  88. _otherTabClass = TAB_CLASS;
  89. break;
  90. case 2:
  91. _uploadButtonClass = BUTTON_CLASS;
  92. _uploadTabClass = TAB_CLASS;
  93. _verifyButtonClass = BUTTON_CLASS;
  94. _verifyTabClass = TAB_CLASS;
  95. _otherButtonClass = ACTIVE_BUTTON_CLASS;
  96. _otherTabClass = ACTIVE_TAB_CLASS;
  97. break;
  98. }
  99. }
  100. async Task WidgetMenuClick(string menuname, string elementid)
  101. {
  102. await JsRuntime.InvokeVoidAsync("WidgetMenuClick", menuname, elementid);
  103. _counter = 1;
  104. }
  105. async Task HandleUpload(InputFileChangeEventArgs e)
  106. {
  107. _modalLoading.Open();
  108. IBrowserFile file = e.File;
  109. if (file != null)
  110. {
  111. Stream stream = file.OpenReadStream(MAX_FILE_SIZE);
  112. _memoryStream = new();
  113. await stream.CopyToAsync(_memoryStream);
  114. _status = $"Finished loading {_memoryStream.Length} bytes from {file.Name}";
  115. Console.WriteLine(_status);
  116. /// calculating hash
  117. string hash = await CalculateHashSum(_memoryStream);
  118. Console.WriteLine($"Hash: {hash}");
  119. /// checking hash
  120. MySQLConnector dbCon = MySQLConnector.Instance();
  121. string stringSQL;
  122. stringSQL = $"SELECT COUNT(*) FROM articles WHERE file_hash='{hash}'";
  123. int count = await dbCon.SQLSelectCount(stringSQL);
  124. if (count < 1)
  125. {
  126. _report = new();
  127. _report.FileName = file.Name;
  128. _report.FileSize = _memoryStream.Length.ToString();
  129. _memoryStream.Position = 0;
  130. byte[] content = _memoryStream.ToArray();
  131. _document = UnitextService.CreateDocument(null, content, null);
  132. if (_document.ErrorMessage != null)
  133. {
  134. // скорее всего, этот формат не поддерживается на данный момент
  135. Console.WriteLine($"error, sorry: {_document.ErrorMessage}");
  136. _memoryStream.Close();
  137. stream.Close();
  138. _modalLoading.Close();
  139. _modalInfo_error.Open("Не удается прочитать документ, формат не поддерживается или файл поврежден.");
  140. return;
  141. }
  142. // восстанавливаем имя исходного файла, извлечённого из ресурсов
  143. _document.SourceFileName = file.Name;
  144. for (int i = file.Name.Length - 7; i > 0; i--)
  145. {
  146. if (file.Name[i] == '.')
  147. {
  148. _document.SourceFileName = file.Name.Substring(i + 1);
  149. break;
  150. }
  151. }
  152. //// записываем результат в XML
  153. //using (FileStream fs = new(doc.SourceFileName + ".xml", FileMode.Create, FileAccess.Write))
  154. //{
  155. // XmlWriterSettings xmlParams = new();
  156. // xmlParams.Encoding = Encoding.UTF8;
  157. // xmlParams.Indent = true;
  158. // xmlParams.IndentChars = " ";
  159. // using (XmlWriter xml = XmlWriter.Create(fs, xmlParams))
  160. // {
  161. // xml.WriteStartDocument();
  162. // doc.GetXml(xml);
  163. // xml.WriteEndDocument();
  164. // }
  165. //}
  166. //Console.WriteLine("XML write done");
  167. // получаем плоский текст
  168. string plainText = _document.GetPlaintextString(null);
  169. if (plainText == null)
  170. plainText = "Текст не выделен";
  171. /// todo обработка, если статус != новый
  172. _articleClone = DocParse.GetBaseProperties(plainText);
  173. _articleClone.Filename = file.Name;
  174. _articleClone.HashSum = hash;
  175. _article = (ArticleModel)_articleClone.Clone();
  176. ///tmp
  177. AppData.CurrentArticle = _article;
  178. Console.WriteLine($"Initializing SDK Pullenti ver {Pullenti.Sdk.Version} ({Pullenti.Sdk.VersionDate})... ");
  179. Pullenti.Sdk.InitializeAll();
  180. //Console.WriteLine($"OK (by ... ms), version {Pullenti.Ner.ProcessorService.Version}");
  181. List<string> npt_tokens = new();
  182. // запускаем обработку на пустом процессоре (без анализаторов NER)
  183. Pullenti.Ner.AnalysisResult are = Pullenti.Ner.ProcessorService.EmptyProcessor.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  184. //System.Console.Write("Noun groups: ");
  185. // перебираем токены
  186. for (Pullenti.Ner.Token t = are.FirstToken; t != null; t = t.Next)
  187. {
  188. // выделяем именную группу с текущего токена
  189. Pullenti.Ner.Core.NounPhraseToken npt = Pullenti.Ner.Core.NounPhraseHelper.TryParse(t, Pullenti.Ner.Core.NounPhraseParseAttr.No, 0, null);
  190. // не получилось
  191. if (npt == null)
  192. continue;
  193. // получилось, выводим в нормализованном виде
  194. //System.Console.Write($"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ");
  195. //_report.NounGroups += $"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ";
  196. _article.NounGroups += $"[{npt.GetSourceText()}=>{npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false)}] ";
  197. npt_tokens.Add(npt.GetNormalCaseText(null, Pullenti.Morph.MorphNumber.Singular, Pullenti.Morph.MorphGender.Undefined, false));
  198. // указатель на последний токен именной группы
  199. t = npt.EndToken;
  200. }
  201. using (Pullenti.Ner.Processor proc = Pullenti.Ner.ProcessorService.CreateProcessor())
  202. {
  203. // анализируем текст
  204. Pullenti.Ner.AnalysisResult ar = proc.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  205. // результирующие сущности
  206. //Console.WriteLine("\r\n==========================================\r\nEntities: ");
  207. foreach (Pullenti.Ner.Referent en in ar.Entities)
  208. {
  209. //Console.WriteLine($"{en.TypeName}: {en}");
  210. //_report.Entities += $"{en.TypeName}: {en}\r\n";
  211. _article.Entities += $"{en.TypeName}: {en}\r\n";
  212. foreach (Pullenti.Ner.Slot s in en.Slots)
  213. {
  214. //Console.WriteLine($" {s.TypeName}: {s.Value}");
  215. //_report.Entities += $" {s.TypeName}: {s.Value}<br>";
  216. _article.Entities += $" {s.TypeName}: {s.Value}<br>";
  217. }
  218. }
  219. // пример выделения именных групп
  220. //Console.WriteLine("\r\n==========================================\r\nNoun groups: ");
  221. for (Pullenti.Ner.Token t = ar.FirstToken; t != null; t = t.Next)
  222. {
  223. // токены с сущностями игнорируем
  224. if (t.GetReferent() != null)
  225. continue;
  226. // пробуем создать именную группу
  227. Pullenti.Ner.Core.NounPhraseToken npt = Pullenti.Ner.Core.NounPhraseHelper.TryParse(t, Pullenti.Ner.Core.NounPhraseParseAttr.AdjectiveCanBeLast, 0, null);
  228. // не получилось
  229. if (npt == null)
  230. continue;
  231. //Console.WriteLine(npt.ToString());
  232. //_report.EntitiesNounGroups += $"{npt}<br>";
  233. _article.Morph += $"{npt}<br>";
  234. // указатель перемещаем на последний токен группы
  235. t = npt.EndToken;
  236. }
  237. }
  238. using (Pullenti.Ner.Processor proc = Pullenti.Ner.ProcessorService.CreateSpecificProcessor(Pullenti.Ner.Keyword.KeywordAnalyzer.ANALYZER_NAME))
  239. {
  240. Pullenti.Ner.AnalysisResult ar = proc.Process(new Pullenti.Ner.SourceOfAnalysis(plainText), null, null);
  241. //Console.WriteLine("\r\n==========================================\r\nKeywords1: ");
  242. foreach (Pullenti.Ner.Referent en in ar.Entities)
  243. {
  244. if (en is Pullenti.Ner.Keyword.KeywordReferent)
  245. //Console.WriteLine(en.ToString());
  246. //_report.Keywords1 += $"{en}<br>";
  247. _article.Keywords1 += $"{en}<br>";
  248. }
  249. //Console.WriteLine("\r\n==========================================\r\nKeywords2: ");
  250. for (Pullenti.Ner.Token t = ar.FirstToken; t != null; t = t.Next)
  251. {
  252. if (t is Pullenti.Ner.ReferentToken)
  253. {
  254. Pullenti.Ner.Keyword.KeywordReferent kw = t.GetReferent() as Pullenti.Ner.Keyword.KeywordReferent;
  255. if (kw == null)
  256. continue;
  257. string kwstr = Pullenti.Ner.Core.MiscHelper.GetTextValueOfMetaToken(t as Pullenti.Ner.ReferentToken, Pullenti.Ner.Core.GetTextAttr.FirstNounGroupToNominativeSingle | Pullenti.Ner.Core.GetTextAttr.KeepRegister);
  258. //Console.WriteLine($"{kwstr} = {kw}");
  259. //_report.Keywords2 += $"{kwstr} = {kw}<br>";
  260. _article.Keywords2 += $"{kwstr} = {kw}<br>";
  261. }
  262. }
  263. }
  264. int res = (from x in npt_tokens
  265. select x).Distinct().Count();
  266. Console.WriteLine($"npt_tokens.count={npt_tokens.Count}, distinct.Count={res}");
  267. Console.WriteLine("Analysis is over!");
  268. var query = from x in npt_tokens
  269. group x by x into g
  270. let count1 = g.Count()
  271. orderby count1 descending
  272. select new { Name = g.Key, Count = count1 };
  273. foreach (var result in query)
  274. {
  275. _report.NounGroupsSorted += $"{result.Name}, Count: {result.Count}<br>";
  276. //Console.WriteLine($"Name: {result.Name}, Count: {result.Count}");
  277. }
  278. //AppData.Report = _report;
  279. }
  280. else
  281. {
  282. _status = $"File duplicate founded, hash: {hash}.";
  283. Console.WriteLine(_status);
  284. _article = new();
  285. _articleClone = new();
  286. _document = null;
  287. _memoryStream.Close();
  288. _modalInfo_error.Open("Загрузка не удалась, такой документ уже есть в системе.");
  289. }
  290. file = null;
  291. stream.Close();
  292. }
  293. _modalLoading.Close();
  294. }
  295. void NewDocument()
  296. {
  297. _article = new();
  298. _articleClone = new();
  299. _document = null;
  300. _memoryStream = null;
  301. _status = "Blank document created";
  302. }
  303. async Task SaveDocument_OnClick(ArticleStatus articleNewStatus)
  304. {
  305. Console.WriteLine($"SaveDocument_OnClick. DocID: {_article.ID}, Status: {_article.Status}");
  306. if (_article.Name == null || _article.Name.Length == 0)
  307. {
  308. Console.WriteLine($"SaveDocument, empty article name. DocID: {_article.ID}, Status: {_article.Status}, filename: {_article.Filename}");
  309. _modalInfo_error.Open($"Для сохранения документа необходимо ввести название.");
  310. return;
  311. }
  312. if (_article.Status == ArticleStatus.New && _memoryStream == null)
  313. {
  314. Console.WriteLine($"SaveDocument, empty source file. DocID: {_article.ID}, Status: {_article.Status}, filename: {_article.Filename}");
  315. _modalInfo_error.Open($"Для сохранения документа необходимо прикрепить исходный файл.");
  316. return;
  317. }
  318. if (_article.Status == ArticleStatus.New && articleNewStatus == ArticleStatus.Verifying
  319. || _article.Status == ArticleStatus.AwatingVerify && articleNewStatus == ArticleStatus.Saved
  320. || _article.Status == ArticleStatus.Verifying && articleNewStatus == ArticleStatus.Saved
  321. || _article.Status == ArticleStatus.Verified && articleNewStatus == ArticleStatus.Saved
  322. || _article.Status == ArticleStatus.Verified && articleNewStatus == ArticleStatus.Verifying)
  323. {
  324. Console.WriteLine($"SaveDocument, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  325. _modalInfo_error.Open($"Текущий статус документа не позволяет сохранение.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  326. }
  327. else
  328. {
  329. /// all is fine, continue
  330. MySQLConnector dbCon = MySQLConnector.Instance();
  331. long id;
  332. string stringSQL;
  333. if (_article.Status == ArticleStatus.New)
  334. {
  335. _modalLoading.Open();
  336. stringSQL = $"INSERT INTO articles (filename, article_name, authors, date_publish, annotation, keywords, file_hash, " +
  337. $"doc_noungroups, doc_entities, doc_morph, doc_keywords1, doc_keywords2) " +
  338. $"VALUES ('{_article.Filename}', '{_article.Name}', '{_article.Authors}', '{_article.PublishDate:yyyy-MM-dd}'," +
  339. $"'{_article.Annotation}', '{_article.Keywords}', '{_article.HashSum}'," +
  340. $"'{_article.NounGroups}', '{_article.Entities}', '{_article.Morph}', '{_article.Keywords1}', '{_article.Keywords2}' )";
  341. id = await dbCon.SQLInsert(stringSQL);
  342. _article.ID = (int)id;
  343. ///todo добавлять новый док в массив AppData.Articles
  344. stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
  345. $"VALUES ('{id}', '{(int)articleNewStatus}', '{_currentAccount.UUID}')";
  346. await dbCon.SQLInsert(stringSQL);
  347. await SaveFiles((int)id);
  348. _article.Status = ArticleStatus.Saved;
  349. _articleClone = (ArticleModel)_article.Clone();
  350. /// reloading articles
  351. await AppData.LoadArticles();
  352. _counter = 1;
  353. _modalLoading.Close();
  354. _modalInfo_error.Open("Документ успешно создан.");
  355. }
  356. else
  357. {
  358. await UpdateDocument(articleNewStatus);
  359. //await SaveFiles(_article.ID);
  360. }
  361. }
  362. }
  363. async Task LoadDocument(int docid)
  364. {
  365. ///todo загружать из массива AppData.Articles
  366. Console.WriteLine($"LoadDocument, docid: {docid}.");
  367. _modalLoading.Open();
  368. if (docid > 0)
  369. {
  370. MySQLConnector dbCon = MySQLConnector.Instance();
  371. string stringSQL = $"SELECT articles.id, filename, article_name, authors, date_publish, annotation, keywords, action_type, rating, file_hash, " +
  372. $"doc_noungroups, doc_entities, doc_morph, doc_keywords1, doc_keywords2 " +
  373. $"FROM articles " +
  374. $"JOIN actions_history ON actions_history.article_id = articles.id " +
  375. $"WHERE articles.id={docid} " +
  376. $"ORDER BY actions_history.id DESC LiMIT 1";
  377. AppData.CurrentArticleClone = await dbCon.SQLSelectArticle(stringSQL);
  378. AppData.CurrentArticle = (ArticleModel)AppData.CurrentArticleClone.Clone();
  379. //string initiator = await _article.GetInitiatorUUID();
  380. //initiatorAcc = AccountModel.Find(initiator);
  381. //_status = $"Article ID={DocID} loaded, status: {_article.Status}, initiator: {initiatorAcc.Name}";
  382. _status = $"Article ID={docid} loaded, status: {AppData.CurrentArticle.Status}.";
  383. _article = AppData.CurrentArticle ?? (new());
  384. _articleClone = AppData.CurrentArticleClone ?? (new());
  385. }
  386. _modalLoading.Close();
  387. }
  388. async Task SendToVerify_OnClick()
  389. {
  390. if (_article.Status == ArticleStatus.New || _article.Status == ArticleStatus.Saved)
  391. {
  392. Console.WriteLine($"SendToVerify, DocID: {_article.ID}, Status: {_article.Status}");
  393. _modalLoading.Open();
  394. /// form validation
  395. List<string> errorFields = ValidateForm<ArticleModel>(_article);
  396. if (errorFields.Count > 0)
  397. {
  398. _modalLoading.Close();
  399. string invalid_fields = string.Join(", ", errorFields);
  400. _modalInfo_error.Open($"Не заполнены поля: {invalid_fields}");
  401. Console.WriteLine($"SendToVerify. Required fields: '{invalid_fields}' is not filled.");
  402. return;
  403. }
  404. await UpdateDocument(ArticleStatus.AwatingVerify);
  405. _modalLoading.Close();
  406. }
  407. else
  408. {
  409. Console.WriteLine($"SendToVerify, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  410. _modalInfo_error.Open($"Документ не может быть отправлен на верификацию.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  411. }
  412. }
  413. async Task Verify_OnClick()
  414. {
  415. if (_article.Status == ArticleStatus.AwatingVerify || _article.Status == ArticleStatus.Verifying)
  416. {
  417. Console.WriteLine($"Verify, DocID: {_article.ID}, Status: {_article.Status}");
  418. _modalLoading.Open();
  419. /// form validation
  420. List<string> errorFields = ValidateForm<ArticleModel>(_article);
  421. if (errorFields.Count > 0)
  422. {
  423. _modalLoading.Close();
  424. string invalid_fields = string.Join(", ", errorFields);
  425. _modalInfo_error.Open($"Не заполнены поля: {invalid_fields}");
  426. Console.WriteLine($"Verify. Required fields: '{invalid_fields}' is not filled.");
  427. return;
  428. }
  429. await UpdateDocument(ArticleStatus.Verified);
  430. _modalLoading.Close();
  431. }
  432. else
  433. {
  434. Console.WriteLine($"Verify, wrong status. DocID: {_article.ID}, Status: {_article.Status}");
  435. _modalInfo_error.Open($"Документ не может быть верифицирован.<br>DocID: {_article.ID}, Status: {GetDisplayName(_article.Status)}");
  436. }
  437. }
  438. async Task UpdateDocument(ArticleStatus articleStatus)
  439. {
  440. _modalLoading.Open();
  441. MySQLConnector dbCon = MySQLConnector.Instance();
  442. string stringSQL;
  443. string rating = (_article.Rating == null) ? "NULL" : _article.Rating.ToString();
  444. stringSQL = $"UPDATE articles " +
  445. $"SET filename='{_article.Filename}', article_name='{_article.Name}', authors='{_article.Authors}', " +
  446. $"date_publish='{_article.PublishDate:yyyy-MM-dd}', annotation='{_article.Annotation}', " +
  447. $"keywords='{_article.Keywords}', rating={rating}, file_hash='{_article.HashSum}' " +
  448. $"WHERE id={_article.ID}";
  449. await dbCon.SQLInsert(stringSQL);
  450. ///todo обновлять док в массиве AppData.Articles
  451. stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " +
  452. $"VALUES ('{_article.ID}', '{(int)articleStatus}', '{_currentAccount.UUID}')";
  453. await dbCon.SQLInsert(stringSQL);
  454. ///если нужно фиксировать изменение статуса в поле (табл articles_edit_log)
  455. //_article.Status = articleStatus;
  456. Dictionary<string, PropertyInfo> propDict = Compare.SimpleCompare<ArticleModel>(_article, _articleClone);
  457. foreach (KeyValuePair<string, PropertyInfo> prop in propDict)
  458. {
  459. //Console.WriteLine($"property name: {prop.Key}, value: {prop.Value.GetValue(articleModel, null)}");
  460. stringSQL = $"INSERT INTO articles_edit_log (article_id, acc_id, field_name, field_prevvalue, field_newvalue) " +
  461. $"VALUES ('{_article.ID}', '{_currentAccount.UUID}', '{prop.Key}', '{prop.Value.GetValue(_articleClone, null)}', '{prop.Value.GetValue(_article, null)}')";
  462. await dbCon.SQLInsert(stringSQL);
  463. }
  464. _article.Status = articleStatus;
  465. _articleClone = (ArticleModel)_article.Clone();
  466. /// reloading articles
  467. await AppData.LoadArticles();
  468. _modalLoading.Close();
  469. string message = propDict.Count > 0 ? "Все изменения успешно сохранены." : "Изменений не найдено.";
  470. _modalInfo_error.Open(message);
  471. }
  472. async Task DocSelect_OnChange(ChangeEventArgs e)
  473. {
  474. int docid = int.Parse(e.Value.ToString());
  475. Console.WriteLine($"DocSelect_OnChange. docid: {docid}");
  476. await LoadDocument(docid);
  477. }
  478. async Task SaveFiles(int docid)
  479. {
  480. if (_document != null )
  481. {
  482. /// получаем html, сохраняем файлы
  483. GetHtmlParam htmlParams = new();
  484. htmlParams.OutHtmlAndBodyTags = true;
  485. string html = _document.GetHtmlString(htmlParams);
  486. string fullpath;
  487. string htmldirectorypath;
  488. string docdirectorypath;
  489. #if DEBUG
  490. htmldirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  491. docdirectorypath = Path.Combine(Environment.CurrentDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  492. #else
  493. htmldirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "html");
  494. docdirectorypath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", STORAGE_FOLDER_NAME, "source");
  495. #endif
  496. ///html
  497. fullpath = Path.Combine(htmldirectorypath, $"{docid}_{_document.SourceFileName}.html");
  498. Console.WriteLine($"Saving file [{fullpath}]");
  499. Directory.CreateDirectory(htmldirectorypath);
  500. File.WriteAllBytes(fullpath, Encoding.UTF8.GetBytes(html));
  501. ///original files
  502. fullpath = Path.Combine(docdirectorypath, $"{docid}_{_article.Filename}");
  503. Console.WriteLine($"Saving file [{fullpath}]");
  504. Directory.CreateDirectory(docdirectorypath);
  505. FileStream fs = new(fullpath, FileMode.Create, FileAccess.Write);
  506. _memoryStream.Position = 0;
  507. await _memoryStream.CopyToAsync(fs);
  508. _status = $"User has saved new article data: [{docid}_{_article.Filename}], memory size:{_memoryStream.Length}b, file size: {fs.Length}b";
  509. Console.WriteLine(_status);
  510. _memoryStream.Close();
  511. fs.Close();
  512. _document = null;
  513. }
  514. }
  515. async Task<string> CalculateHashSum(MemoryStream ms)
  516. {
  517. MD5CryptoServiceProvider md5Provider = new();
  518. ms.Position = 0;
  519. byte[] hash = await md5Provider.ComputeHashAsync(ms);
  520. return Convert.ToBase64String(hash);
  521. }
  522. List<string> ValidateForm<T>(T obj)
  523. {
  524. var props = typeof(T).GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(RequiredAttribute)));
  525. List<string> result = new();
  526. foreach (var prop in props)
  527. {
  528. var val = prop.GetValue(obj, null);
  529. if (val == null || val?.ToString().Length == 0)
  530. result.Add(prop.Name);
  531. //Console.WriteLine($"Required field '{prop.Name}' is not filled.");
  532. }
  533. return result;
  534. }
  535. static string GetDisplayName(Enum enumValue)
  536. {
  537. return enumValue.GetType()
  538. .GetMember(enumValue.ToString())
  539. .First()
  540. .GetCustomAttribute<DisplayAttribute>()
  541. .GetName();
  542. }
  543. async Task<AccountModel> GetCurrentAcc()
  544. {
  545. Console.WriteLine($"Desktop GetCurrentAcc");
  546. if (_currentAccount == null)
  547. {
  548. var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
  549. var user = authState.User;
  550. if (user.Identity.IsAuthenticated)
  551. {
  552. ///tmp
  553. Dictionary<string, AccountModel> accounts = await MySQLConnector.Instance().SQLSelectASPUsers();
  554. var currentUser = await UserManager.GetUserAsync(user);
  555. if (accounts.ContainsKey(currentUser.Id))
  556. _currentAccount = accounts[currentUser.Id];
  557. }
  558. }
  559. return _currentAccount;
  560. }
  561. }
  562. }