RoomController.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Newtonsoft.Json;
  7. namespace jsonapi.Controllers
  8. {
  9. [ApiController]
  10. [Route("room")]
  11. [Produces("application/json")]
  12. public class RoomController : ControllerBase
  13. {
  14. private IConfiguration configuration;
  15. private Library.SHA256HashGenerator sha256HashGenerator;
  16. private Library.JsonFileReader jsonFileReader;
  17. public RoomController(IConfiguration config)
  18. {
  19. configuration = config;
  20. sha256HashGenerator = Library.SHA256HashGenerator.GetInstance();
  21. jsonFileReader = Library.JsonFileReader.GetInstance();
  22. }
  23. [HttpGet]
  24. public IActionResult Get()
  25. {
  26. try
  27. {
  28. var json = jsonFileReader.Read("Static/room.json");
  29. return Ok(json);
  30. }
  31. catch (Exception)
  32. {
  33. dynamic errorObject = new
  34. {
  35. errorCode = StatusCodes.Status500InternalServerError,
  36. errorMessage = "500 Error: Something went wrong. Please contact the administrator for assistance."
  37. };
  38. return StatusCode(errorObject.errorCode, errorObject);
  39. }
  40. }
  41. [HttpGet("{x},{y},{z}")]
  42. public IActionResult Get(int x, int y, int z)
  43. {
  44. string worldPath = configuration.GetSection("jsonapi").GetValue<string>("world");
  45. string filePath = worldPath + "/rooms/" + z + "/" + x + "," + y + ".json";
  46. if(!System.IO.File.Exists(filePath)) {
  47. var generator = Library.RoomGenerator.GetInstance();
  48. var body = generator.Generate(x, y, z);
  49. System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(body, Formatting.Indented));
  50. return Ok(body);
  51. }
  52. try
  53. {
  54. var json = jsonFileReader.Read(filePath);
  55. return Ok(json);
  56. }
  57. catch (Exception)
  58. {
  59. dynamic errorObject = new
  60. {
  61. errorCode = StatusCodes.Status500InternalServerError,
  62. errorMessage = "500 Error: Something went wrong. Please contact the administrator for assistance.",
  63. filePath = filePath
  64. };
  65. return StatusCode(errorObject.errorCode, errorObject);
  66. }
  67. }
  68. }
  69. }