using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Forms; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; using HyperCube.Models; using Console = HyperCube.Utils.AdvConsole; using System.Net; namespace HyperCube.Pages { public partial class DocEdit : ComponentBase { [Parameter] public int docID { get; set; } [Inject] public AppData AppData { get; set; } const string FOLDER_NAME = "articles_storage"; const long MAX_FILE_SIZE = 5120000; //bytes string transactionId; ArticleModel articleModelClone = new(); ArticleModel articleModel = new(); AccountModel currentAcc = new(); AccountModel initiatorAcc = new(); string status; string header; string storageFolderPath; MemoryStream memoryStream; Modal modal { get; set; } string fullName { get { return FOLDER_NAME + "/" + articleModel.FilenameReal; } } int editsCount; async Task Verify() { Console.WriteLine($"Verify starting"); try { VerifyContract verifyContract = SmartContract.Find("Verify", Blockchain.GetMain()) as VerifyContract; if (verifyContract != null) { Console.WriteLine($"VerifyContract found"); transactionId = await verifyContract.Run(articleModel); return transactionId; } else Console.WriteLine($"VerifyContract null"); } catch (Exception e) { Console.WriteLine(e.Message + "stack trace" + e.StackTrace); } return "Verify failed"; } protected override async Task OnInitializedAsync() { currentAcc = AppData.CurrentAccount; string path = AppDomain.CurrentDomain.BaseDirectory+@"wwwroot"; storageFolderPath = (Path.Combine(path, FOLDER_NAME)); Console.WriteLine("docedit OnInitializedAsync storageFolderPath2 " + storageFolderPath); if (docID > 0) { header = "Проверка материала"; MySQLConnector dbCon = MySQLConnector.Instance(); string stringSQL = $"SELECT articles.id, filename, article_name, authors, date_publish, annotation, keywords, action_type, rating " + $"FROM articles " + $"JOIN actions_history ON actions_history.article_id = articles.id " + $"WHERE articles.id={docID} " + $"ORDER BY actions_history.id DESC LiMIT 1"; articleModelClone = await dbCon.SQLSelectArticle(stringSQL); articleModel = (ArticleModel)articleModelClone.Clone(); string initiatorID = await articleModel.GetInitiatorUUID(); var accounts = await AppData.LoadAccounts(); if(accounts.ContainsKey(initiatorID)) initiatorAcc = accounts[initiatorID]; status = $"Article ID={docID} loaded, status: {articleModel.Status}, initiator: {initiatorAcc.Name}"; } else header = "Загрузка материала"; await InitializeAccount(); //int count = await articleModel.GetEditsCount(); //int countbyid = await articleModel.GetEditsCount(currentAcc.UUID); //header += $", uuid:{currentAcc.UUID}, name: {currentAcc.Name}, edits count:{count}, count by accid: {countbyid}"; } public async Task NewProjectSmopp(long articleId) { WebRequest wrGETURL; wrGETURL = WebRequest.Create("http://dev.prmsys.net/makeproject.php?pt=232&aid="+ articleId); var response = await wrGETURL.GetResponseAsync(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string rt = reader.ReadToEnd(); return rt; } private async Task HandleValidSubmit() { MySQLConnector dbCon = MySQLConnector.Instance(); long id = 0; string stringSQL; Console.WriteLine($"HandleValidSubmit, docID: {docID}"); if (docID > 0) { id = docID; stringSQL = $"UPDATE articles " + $"SET filename='{articleModel.Filename}', article_name='{articleModel.Name}', authors='{articleModel.Authors}', " + $"date_publish='{articleModel.PublishDate.ToString("yyyy-MM-dd")}', annotation='{articleModel.Annotation}', " + $"keywords='{articleModel.Keywords}', rating={articleModel.Rating} " + $"WHERE id={docID}"; await dbCon.SQLInsert(stringSQL); } else { stringSQL = $"INSERT INTO articles (filename, article_name, authors, date_publish, annotation, keywords) " + $"VALUES ('{articleModel.Filename}', '{articleModel.Name}', '{articleModel.Authors}', '{articleModel.PublishDate.ToString("yyyy-MM-dd")}'," + $"'{articleModel.Annotation}', '{articleModel.Keywords}')"; id = await dbCon.SQLInsert(stringSQL); NewProjectSmopp(id); } ///temp int action_type = docID > 0 ? 2 : 1; stringSQL = $"INSERT INTO actions_history (article_id, action_type, acc_id) " + $"VALUES ('{id}', '{action_type}', '{currentAcc.UUID}')"; await dbCon.SQLInsert(stringSQL); Dictionary propDict = Compare.SimpleCompare(articleModel, articleModelClone); foreach (KeyValuePair prop in propDict) { //Console.WriteLine($"property name: {prop.Key}, value: {prop.Value.GetValue(articleModel, null)}"); stringSQL = $"INSERT INTO articles_edit_log (article_id, acc_id, field_name, field_prevvalue, field_newvalue) " + $"VALUES ('{id}', '{currentAcc.UUID}', '{prop.Key}', '{prop.Value.GetValue(articleModelClone, null)}', '{prop.Value.GetValue(articleModel, null)}')"; await dbCon.SQLInsert(stringSQL); } dbCon.Close(); if (docID > 0) { status = propDict.Count > 0 ? "All changes saved, article has veryfied." : "Article verifyed without any changes."; transactionId = await Verify(); Console.WriteLine("transactionId found " + transactionId); ///tmp editsCount = await articleModel.GetEditsCount(currentAcc.UUID); modal.Open(); } else { string fullpath = Path.Combine(storageFolderPath, $"{id}_{articleModel.Filename}"); Directory.CreateDirectory(storageFolderPath); FileStream fs = new(fullpath, FileMode.Create, FileAccess.Write); memoryStream.Position = 0; await memoryStream.CopyToAsync(fs); Console.WriteLine($"User has saved new article data, {id}_{articleModel.Filename}, memory size:{memoryStream.Length}b, file size: {fs.Length}b"); memoryStream.Close(); fs.Close(); status = "New article data saved."; bool confirmed = await JsRuntime.InvokeAsync("confirm", "Хотите загрузить еще статью?"); if (confirmed) NavigationManager.NavigateTo("docedit", true); else NavigationManager.NavigateTo(""); } } private async Task HandleSelection(InputFileChangeEventArgs e) { IBrowserFile file = e.File; if (file != null) { Stream stream = file.OpenReadStream(MAX_FILE_SIZE); memoryStream = new(); await stream.CopyToAsync(memoryStream); status = $"Finished loading {memoryStream.Length} bytes from {file.Name}"; DocParse docParse = new DocParse(); articleModelClone = docParse.ReadPDF(memoryStream); articleModelClone.Filename = file.Name; articleModel = (ArticleModel)articleModelClone.Clone(); } } private async Task Cancel() { bool confirmed = await JsRuntime.InvokeAsync("confirm", "Вы уверены, что хотите отклонить статью?"); if (confirmed) { ///какая-то логика отмены... NavigationManager.NavigateTo(""); } } public async Task InitializeAccount() { //AppData.CurrentAccount = await GetCurrentAcc(); Console.WriteLine($"InitializeAccount in DocEdit: {AppData.CurrentAccount.Name}"); } //private async Task GetCurrentAcc() //{ // AccountModel account = new(); // var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); // var user = authState.User; // if (user.Identity.IsAuthenticated) // { // var currentUser = await UserManager.GetUserAsync(user); // account.UUID = currentUser.Id; // //account.Name = currentUser.UserName; // //account.Email = currentUser.Email; // var acc = AccountModel.Find(account.UUID); // if (acc != null) // account = acc; // ///tmp // //account.AccRole = Role.User; // return account; // } // return null; //} } }