date.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-FileCopyrightText: Adam Evyčędo
  2. //
  3. // SPDX-License-Identifier: AGPL-3.0-or-later
  4. package traffic
  5. import (
  6. "slices"
  7. traffic_errors "apiote.xyz/p/szczanieckiej/traffic/errors"
  8. "fmt"
  9. "time"
  10. )
  11. func GetTimezone(stop Stop, t *Traffic, feedID string) (*time.Location, error) {
  12. if stop.Timezone != "" {
  13. return time.LoadLocation(stop.Timezone)
  14. }
  15. for _, feedInfos := range t.FeedInfos {
  16. feedInfo, ok := feedInfos[feedID]
  17. if ok {
  18. return time.LoadLocation(feedInfo.Timezone)
  19. }
  20. }
  21. return nil, fmt.Errorf("cannot find feedInfo for %s in timezone calculation", feedID)
  22. }
  23. func ParseDate(dateString string, feedName string, t *Traffic) (Validity, time.Time, error) {
  24. versionCode := Validity("")
  25. timezone, err := GetTimezone(Stop{}, t, feedName)
  26. if err != nil {
  27. return versionCode, time.Time{}, fmt.Errorf("while getting timezone: %w", err)
  28. }
  29. if dateString == "" {
  30. feedNow := time.Now().In(timezone)
  31. dateString = feedNow.Format(DateFormat)
  32. }
  33. date, err := time.ParseInLocation(DateFormat, dateString, timezone)
  34. if err != nil {
  35. return versionCode, date, fmt.Errorf("while parsing date: %w", err)
  36. }
  37. versions := t.Versions[feedName]
  38. slices.Reverse(versions)
  39. for _, v := range versions {
  40. if !v.ValidFrom.After(date) && !date.After(v.ValidTill) {
  41. versionCode = Validity(v.String())
  42. }
  43. }
  44. if versionCode == "" {
  45. return versionCode, date, traffic_errors.NoVersionError{
  46. Date: dateString,
  47. }
  48. }
  49. return versionCode, date, nil
  50. }