new.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // SPDX-FileCopyrightText: Adam Evyčędo
  2. //
  3. // SPDX-License-Identifier: AGPL-3.0-or-later
  4. package gtfs_rt
  5. import (
  6. pb "apiote.xyz/p/szczanieckiej/gtfs_rt/transit_realtime"
  7. "archive/zip"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "os"
  13. "strings"
  14. "time"
  15. "google.golang.org/protobuf/proto"
  16. )
  17. func GetMessages(feedID string, updatesLocation string) (*pb.FeedMessage, error) {
  18. var (
  19. message *pb.FeedMessage
  20. feedURL string
  21. unarchive string
  22. fileName string
  23. bytes []byte
  24. )
  25. if strings.Contains(updatesLocation, " | ") {
  26. urlCommand := strings.Split(updatesLocation, " | ")
  27. feedURL = urlCommand[0]
  28. command := strings.SplitN(urlCommand[1], " ", 2)
  29. unarchive = command[0]
  30. fileName = command[1]
  31. } else {
  32. feedURL = updatesLocation
  33. }
  34. client := http.Client{Timeout: 5 * time.Second}
  35. response, err := client.Get(feedURL)
  36. if err != nil {
  37. return nil, fmt.Errorf("while getting: %w", err)
  38. }
  39. switch unarchive {
  40. case "zip":
  41. tmp, err := os.CreateTemp("", "gtfsrt")
  42. if err != nil {
  43. return nil, fmt.Errorf("while creating temporary file for gtfs-rt: %w", err)
  44. }
  45. io.Copy(tmp, response.Body)
  46. z, err := zip.OpenReader(tmp.Name())
  47. if err != nil {
  48. return nil, fmt.Errorf("while opening temporary file for unzipping gtfs-rt: %w", err)
  49. }
  50. for _, file := range z.File {
  51. if file.Name == fileName {
  52. srcFile, err := file.Open()
  53. if err != nil {
  54. return nil, fmt.Errorf("while openning zipped file: %w", err)
  55. }
  56. bytes, err = io.ReadAll(srcFile)
  57. if err != nil {
  58. return nil, fmt.Errorf("while reading zipped file: %w", err)
  59. }
  60. break
  61. }
  62. }
  63. err = os.Remove(tmp.Name())
  64. if err != nil {
  65. log.Println("failed removing temporary zip file")
  66. }
  67. case "":
  68. bytes, err = io.ReadAll(response.Body)
  69. if err != nil {
  70. return nil, fmt.Errorf("while reading body: %w", err)
  71. }
  72. }
  73. message = new(pb.FeedMessage)
  74. if err := proto.Unmarshal(bytes, message); err != nil {
  75. return nil, fmt.Errorf("Failed to parse message: %w", err)
  76. }
  77. return message, nil
  78. }