mc_misc.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net/http"
  9. "os"
  10. "time"
  11. guuid "github.com/google/uuid"
  12. )
  13. var prevFileMD5 = ""
  14. func SendCommand(w http.ResponseWriter, r *http.Request) {
  15. command, _ := mv(r, "command", false)
  16. MCServer.SendCommand(command)
  17. //Handle image output
  18. //generate UUID if for image
  19. id := guuid.New()
  20. filename := id.String() + ".png"
  21. MCServer.SendCommand("print -dpng " + filename)
  22. for {
  23. <-time.After(time.Second)
  24. fmt.Println("Waiting files...")
  25. if fileExists("./tmp/" + filename) {
  26. break
  27. }
  28. }
  29. if fileExists("./tmp/" + filename) {
  30. newFileMD5, _ := hashFileMD5("./tmp/" + filename)
  31. fmt.Println(newFileMD5)
  32. if newFileMD5 == prevFileMD5 && prevFileMD5 != "" {
  33. e := os.Remove("./tmp/" + filename)
  34. if e != nil {
  35. log.Fatal(e)
  36. }
  37. } else {
  38. if prevFileMD5 != "" {
  39. MCServer.AddLogEntry("<img style=\"width:400px;height:auto\" src=\"./output/" + filename + "\"></img>")
  40. } else {
  41. e := os.Remove("./tmp/" + filename)
  42. if e != nil {
  43. log.Fatal(e)
  44. }
  45. }
  46. }
  47. prevFileMD5 = newFileMD5
  48. }
  49. //end image output
  50. sendJSONResponse(w, "OK")
  51. }
  52. func hashFileMD5(filePath string) (string, error) {
  53. var returnMD5String string
  54. file, err := os.Open(filePath)
  55. if err != nil {
  56. return returnMD5String, err
  57. }
  58. defer file.Close()
  59. hash := md5.New()
  60. if _, err := io.Copy(hash, file); err != nil {
  61. return returnMD5String, err
  62. }
  63. hashInBytes := hash.Sum(nil)[:16]
  64. returnMD5String = hex.EncodeToString(hashInBytes)
  65. return returnMD5String, nil
  66. }