diff --git a/.drone.yml b/.drone.yml index c912393..ba4962c 100644 --- a/.drone.yml +++ b/.drone.yml @@ -22,6 +22,7 @@ steps: commands: - cd /usr/share/$DRONE_REPO_NAME - dotnet build + - name: recreate dist folder commands: - rm -rf /usr/share/$DRONE_REPO_NAME/dist diff --git a/.gitignore b/.gitignore index da6f134..dbb0a96 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ obj bin -dist +dist \ No newline at end of file diff --git a/.idea/NeDvachAPI.iml b/.idea/NeDvachAPI.iml new file mode 100644 index 0000000..0c8867d --- /dev/null +++ b/.idea/NeDvachAPI.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..4d319ec --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..d47bf8d --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + 1668991859805 + + + + + + \ No newline at end of file diff --git a/.vs/NeDvachAPI/FileContentIndex/ab543bd0-617c-45ed-ab03-ad1ed2f70181.vsidx b/.vs/NeDvachAPI/FileContentIndex/ab543bd0-617c-45ed-ab03-ad1ed2f70181.vsidx deleted file mode 100644 index c68e021..0000000 Binary files a/.vs/NeDvachAPI/FileContentIndex/ab543bd0-617c-45ed-ab03-ad1ed2f70181.vsidx and /dev/null differ diff --git a/.vs/NeDvachAPI/FileContentIndex/bd028927-4a6a-4c4d-814d-056a1b6cdb4f.vsidx b/.vs/NeDvachAPI/FileContentIndex/bd028927-4a6a-4c4d-814d-056a1b6cdb4f.vsidx new file mode 100644 index 0000000..80e44c8 Binary files /dev/null and b/.vs/NeDvachAPI/FileContentIndex/bd028927-4a6a-4c4d-814d-056a1b6cdb4f.vsidx differ diff --git a/.vs/NeDvachAPI/config/applicationhost.config b/.vs/NeDvachAPI/config/applicationhost.config new file mode 100644 index 0000000..cdd2df8 --- /dev/null +++ b/.vs/NeDvachAPI/config/applicationhost.config @@ -0,0 +1,1026 @@ + + + + + + + +
+
+
+
+
+
+
+
+ + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+
+ + +
+
+
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.vs/NeDvachAPI/v17/.wsuo b/.vs/NeDvachAPI/v17/.wsuo new file mode 100644 index 0000000..530c526 Binary files /dev/null and b/.vs/NeDvachAPI/v17/.wsuo differ diff --git a/.vs/VSWorkspaceState.json b/.vs/VSWorkspaceState.json index 24b1642..554e027 100644 --- a/.vs/VSWorkspaceState.json +++ b/.vs/VSWorkspaceState.json @@ -1,8 +1,7 @@ { "ExpandedNodes": [ - "", - "\\Controllers" + "" ], - "SelectedNode": "\\Program.cs", + "SelectedNode": "\\appsettings.json", "PreviewInSolutionExplorer": false } \ No newline at end of file diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite index 4e511b8..00842c6 100644 Binary files a/.vs/slnx.sqlite and b/.vs/slnx.sqlite differ diff --git a/Controllers/DeletePost.cs b/APIControllers/DeletePost.cs similarity index 89% rename from Controllers/DeletePost.cs rename to APIControllers/DeletePost.cs index c7a7e01..ccd0cf9 100644 --- a/Controllers/DeletePost.cs +++ b/APIControllers/DeletePost.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc; -using System.Data; -using System.Text.Json; +using NeDvachAPI.DBControllers; namespace NeDvachAPI.Controllers { diff --git a/APIControllers/GetPosts.cs b/APIControllers/GetPosts.cs new file mode 100644 index 0000000..294f2c7 --- /dev/null +++ b/APIControllers/GetPosts.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Mvc; +using NeDvachAPI.BufferControllers; +using System.Text.Json; +using System.Web.Http; +using HttpGetAttribute = Microsoft.AspNetCore.Mvc.HttpGetAttribute; +using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute; + +namespace NeDvachAPI.Controllers +{ + [ApiController] + [Route("[controller]")] + public class ListController : ControllerBase + { + [HttpGet(Name = "GetPosts")] + public string Get([FromUri] string board, int thread) + { + string postsJson = JsonSerializer.Serialize(APIThreadBuffer.GetThread(thread)); + return postsJson ; + } + } +} diff --git a/APIControllers/PictureUpload.cs b/APIControllers/PictureUpload.cs new file mode 100644 index 0000000..dae9f77 --- /dev/null +++ b/APIControllers/PictureUpload.cs @@ -0,0 +1,50 @@ +using Microsoft.AspNetCore.Mvc; +using NeDvachAPI.DBControllers; + + +namespace NeDvachAPI.Controllers +{ + [ApiController] + [Route("[controller]")] + public class UploadPic : ControllerBase + { + + + [HttpPost(Name = "UploadPicture")] + public async Task ReceivePost([FromForm] IFormFile PostPicture) + { + + string receivedFileName = PostPicture.FileName; + string fName = Path.GetFileNameWithoutExtension(receivedFileName); + string fExtention = Path.GetExtension(receivedFileName); + string previevFileName = fName + 's' + fExtention; + + Console.WriteLine("Расширение файла: " + fExtention); + + if (ImageController.CheckExtention(fExtention)) //file type check + { + ///Local Buffer File Part + string filePath; + string previevPath; + filePath = Directory.GetCurrentDirectory() + "\\Buffer\\" + receivedFileName; + previevPath = Directory.GetCurrentDirectory() + "\\Buffer\\" + previevFileName; + //creating original file buffer + Stream picBuffer = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); + PostPicture.CopyTo(picBuffer); + picBuffer.Close(); + //resizing + ImageController.ResizeImage(filePath, previevPath, 300, 400); + ///MinIo part + await MinIOchat.PictureUpload(previevPath, receivedFileName, "thread-pics-small"); //upload thumbnail + JsonResult picAdress = new(await MinIOchat.PictureUpload(filePath, receivedFileName, "thread-pics")); //upload fullsize + Console.WriteLine("Загружен файл:" + "http://static.vdk2ch.ru:15555/thread-pics/" + receivedFileName); + return picAdress; + } + + else return new JsonResult("Неверный тип файла"); + } + + + } + +} diff --git a/APIControllers/PostPost.cs b/APIControllers/PostPost.cs new file mode 100644 index 0000000..4aa664b --- /dev/null +++ b/APIControllers/PostPost.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Mvc; +using NeDvachAPI.BufferControllers; +using NeDvachAPI.DBControllers; +using NeDvachAPI.Models; + +namespace NeDvachAPI.Controllers +{ + [ApiController] + [Route("[controller]")] + public class PostToController : ControllerBase + { + [HttpPost(Name = "PostPosts")] + public JsonResult ReceivePost([FromBody] Post ReceivedPost) + { + string ipAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString(); + ReceivedPost.Ip = ipAddress; + + if(ReceivedPost.Text.Length == 0) + { + return new JsonResult("Вы отправили пустое сообщение!"); + } + try + { + DBchat.SendPost(ReceivedPost); + APIThreadBuffer.RefreshThread(ReceivedPost.Thread_Id); + return new JsonResult("Сообщение успешно добавлено."); + } + catch + { + return new JsonResult("Произошла ошибка постинга"); + } + } + } +} diff --git a/APIControllers/ShowThreads.cs b/APIControllers/ShowThreads.cs new file mode 100644 index 0000000..6bd4783 --- /dev/null +++ b/APIControllers/ShowThreads.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Mvc; +using NeDvachAPI.BufferControllers; +using System.Text.Json; +using System.Web.Http; +using HttpGetAttribute = Microsoft.AspNetCore.Mvc.HttpGetAttribute; +using RouteAttribute = Microsoft.AspNetCore.Mvc.RouteAttribute; + +namespace NeDvachAPI.Controllers +{ + [ApiController] + [Route("[controller]")] + public class ThreadsController : ControllerBase + { + [HttpGet(Name = "GetThreads")] + public string Get([FromUri] string board) + { + string postsJson = JsonSerializer.Serialize(APIThreadBuffer.GetThreadPreviews()); + return postsJson; + } + } +} diff --git a/AuthInfo.cs b/AuthInfo.cs new file mode 100644 index 0000000..c43298e --- /dev/null +++ b/AuthInfo.cs @@ -0,0 +1,24 @@ +namespace NeDvachAPI +{ + public class AuthInfo + { + public class MinIo + { + public static string endpoint = "static.vdk2ch.ru:15555"; + public static string bucketName = "thread-pics thread-pics-small"; + public static string username = "admin"; + public static string password = "password2ch"; + } + + public class DB + { + public static string Host = "postgres.vdk2ch.ru"; + public static string User = "postgres"; + public static string DBname = "dvaach"; + public static string Password = "postgres"; + public static string Port = "5432"; + } + + + } +} diff --git a/BufferControllers/APIThreadBuffer.cs b/BufferControllers/APIThreadBuffer.cs new file mode 100644 index 0000000..2074a54 --- /dev/null +++ b/BufferControllers/APIThreadBuffer.cs @@ -0,0 +1,82 @@ +using NeDvachAPI.DBControllers; +using NeDvachAPI.Models; + +namespace NeDvachAPI.BufferControllers +{ + public class APIThreadBuffer + { + private static List[] ThreadsPrewievs = new List[0]; + private static List[] Threads = new List[0]; + public static void WriteThreadPreviewsBuffer(List OPPostsToWrite) //add list of OP-posts and last post to buffer + { + for(int pos = 0; pos < OPPostsToWrite.Count; pos ++) + { + var deb = new List(); + deb.Add(OPPostsToWrite[pos]); + ThreadsPrewievs = ThreadsPrewievs.Append(deb).ToArray(); + } + } + + public static void AppendToThreadPreviews(int index,Post toAppend) + { + ThreadsPrewievs[index].Add(toAppend); + } + + public static List[] GetThreadPreviews() + { + return ThreadsPrewievs; + } + + public static void UpdateThreadsPreviews(int threadId) + { + Console.WriteLine("Пытаюсь обновить превью треда " + threadId); + + var newPreview = new List(); + newPreview.Add(ThreadsPrewievs[threadId -1][0]); + int targetLength = APIThreadBuffer.GetThreadLength(threadId - 1); + for (int lastofthree = targetLength- 2; lastofthree <= targetLength; lastofthree ++) + { + newPreview.Add(GetSinglePost(threadId - 1,lastofthree)); + } + ThreadsPrewievs[threadId -1] = newPreview; + } + + public static void AppendThreadsBuffer(List ThreadToAdd) //add thread's posts from DB to buffer + { + Threads = Threads.Append(ThreadToAdd).ToArray(); + } + + public static int GetThreadLength(int threadId) + { + return Threads[threadId].Count; + } + + public static List GetThread(int threadId) + { + if (threadId < Threads.Length + 1 & threadId != 0) + { + return Threads[threadId - 1]; + } + else return null; + } + + public static Post GetSinglePost(int thread, int postPosition) + { + List postsList = Threads[thread]; + return postsList[postPosition-1]; + } + + public static void UpdateThreadPosts(int threadId) + { + Console.WriteLine("Пытаюсь обновить тред " + threadId); + Threads[threadId - 1] = DBchat.PostsList("b", threadId); + } + + public static void RefreshThread(int threadId) + { + UpdateThreadPosts(threadId); + UpdateThreadsPreviews(threadId); + } + + } +} diff --git a/BufferControllers/AccessController.cs b/BufferControllers/AccessController.cs new file mode 100644 index 0000000..9a1c9ed --- /dev/null +++ b/BufferControllers/AccessController.cs @@ -0,0 +1,15 @@ +using NeDvachAPI.Models; +using Npgsql; + +namespace NeDvachAPI.DBControllers +{ + public class BanList + { + public static string[] GetBanned() + { + string[] bannedIPs = new string[0]; + // + return bannedIPs; + } + } +} \ No newline at end of file diff --git a/BufferControllers/BufferFill.cs b/BufferControllers/BufferFill.cs new file mode 100644 index 0000000..95fa0fb --- /dev/null +++ b/BufferControllers/BufferFill.cs @@ -0,0 +1,33 @@ +using NeDvachAPI.DBControllers; +using NeDvachAPI.Models; + +namespace NeDvachAPI.BufferControllers +{ + public class BufferFill + { + + public static bool FillBuffer(string board) //method to get buffer of information, which is being ran while API is started + { + List Previews = DBchat.ThreadsList(board); + APIThreadBuffer.WriteThreadPreviewsBuffer(Previews); + Console.WriteLine("Adding OP-posts to buffer"); + + for (int threadId = 1; threadId <= Previews.Count; threadId++) + { + APIThreadBuffer.AppendThreadsBuffer(DBchat.PostsList(board, threadId)); + } + Console.WriteLine($@"Buffering threads {1} to {Previews.Count}."); + + for (int preview = 0; preview < Previews.Count; preview++) + { + int targetLength = APIThreadBuffer.GetThreadLength(preview); + for (int lastofthree = targetLength- 2; lastofthree <= targetLength; lastofthree ++) + { + APIThreadBuffer.AppendToThreadPreviews(preview,APIThreadBuffer.GetSinglePost(preview,lastofthree)); + } + } + + return true; + } + } +} diff --git a/Controllers/GetPosts.cs b/Controllers/GetPosts.cs deleted file mode 100644 index 8f2741c..0000000 --- a/Controllers/GetPosts.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System.Text.Json; - -namespace NeDvachAPI.Controllers -{ - [ApiController] - [Route("[controller]")] - public class ListController : ControllerBase - { - [HttpGet(Name = "GetPosts")] - public string Get() - { - - //Post[] posts = DBchat.DbList(); - List posts = DBchat.DbList(); - string postsJson = JsonSerializer.Serialize(posts); - Console.WriteLine("Запрошен список постов"); - return postsJson ; - - - } - } -} diff --git a/Controllers/PictureUpload.cs b/Controllers/PictureUpload.cs deleted file mode 100644 index b5b65b6..0000000 --- a/Controllers/PictureUpload.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System.Net.Http.Headers; -using System.Text.Json; - -namespace NeDvachAPI.Controllers -{ - [ApiController] - [Route("[controller]")] - public class UploadPic : ControllerBase - { - [HttpPost(Name = "UploadPicture")] - public JsonResult ReceivePost([FromForm] IFormFile PostPicture) - { - Console.Write("Принята картинка "); - Console.WriteLine(PostPicture.FileName); - return new JsonResult(PostPicture.FileName + " получен!"); - } - } -} diff --git a/Controllers/PostPost.cs b/Controllers/PostPost.cs deleted file mode 100644 index 764651b..0000000 --- a/Controllers/PostPost.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System.Text.Json; - -namespace NeDvachAPI.Controllers -{ - [ApiController] - [Route("[controller]")] - public class PostToController : ControllerBase - { - [HttpPost(Name = "PostPosts")] - public JsonResult ReceivePost([FromBody] Post ReceivedPost) - { - Console.WriteLine("Принят пост"); - DBchat.SendPost(ReceivedPost); - return new JsonResult("Posted Successfully!"); - } - } -} diff --git a/Controllers/TestPosting.cs b/Controllers/TestPosting.cs deleted file mode 100644 index 68c0748..0000000 --- a/Controllers/TestPosting.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using System.Net; -using System.Text.Json; - -namespace NeDvachAPI.Controllers -{ - [ApiController] - [Route("[controller]")] - public class TestPostingController : ControllerBase - { - [HttpPost] - public int Area([FromForm] int height , int altitude) - { - //DBchat.SendPost(ReceivedPost); - Console.WriteLine("Received! " + height + " " + altitude ); - return 200; - } - } -} diff --git a/DBControllers/DBchat.cs b/DBControllers/DBchat.cs new file mode 100644 index 0000000..74b9009 --- /dev/null +++ b/DBControllers/DBchat.cs @@ -0,0 +1,211 @@ +using NeDvachAPI.Models; +using Npgsql; + +namespace NeDvachAPI.DBControllers +{ + public class DBchat + { + public static List PostsList(string boardName, int thread) + { + List posts = new List(); + string connString = + string.Format( + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", + AuthInfo.DB.Host, + AuthInfo.DB.User, + AuthInfo.DB.DBname, + AuthInfo.DB.Port, + AuthInfo.DB.Password); + + using (var conn = new NpgsqlConnection(connString)) + { + + + conn.Open(); + using (var command = new NpgsqlCommand($@" + SELECT * FROM + ( + SELECT post_id, post_text, content, post_timestamp + FROM posts + WHERE thread_id = {thread} + ORDER BY post_id DESC + ) subquery + ORDER BY post_id ASC", conn)) + { + + var reader = command.ExecuteReader(); + while (reader.Read()) + { + Post receivedPost = new() + { + Id = reader.GetInt32(0), + Text = reader.GetString(1), + ImgURL = reader.IsDBNull(2) ? null : reader.GetFieldValue(2), + Timestamp = reader.GetString(3) + + }; + posts.Add(receivedPost); + } + reader.Close(); + } + } + return posts; + } + + public static List ThreadsList(string boardName) + { + List posts = new List(); + string connString = + string.Format( + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", + AuthInfo.DB.Host, + AuthInfo.DB.User, + AuthInfo.DB.DBname, + AuthInfo.DB.Port, + AuthInfo.DB.Password); + + using (var conn = new NpgsqlConnection(connString)) + { + + + conn.Open(); + + using (var command = new NpgsqlCommand($@" + SELECT * FROM + ( + SELECT post_id, post_text, content, post_timestamp, is_op, thread_id + FROM posts + WHERE + is_op = {true} + ORDER BY thread_id DESC + ) subquery + ORDER BY thread_id ASC", conn)) + { + + var reader = command.ExecuteReader(); + while (reader.Read()) + { + Post receivedPost = new() + { + Id = reader.GetInt32(0), + Text = reader.GetString(1), + ImgURL = reader.IsDBNull(2) ? null : reader.GetFieldValue(2), + Timestamp = reader.GetString(3), + Is_OP = reader.GetBoolean(4), + Thread_Id = reader.GetInt32(5) + + }; + posts.Add(receivedPost); + } + reader.Close(); + } + } + return posts; + } + + public static void DbUpdate(string id, string text) + { + string connString = + string.Format( + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", + AuthInfo.DB.Host, + AuthInfo.DB.User, + AuthInfo.DB.DBname, + AuthInfo.DB.Port, + AuthInfo.DB.Password); + + using (var conn = new NpgsqlConnection(connString)) + { + conn.Open(); + + using (var command = new NpgsqlCommand("UPDATE dvach " + + "SET post = @postText WHERE post_id = @ID", conn)) + { + command.Parameters.AddWithValue("ID", int.Parse(id)); + command.Parameters.AddWithValue("postText", text); + + int nRows = command.ExecuteNonQuery(); + Console.Out.WriteLine(string.Format("Number of rows updated={0}", nRows)); + } + } + + Console.WriteLine("Данные обновлены!"); + Console.ReadLine(); + } + public static void SendPost(Post postToSend) //sending post to database + { + string connString = + string.Format( + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", + AuthInfo.DB.Host, + AuthInfo.DB.User, + AuthInfo.DB.DBname, + AuthInfo.DB.Port, + AuthInfo.DB.Password); + + using (var conn = new NpgsqlConnection(connString)) + { + conn.Open(); + int postNum = 14; + + using (var command = new NpgsqlCommand(@" + INSERT INTO posts (post_id, post_text, post_number, content, thread_id, auth_ip, is_op, post_timestamp) + VALUES ( + DEFAULT, + @postText, + @postNum, + @postImgUrl, + @threadId, + @ip, + false, + ( + SELECT date_trunc( + 'second', + (now()::timestamp(0) AT TIME ZONE 'UTC+10')::TIMESTAMP + ) + ) )", conn)) + { + command.Parameters.AddWithValue("postText", postToSend.Text); + command.Parameters.AddWithValue("postNum", postNum); + command.Parameters.AddWithValue("postImgUrl", postToSend.ImgURL); + command.Parameters.AddWithValue("threadId", postToSend.Thread_Id); + command.Parameters.AddWithValue("ip", postToSend.Ip); + int nRows = command.ExecuteNonQuery(); + Console.Out.WriteLine("Добавлен пост с текстом " + postToSend.Text + " номером " + 22); + } + } + + } + public static void DeletePost(string idToDel) //удалялка + { + string connString = + string.Format( + "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", + AuthInfo.DB.Host, + AuthInfo.DB.User, + AuthInfo.DB.DBname, + AuthInfo.DB.Port, + AuthInfo.DB.Password); + + using (var conn = new NpgsqlConnection(connString)) + { + + conn.Open(); + + using (var command = new NpgsqlCommand(@" + DELETE FROM dvach + WHERE post_id = @ID", conn)) + { + command.Parameters.AddWithValue("ID", int.Parse(idToDel)); ; + + int nRows = command.ExecuteNonQuery(); + Console.Out.WriteLine(string.Format("Number of rows updated={0}", nRows)); + } + } + + Console.WriteLine("Данные удалены!"); + Console.ReadLine(); + + } + } +} diff --git a/DBControllers/ImageController.cs b/DBControllers/ImageController.cs new file mode 100644 index 0000000..130c47c --- /dev/null +++ b/DBControllers/ImageController.cs @@ -0,0 +1,43 @@ + +using SkiaSharp; + +namespace NeDvachAPI.DBControllers +{ + public class ImageController + { + public static bool CheckExtention(string extentionToCheck) + { + var supportedTypes = new[] { ".jpg", ".png", ".jpeg" }; + if (supportedTypes.Contains(extentionToCheck.ToLower())) + { + return true; + } + else return false; + } + + public static bool ResizeImage(string picPath, string smallPath, int width, int height) + { + + var bitmap = SKBitmap.Decode(picPath); + + double ratio = Math.Max((double)bitmap.Width / (double)width , (double)bitmap.Height / (double)height); + int targetWidth = (int)(bitmap.Width/ ratio); + int targetHeight = (int)(bitmap.Height / ratio); + + Console.WriteLine($"Ресайзим картинку до {targetWidth} ширины и {targetHeight} высоты."); + + var dstInfo = new SKImageInfo(targetWidth , targetHeight); + var image = SKImage.FromBitmap(bitmap.Resize(dstInfo, SKFilterQuality.Medium)); + var data = image.Encode(SKEncodedImageFormat.Jpeg, 90); + + using (var stream = new FileStream(smallPath, FileMode.Create, FileAccess.Write)) + data.SaveTo(stream); + + data.Dispose(); + image.Dispose(); + bitmap.Dispose(); + return true; + } + } +} + diff --git a/DBControllers/MinIOchat.cs b/DBControllers/MinIOchat.cs new file mode 100644 index 0000000..da3ae55 --- /dev/null +++ b/DBControllers/MinIOchat.cs @@ -0,0 +1,36 @@ +using Microsoft.AspNetCore.Mvc; +using Minio.DataModel; +using Minio; +using System.Security.Cryptography; + +namespace NeDvachAPI.DBControllers +{ + public class MinIOchat + { + public static async Task PictureUpload(string fileroute, string filename, string bucket) + { + MinioClient DvachIo = new MinioClient() + .WithEndpoint(AuthInfo.MinIo.endpoint) + .WithCredentials(AuthInfo.MinIo.username, AuthInfo.MinIo.password) + //.WithSSL() + .Build(); + + Aes aesEncryption = Aes.Create(); + aesEncryption.KeySize = 256; + aesEncryption.GenerateKey(); + var ssec = new SSEC(aesEncryption.Key); + PutObjectArgs putObjectArgs = new PutObjectArgs() + .WithBucket(bucket) + .WithObject(filename) + .WithFileName(fileroute) + .WithContentType("image/png"); + //.WithServerSideEncryption(ssec); + await DvachIo.PutObjectAsync(putObjectArgs); + GC.Collect(); + GC.WaitForPendingFinalizers(); + File.Delete(fileroute); + + return new JsonResult("http://static.vdk2ch.ru:15555/thread-pics/" + filename); + } + } +} diff --git a/DBchat.cs b/DBchat.cs deleted file mode 100644 index d6be19b..0000000 --- a/DBchat.cs +++ /dev/null @@ -1,181 +0,0 @@ -using Npgsql; -using static System.Net.Mime.MediaTypeNames; - -namespace NeDvachAPI -{ - public class DBchat - { - // Obtain connection string information from the portal - private static string Host = "postgres.vdk2ch.ru"; - private static string User = "postgres"; - private static string DBname = "postgres"; - private static string Password = "postgres"; - private static string Port = "5432"; - - public static List DbList() - { - // Build connection string using parameters from portal - //Post[] posts = new Post[10]; - List posts = new List(); - //int postCount = 0; - string received = ""; - string connString = - String.Format( - "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", - Host, - User, - DBname, - Port, - Password); - - using (var conn = new NpgsqlConnection(connString)) - { - - - conn.Open(); - - - // using ( var command = new NpgsqlCommand(@" - // SELECT * FROM - // (SELECT post_id, substring(post,1,200) - // FROM dvach - // ORDER BY post_id DESC - // limit 10 - // ) - // subquery ORDER BY post_id ASC", conn) ) - using ( var command = new NpgsqlCommand(@" - SELECT * FROM - ( - SELECT post_id, post, post_timestamp, post_pic - FROM dvach - ORDER BY post_id DESC - ) subquery - ORDER BY post_id ASC", conn) ) - { - - var reader = command.ExecuteReader(); - while (reader.Read()) - { - //received +=( - //string.Format( - //"#{0}: {1}" + "\n", - // reader.GetInt32(0).ToString(), - //reader.GetString(1) - //) - //); - Post receivedPost = new() - { - Id = reader.GetInt32(0), - Text = reader.GetString(1), - Timestamp = reader.GetString(2), - ImgURL = (string)reader.GetString(3) - - }; - posts.Add(receivedPost); - //posts[postCount] = receivedPost; - //postCount++; - } - reader.Close(); - } - } - return posts; - } - - public static void DbUpdate(string id, string text) - { - string connString = - String.Format( - "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", - Host, - User, - DBname, - Port, - Password); - - using (var conn = new NpgsqlConnection(connString)) - { - conn.Open(); - - using (var command = new NpgsqlCommand("UPDATE dvach " + - "SET post = @postText WHERE post_id = @ID", conn)) - { - command.Parameters.AddWithValue("ID", int.Parse(id)); - command.Parameters.AddWithValue("postText", text); - - int nRows = command.ExecuteNonQuery(); - Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows)); - } - } - - Console.WriteLine("Данные обновлены!"); - Console.ReadLine(); - } - public static void SendPost(Post postToSend) //добавлялка - { - string connString = - String.Format( - "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", - Host, - User, - DBname, - Port, - Password); - - using (var conn = new NpgsqlConnection(connString)) - { - - Console.Out.WriteLine("Opening connection"); - conn.Open(); - - using (var command = new NpgsqlCommand(@" - INSERT INTO dvach (post_id, post, post_timestamp) - VALUES ( DEFAULT, @postText, ( - SELECT date_trunc( - 'second', - (now()::timestamp(0) AT TIME ZONE 'UTC+10')::TIMESTAMP - ) - ) )", conn)) - { - command.Parameters.AddWithValue("postText", postToSend.Text); - //command.Parameters.AddWithValue("postTimeStamp", DateTime.Now.ToString("dd/MM/yyyy HH:mm")); - - int nRows = command.ExecuteNonQuery(); - Console.Out.WriteLine("Добавлен пост"); - } - } - - } - public static void DeletePost(string idToDel) //удалялка - { - string connString = - String.Format( - "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};SSLMode=Prefer", - Host, - User, - DBname, - Port, - Password); - - using (var conn = new NpgsqlConnection(connString)) - { - - //Console.Out.WriteLine("Opening connection"); - conn.Open(); - - using (var command = new NpgsqlCommand(@" - DELETE FROM dvach - WHERE post_id = @ID", conn)) - { - command.Parameters.AddWithValue("ID", int.Parse(idToDel)); ; - - int nRows = command.ExecuteNonQuery(); - Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows)); - } - } - - Console.WriteLine("Данные удалены!"); - Console.ReadLine(); - - } - } -} diff --git a/Dockerfile b/Dockerfile index d73a1ee..4fd2955 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,7 @@ FROM mcr.microsoft.com/dotnet/aspnet:6.0 + + ADD dist /app WORKDIR /app diff --git a/Models/Post.cs b/Models/Post.cs new file mode 100644 index 0000000..dd63af7 --- /dev/null +++ b/Models/Post.cs @@ -0,0 +1,14 @@ +namespace NeDvachAPI.Models +{ + public class Post + { + public string Timestamp { get; set; } + public int Id { get; set; } + public string Text { get; set; } + public string[]? ImgURL { get; set; } + public int Thread_Id { get; set; } + public bool Is_OP { get; set; } + public bool Is_Deleted { get; set; } + public string? Ip { get; set; } + } +} \ No newline at end of file diff --git a/NeDvachAPI.csproj b/NeDvachAPI.csproj index fa2104b..3cb4b3e 100644 --- a/NeDvachAPI.csproj +++ b/NeDvachAPI.csproj @@ -7,8 +7,17 @@ - - + + + + + + + + + + + diff --git a/NeDvachAPI.csproj.user b/NeDvachAPI.csproj.user index e4f6e71..4c07044 100644 --- a/NeDvachAPI.csproj.user +++ b/NeDvachAPI.csproj.user @@ -3,5 +3,9 @@ MvcControllerEmptyScaffolder root/Common/MVC/Controller + NeDvachAPI + + + ProjectDebugger \ No newline at end of file diff --git a/Post.cs b/Post.cs deleted file mode 100644 index 8e083e7..0000000 --- a/Post.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace NeDvachAPI -{ - public class Post - { - public string? Timestamp { get; set; } - - public int Id { get; set; } - - public string Text { get; set; } - - public string ImgURL { get; set; } - } -} \ No newline at end of file diff --git a/Program.cs b/Program.cs index d02cb2a..605bcbc 100644 --- a/Program.cs +++ b/Program.cs @@ -1,12 +1,11 @@ -var builder = WebApplication.CreateBuilder(args); +using NeDvachAPI.BufferControllers; -// Add services to the container. +var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddCors(setup => { setup.AddDefaultPolicy(policyBuilder => @@ -19,18 +18,12 @@ builder.Services.AddCors(setup => }); -//builder.Services.AddSwaggerGen(); - var app = builder.Build(); -// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { - //app.UseSwagger(); - //app.UseSwaggerUI(); -} -//app.UseHttpsRedirection(); +} app.UseCors(); @@ -38,4 +31,12 @@ app.UseAuthorization(); app.MapControllers(); -app.Run(); +app.UseHttpsRedirection(); + +if (BufferFill.FillBuffer("b")) +{ + Console.WriteLine("Ready for work."); + app.Run(); +} +else Console.WriteLine("Ошибка буферизации, проверьте доступность базы данных."); + diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json index 6bff1e8..0973904 100644 --- a/Properties/launchSettings.json +++ b/Properties/launchSettings.json @@ -1,4 +1,22 @@ -{ +{ + "profiles": { + "NeDvachAPI": { + "commandName": "Project", + "launchUrl": "Home", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://0.0.0.0:7141" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchUrl": "Home", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + }, "$schema": "https://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, @@ -7,25 +25,5 @@ "applicationUrl": "http://0.0.0.0:31551", "sslPort": 44346 } - }, - "profiles": { - "NeDvachAPI": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "Home", - "applicationUrl": "http://0.0.0.0:7141;http://0.0.0.0:5141", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "Home", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } } -} +} \ No newline at end of file diff --git a/appsettings.json b/appsettings.json index 23039ed..90652b9 100644 --- a/appsettings.json +++ b/appsettings.json @@ -1,4 +1,5 @@ { + "https_port": 443, "Logging": { "LogLevel": { "Default": "Debug", diff --git a/docker-compose.yml b/docker-compose.yml index f060431..e4206f9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,3 +10,8 @@ services: restart: always ports: - "5000:80" + logging: + driver: "gelf" + options: + gelf-address: "udp://graylog.vdk2ch.ru:12201" + tag: "backend-logs" diff --git a/libman.json b/libman.json new file mode 100644 index 0000000..ceee271 --- /dev/null +++ b/libman.json @@ -0,0 +1,5 @@ +{ + "version": "1.0", + "defaultProvider": "cdnjs", + "libraries": [] +} \ No newline at end of file diff --git a/newFile.txt b/newFile.txt new file mode 100644 index 0000000..e69de29