Skip to content

Commit

Permalink
socializer modernization
Browse files Browse the repository at this point in the history
  • Loading branch information
sei-dupdyke committed Dec 18, 2023
1 parent 95532a7 commit fadc3b9
Show file tree
Hide file tree
Showing 2,349 changed files with 449,777 additions and 23,412 deletions.
170 changes: 170 additions & 0 deletions src/ghosts.pandora.socializer/src/Controllers/DataController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Socializer.Hubs;
using Socializer.Infrastructure;

namespace Socializer.Controllers;

[Route("/api")]
public class DataController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHubContext<PostsHub> _hubContext;
private readonly DataContext _db;

public DataController(ILogger<HomeController> logger, IHubContext<PostsHub> hubContext, DataContext dbContext)
{
_logger = logger;
_hubContext = hubContext;
_db = dbContext;
}

[HttpGet]
public IEnumerable<Post> Index()
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

var posts = _db.Posts.OrderByDescending(x=>x.CreatedUtc).Take(Program.Configuration.DefaultDisplay).ToList();

if (Request.QueryString.HasValue && !string.IsNullOrEmpty(Request.Query["u"]))
ViewBag.User = Request.Query["u"];
return posts;
}

[HttpGet("u/{userId}")]
public new virtual IEnumerable<Post> User(string userId)
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

var posts = _db.Posts.Where(x=>x.User.ToLower() == userId.ToLower()).OrderByDescending(x=>x.CreatedUtc).Take(Program.Configuration.DefaultDisplay).ToList();

if (Request.QueryString.HasValue && !string.IsNullOrEmpty(Request.Query["u"]))
ViewBag.User = Request.Query["u"];
return posts;
}

[HttpGet("{id:guid}")]
public Post? Detail(Guid id)
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

var post = _db.Posts.FirstOrDefault(x => x.Id == id.ToString());

if (Request.QueryString.HasValue && !string.IsNullOrEmpty(Request.Query["u"]))
ViewBag.User = Request.Query["u"];
return post;
}

[HttpGet("/admin/delete")]
public async Task<IActionResult> Delete()
{
this._db.Posts.RemoveRange(this._db.Posts);
await this._db.SaveChangesAsync();
return NoContent();
}

[HttpGet("/admin/generate/{n}")]
public async Task<IActionResult> Generate(int n)
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

var r = new Random();
for (var i = 0; i < n; i++)
{
var min = DateTime.Now.AddDays(-7);
var randTicks = r.Next(0, (int) (DateTime.Now.Ticks - min.Ticks));

var post = new Post();
post.Id = Guid.NewGuid().ToString();
post.CreatedUtc = DateTime.MinValue.Add(TimeSpan.FromTicks(min.Ticks + (long) (r.NextDouble()*(DateTime.Now.Ticks - min.Ticks))));
post.User = Faker.Internet.UserName();
post.Message = Faker.Lorem.Sentence(15);
this._db.Posts.Add(post);
}
await _db.SaveChangesAsync();

return NoContent();
}

[HttpPost]
public async Task<IActionResult> Post([FromForm] FilesController.FileInputModel model)
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|{Join}", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method, string.Join(",", Request.Form));

var post = new Post
{
Id = Guid.NewGuid().ToString(),
CreatedUtc = DateTime.UtcNow
};

var userFormValues = new [] {"user", "usr", "u", "uid", "user_id", "u_id"};
foreach (var userFormValue in userFormValues)
{
if (string.IsNullOrEmpty(Request.Form[userFormValue])) continue;
post.User = Request.Form[userFormValue]!;
break;
}

var messageFormValues = new [] {"message", "msg", "m", "message_id", "msg_id", "msg_text", "text", "payload"};
foreach (var messageFormValue in messageFormValues)
{
if (string.IsNullOrEmpty(Request.Form[messageFormValue])) continue;
post.Message = Request.Form[messageFormValue]!;
break;
}

if(string.IsNullOrEmpty(post.User) || string.IsNullOrEmpty(post.Message))
return BadRequest("User and message are required.");

// has the same user tried to post the same message within the past x minutes?
if (_db.Posts.Any(_ => _.Message.ToLower() == post.Message.ToLower()
&& _.User.ToLower() == post.User.ToLower()
&& _.CreatedUtc > post.CreatedUtc.AddMinutes(-Program.Configuration.MinutesToCheckForDuplicatePost)))
{
this._logger.LogInformation("Client is posting duplicates: {PostUser}", post.User);
return NoContent();
}

var imagePath = string.Empty;
if (model.File != null)
{
var guid = Guid.NewGuid().ToString();
var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images");
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
savePath = Path.Combine(savePath, guid);
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);

savePath = Path.Combine(savePath, model.File.FileName);

try
{
// Process the file and save it to storage
// Note: You may want to validate the file size, content type, etc. before saving it
await using (var stream = new FileStream(savePath, FileMode.Create))
{
await model.File.CopyToAsync(stream);
}

imagePath = $"/images/{guid}/{model.File.FileName}";
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}

if (!string.IsNullOrEmpty(imagePath))
{
post.Message = post.Message + $" <img src=\"{imagePath}\"/>";
}

_db.Posts.Add(post);
await _db.SaveChangesAsync();

await _hubContext.Clients.All.SendAsync("SendMessage", post.Id, post.User, post.Message, post.CreatedUtc);

return NoContent();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ public IActionResult Index()
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

var posts = _db.Posts.Take(Program.Configuration.DefaultDisplay).ToList();
var posts = _db.Posts.OrderByDescending(x=>x.CreatedUtc).Take(Program.Configuration.DefaultDisplay).ToList();

if (Request.QueryString.HasValue && !string.IsNullOrEmpty(Request.Query["u"]))
ViewBag.User = Request.Query["u"];
return View(posts);
}

[HttpGet("/u/{userId}")]
public IActionResult User(string userId)
public new virtual IActionResult User(string userId)
{
this._logger.LogTrace("{RequestScheme}://{RequestHost}{RequestPath}{RequestQueryString}|{RequestMethod}|", Request.Scheme, Request.Host, Request.Path, Request.QueryString, Request.Method);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,10 @@ public class Post
public string Message { get; set; }
public DateTime CreatedUtc { get; set; }
}

public class User
{
public string Name { get; set; }
public string Avatar { get; set; }
public string Status { get; set; }
}
36 changes: 1 addition & 35 deletions src/ghosts.pandora.socializer/src/Views/Home/Detail.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
@model Socializer.Infrastructure.Post

<div class="row row-cols-1 row-cols-md-12" id="itemList">
@if (Model != null)
{
@{
var post = Model;
<div class="col" id="@post.Id">
<div class="card h-100">
Expand All @@ -23,36 +22,3 @@
</div>
}
</div>
<br/>
@* <div class="row"> *@
@* <div class="col-12"> *@
@* <hr/> *@
@* </div> *@
@* </div> *@
@* <div class="container"> *@
@* <div class="row">&nbsp;</div> *@
@* <div class="row"> *@
@* <div class="col-2">User</div> *@
@* <div class="col-4"> *@
@* <input type="text" id="userInput" class="form-control" value="@ViewBag.User"/> *@
@* </div> *@
@* </div> *@
@* <div class="row"> *@
@* <div class="col-2">Message</div> *@
@* <div class="col-4"> *@
@* <textarea type="text" id="messageInput" class="form-control"></textarea> *@
@* </div> *@
@* </div> *@
@* <div class="row">&nbsp;</div> *@
@* <div class="row"> *@
@* <div class="col-6"> *@
@* <input type="button" id="sendButton" value="Send Message"/> *@
@* </div> *@
@* </div> *@
@* </div> *@
<br/>
<form method="post" enctype="multipart/form-data">
<input type="text" name="u" id="u"/> <input type="text" name="m" id="m"/> <input type="file" name="File"/> <input type="submit" name="submit" id="sendButton"/>
</form>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/posts.js" asp-append-version="true"></script>
Loading

0 comments on commit fadc3b9

Please sign in to comment.