timezone.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package timezone
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "time"
  10. "imuslab.com/arozos/mod/utils"
  11. )
  12. /*
  13. (The Original) System Time & Date Services
  14. This module handle updates and setup of the current system time and date
  15. (Add more helpful comments here)
  16. Original author: alanyeung
  17. Migrated to go module from main scope by tobychui
  18. TODO: timezone problems.
  19. */
  20. //returnFormat shoulbn't be exported
  21. type returnFormat struct {
  22. Time string `json:"time"`
  23. Timezone string `json:"timezone"`
  24. }
  25. //WindowsTimeZoneStruct shouldn't be exported.
  26. type WindowsTimeZoneStruct struct {
  27. SupplementalData struct {
  28. Version struct {
  29. Number string `json:"_number"`
  30. } `json:"version"`
  31. WindowsZones struct {
  32. MapTimezones struct {
  33. MapZone []struct {
  34. Other string `json:"_other"`
  35. Territory string `json:"_territory"`
  36. Type string `json:"_type"`
  37. } `json:"mapZone"`
  38. OtherVersion string `json:"_otherVersion"`
  39. TypeVersion string `json:"_typeVersion"`
  40. } `json:"mapTimezones"`
  41. } `json:"windowsZones"`
  42. } `json:"supplementalData"`
  43. }
  44. func ShowTime(w http.ResponseWriter, r *http.Request) {
  45. now := time.Now() // current local time
  46. Timezone := ""
  47. if runtime.GOOS == "linux" {
  48. cmd := exec.Command("timedatectl", "show", "-p", "Timezone")
  49. out, _ := cmd.CombinedOutput()
  50. outString := string(out)
  51. outString = strings.SplitN(outString, "=", 2)[1]
  52. Timezone = outString
  53. } else if runtime.GOOS == "windows" {
  54. cmd := exec.Command("tzutil", "/g")
  55. out, _ := cmd.CombinedOutput()
  56. outString := string(out)
  57. Timezone = ConvertWinTZtoLinuxTZ(outString)
  58. } else if runtime.GOOS == "darwin" {
  59. //no support, just ease my debugging
  60. Timezone = "America/Los_Angeles"
  61. }
  62. returnStruct := returnFormat{
  63. Time: now.Format(time.RFC3339),
  64. Timezone: Timezone,
  65. }
  66. returnString, _ := json.Marshal(returnStruct)
  67. utils.SendJSONResponse(w, string(returnString))
  68. }
  69. func ConvertWinTZtoLinuxTZ(WinTZ string) string {
  70. file, _ := ioutil.ReadFile("./system/time/wintz.json")
  71. WinTZLinuxTz := WindowsTimeZoneStruct{}
  72. json.Unmarshal([]byte(file), &WinTZLinuxTz)
  73. for _, data := range WinTZLinuxTz.SupplementalData.WindowsZones.MapTimezones.MapZone {
  74. if data.Other == WinTZ {
  75. LinuxTZ := strings.SplitN(data.Type, " ", 2)[0]
  76. return LinuxTZ
  77. }
  78. }
  79. return ""
  80. }