access.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. // SPDX-FileCopyrightText: Adam Evyčędo
  2. //
  3. // SPDX-License-Identifier: AGPL-3.0-or-later
  4. package traffic
  5. import (
  6. "apiote.xyz/p/szczanieckiej/config"
  7. "apiote.xyz/p/szczanieckiej/file"
  8. traffic_errors "apiote.xyz/p/szczanieckiej/traffic/errors"
  9. "apiote.xyz/p/szczanieckiej/transformers"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log"
  14. "net"
  15. "os"
  16. "path/filepath"
  17. "sort"
  18. "strings"
  19. "time"
  20. "golang.org/x/text/language"
  21. "golang.org/x/text/runes"
  22. "golang.org/x/text/transform"
  23. "git.sr.ht/~sircmpwn/go-bare"
  24. "github.com/dhconnelly/rtreego"
  25. "github.com/sahilm/fuzzy"
  26. "notabug.org/apiote/gott"
  27. )
  28. type OlcError struct {
  29. Value string
  30. Err error
  31. }
  32. func (e OlcError) Error() string {
  33. return e.Err.Error()
  34. }
  35. type _Result struct {
  36. Filename string
  37. Offset uint
  38. Date time.Time
  39. LineID string
  40. TimetableHome string
  41. Calendar []Schedule
  42. DeparturesType DeparturesType
  43. Vehicles Vehicles
  44. Feed Feed
  45. Ctx Context
  46. Traffic *Traffic
  47. Languages []language.Tag
  48. Location *time.Location
  49. Datetime time.Time
  50. MinuteB4Datetime time.Time
  51. TodaySchedule map[string]struct{}
  52. YesterdaySchedule map[string]struct{}
  53. file *os.File
  54. TripsFile *os.File
  55. Trips map[string]Trip
  56. Departures []DepartureRealtime
  57. Stop Stop
  58. Line Line
  59. Trip Trip
  60. FeedInfo FeedInfo
  61. }
  62. func isTimeout(err error) bool {
  63. var e net.Error
  64. return errors.As(err, &e) && e.Timeout()
  65. }
  66. func CleanQuery(query string, feed Feed) (string, error) {
  67. t := transform.Chain(runes.Remove(runes.Predicate(transformers.IsNonAlphanum)), feed.Transformer())
  68. queryCleaned, _, err := transform.String(t, query)
  69. return strings.ToLower(queryCleaned), err
  70. }
  71. func findSchedule(home string, time time.Time, calendar []Schedule) (map[string]struct{},
  72. error) {
  73. schedules := map[string]struct{}{}
  74. weekday := uint8(1 << time.Weekday())
  75. date := time.Format(DateFormat)
  76. for _, schedule := range calendar {
  77. for _, dateRange := range schedule.DateRanges {
  78. if dateRange.Start <= date && date <= dateRange.End &&
  79. (dateRange.Weekdays&weekday != 0) {
  80. schedules[schedule.Id] = struct{}{}
  81. break
  82. }
  83. }
  84. }
  85. var err error
  86. if len(schedules) == 0 {
  87. err = traffic_errors.NoSchedule{Date: date}
  88. }
  89. return schedules, err
  90. }
  91. func calculateGtfsTime(gtfsTime uint, delay int32, date time.Time,
  92. timezone *time.Location) time.Time {
  93. noon := time.Date(date.Year(), date.Month(), date.Day(), 12, 0, 0, 0,
  94. timezone)
  95. return noon.Add(time.Duration(-12) * time.Hour).Add(time.Duration(gtfsTime) * time.Second).Add(time.Duration(delay) * time.Second)
  96. }
  97. func loadLocation(input ...interface{}) (interface{}, error) {
  98. result := input[0].(_Result)
  99. var err error = nil
  100. result.Location, err = GetTimezone(result.Stop, result.Traffic, result.Ctx.FeedID)
  101. return result, err
  102. }
  103. func loadTime(input ...interface{}) interface{} {
  104. result := input[0].(_Result)
  105. now := time.Now()
  106. datetime := time.Date(result.Date.Year(), result.Date.Month(),
  107. result.Date.Day(), now.Hour(), now.Minute(), now.Second(), 0, now.Location()).In(result.Location)
  108. result.Datetime = datetime
  109. result.MinuteB4Datetime = datetime.Add(time.Duration(-1) * time.Minute)
  110. return result
  111. }
  112. func loadTodaySchedule(input ...interface{}) (interface{}, error) {
  113. result := input[0].(_Result)
  114. todaySchedule, err := findSchedule(result.TimetableHome, result.Date,
  115. result.Calendar)
  116. result.TodaySchedule = todaySchedule
  117. return result, err
  118. }
  119. func loadYesterdaySchedule(input ...interface{}) (interface{}, error) {
  120. result := input[0].(_Result)
  121. yesterday := result.Date.AddDate(0, 0, -1)
  122. yesterdaySchedule, err := findSchedule(result.TimetableHome, yesterday,
  123. result.Calendar)
  124. result.YesterdaySchedule = yesterdaySchedule
  125. return result, err
  126. }
  127. func recoverYesterdaySchedule(input ...interface{}) (interface{}, error) {
  128. result := input[0].(_Result)
  129. err := input[1].(error)
  130. dayBefore := result.Date.AddDate(0, 0, -1).Format(DateFormat)
  131. if err, ok := err.(traffic_errors.NoSchedule); ok && err.Date == dayBefore {
  132. result.YesterdaySchedule = map[string]struct{}{}
  133. return gott.Tuple{result}, nil
  134. }
  135. return gott.Tuple{result}, err
  136. }
  137. func openFile(input ...interface{}) (interface{}, error) {
  138. result := input[0].(_Result)
  139. file, err := os.Open(filepath.Join(result.TimetableHome, result.Filename))
  140. result.file = file
  141. return result, err
  142. }
  143. func seek(input ...interface{}) (interface{}, error) {
  144. result := input[0].(_Result)
  145. _, err := result.file.Seek(int64(result.Offset), 0)
  146. return result, err
  147. }
  148. func unmarshalStop(input ...interface{}) (interface{}, error) {
  149. result := input[0].(_Result)
  150. result.Stop = Stop{}
  151. err := bare.UnmarshalReader(result.file, &result.Stop)
  152. result.file.Close()
  153. return result, err
  154. }
  155. func unmarshalFeedInfo(input ...interface{}) (interface{}, error) {
  156. result := input[0].(_Result)
  157. result.FeedInfo = FeedInfo{}
  158. err := bare.UnmarshalReader(result.file, &result.FeedInfo)
  159. result.file.Close()
  160. return result, err
  161. }
  162. func unmarshalLine(input ...interface{}) (interface{}, error) {
  163. result := input[0].(_Result)
  164. result.Line = Line{}
  165. err := bare.UnmarshalReader(result.file, &result.Line)
  166. result.file.Close()
  167. return result, err
  168. }
  169. func unmarshalTrip(input ...interface{}) (interface{}, error) {
  170. result := input[0].(_Result)
  171. result.Trip = Trip{}
  172. err := bare.UnmarshalReader(result.file, &result.Trip)
  173. result.file.Close()
  174. return result, err
  175. }
  176. func openTripsFile(input ...interface{}) (interface{}, error) {
  177. result := input[0].(_Result)
  178. tripsFile, err := os.Open(filepath.Join(result.TimetableHome, "trips.bare"))
  179. result.TripsFile = tripsFile
  180. return result, err
  181. }
  182. func readTrips(input ...interface{}) (interface{}, error) {
  183. result := input[0].(_Result)
  184. trips := map[string]Trip{}
  185. orders := map[string]StopOrder{}
  186. for _, order := range result.Stop.Order {
  187. _, err := result.TripsFile.Seek(int64(order.TripOffset), 0)
  188. if err != nil {
  189. return result, err
  190. }
  191. trip := Trip{}
  192. err = bare.UnmarshalReader(result.TripsFile, &trip)
  193. if err != nil {
  194. return result, err
  195. }
  196. _, inToday := result.TodaySchedule[trip.ScheduleID]
  197. _, inYesterday := result.YesterdaySchedule[trip.ScheduleID]
  198. if inToday || inYesterday {
  199. trips[trip.Id] = trip
  200. orders[trip.Id] = order
  201. }
  202. }
  203. result.Stop.Order = orders
  204. result.Trips = trips
  205. return result, nil
  206. }
  207. func getDepartures(input ...interface{}) (interface{}, error) {
  208. result := input[0].(_Result)
  209. departures := []DepartureRealtime{}
  210. timedOut := false
  211. for tripID, order := range result.Stop.Order {
  212. trip := result.Trips[tripID]
  213. var date time.Time
  214. if _, ok := result.TodaySchedule[trip.ScheduleID]; ok {
  215. date = result.Date
  216. } else if _, ok := result.YesterdaySchedule[trip.ScheduleID]; ok {
  217. date = result.Date.AddDate(0, 0, -1)
  218. } else {
  219. continue
  220. }
  221. departure, err := getDeparture(date, result, order, trip, result.Feed, timedOut)
  222. if err != nil {
  223. if isTimeout(err) {
  224. timedOut = true
  225. err = nil
  226. } else {
  227. return result, err
  228. }
  229. }
  230. departures = append(departures, departure)
  231. }
  232. result.Departures = departures
  233. return result, nil
  234. }
  235. func makeDeparturesRealtime(input ...interface{}) (interface{}, error) {
  236. result := input[0].(_Result)
  237. departures, err := enrichDepartures(result.Stop.Id, result.Stop.Code, result.Departures, result.Datetime, result.DeparturesType, result.Ctx, result.TripsFile, result.Location, result.Languages)
  238. result.TripsFile.Close()
  239. result.Departures = departures
  240. return result, err
  241. }
  242. func addAlerts(input ...interface{}) interface{} {
  243. result := input[0].(_Result)
  244. alertedDepartures := make([]DepartureRealtime, len(result.Departures))
  245. for i, d := range result.Departures {
  246. if len(d.Alerts) == 0 {
  247. d.Alerts = GetAlerts("", "", int(d.Order.TripOffset), result.Ctx, result.Traffic, result.Languages)
  248. }
  249. alertedDepartures[i] = d
  250. }
  251. result.Departures = alertedDepartures
  252. return result
  253. }
  254. func getDeparture(date time.Time, result _Result, order StopOrder,
  255. trip Trip, feed Feed, timedOut bool) (DepartureRealtime, error) {
  256. found := false
  257. departureRt := DepartureRealtime{}
  258. var finalErr error
  259. for _, departure := range trip.Departures {
  260. if departure.StopSequence == order.Sequence {
  261. departureRt.Departure = departure
  262. departureRt.Headsign = trip.Headsign
  263. departureRt.LineID = trip.LineID
  264. departureRt.Order = order
  265. departureRt.Update = Update{}
  266. departureRt.Time = calculateGtfsTime(departure.Time, 0, date,
  267. result.Location)
  268. found = true
  269. break
  270. }
  271. }
  272. if !found {
  273. return departureRt, traffic_errors.NoStopOrder{
  274. TripID: trip.Id,
  275. Order: order.Sequence,
  276. }
  277. }
  278. return departureRt, finalErr
  279. }
  280. func GetTimeWithDelay(departure DepartureRealtime) time.Time {
  281. if departure.Update.TimeUTC != "" {
  282. updateTimeUTC, err := time.Parse("150405", departure.Update.Time)
  283. if err != nil {
  284. panic("departure update time ‘" + departure.Update.Time + "’ not in format 150405")
  285. }
  286. updateTime := time.Date(departure.Time.Year(), departure.Time.Month(), departure.Time.Day(), updateTimeUTC.Hour(), updateTimeUTC.Minute(), updateTimeUTC.Second(), 0, time.UTC)
  287. return updateTime.In(departure.Time.Location())
  288. } else if departure.Update.Time != "" {
  289. updateTime, err := time.Parse("150405", departure.Update.Time)
  290. if err != nil {
  291. panic("departure update time ‘" + departure.Update.Time + "’ not in format 150405")
  292. }
  293. updateDateTime := time.Date(departure.Time.Year(), departure.Time.Month(), departure.Time.Day(), updateTime.Hour(), updateTime.Minute(), updateTime.Second(), 0, departure.Time.Location())
  294. return updateDateTime
  295. } else {
  296. delay := int(departure.Update.Delay)
  297. return departure.Time.Add(time.Duration(delay) * time.Second)
  298. }
  299. }
  300. func filterDepartures(input ...interface{}) interface{} {
  301. result := input[0].(_Result)
  302. departures := []DepartureRealtime{}
  303. midnight := result.Date
  304. for _, departure := range result.Departures {
  305. if (result.DeparturesType == DEPARTURES_FULL && GetTimeWithDelay(departure).After(midnight)) || (result.DeparturesType == DEPARTURES_HYBRID && GetTimeWithDelay(departure).After(result.MinuteB4Datetime)) {
  306. departures = append(departures, departure)
  307. }
  308. }
  309. result.Departures = departures
  310. return result
  311. }
  312. func filterDeparturesByLine(input ...interface{}) interface{} {
  313. result := input[0].(_Result)
  314. departures := []DepartureRealtime{}
  315. if result.LineID != "" {
  316. for _, departure := range result.Departures {
  317. if departure.LineID == result.LineID {
  318. departures = append(departures, departure)
  319. }
  320. }
  321. result.Departures = departures
  322. }
  323. return result
  324. }
  325. func sortDepartures(input ...interface{}) interface{} {
  326. result := input[0].(_Result)
  327. sort.Slice(result.Departures, func(i, j int) bool {
  328. return GetTimeWithDelay(result.Departures[i]).Before(GetTimeWithDelay(result.Departures[j]))
  329. })
  330. return result
  331. }
  332. func closeFiles(input ...interface{}) (interface{}, error) {
  333. result := input[0].(_Result)
  334. err := input[1].(error)
  335. if result.file != nil {
  336. result.file.Close()
  337. }
  338. if result.TripsFile != nil {
  339. result.TripsFile.Close()
  340. }
  341. return result, err
  342. }
  343. func unmarshalCodeIndex(timetableHome, filename string) (CodeIndex, error) {
  344. ix := CodeIndex{}
  345. ixFile, err := os.Open(filepath.Join(timetableHome, filename))
  346. if err != nil {
  347. return ix, fmt.Errorf("while opening file: %w", err)
  348. }
  349. defer ixFile.Close()
  350. r := bare.NewReader(ixFile)
  351. num, err := r.ReadUint()
  352. if err != nil {
  353. return ix, fmt.Errorf("while reading length: %w", err)
  354. }
  355. for i := uint64(0); i < num; i++ {
  356. k, err := r.ReadString()
  357. if err != nil {
  358. return ix, fmt.Errorf("while reading key at %d: %w", i, err)
  359. }
  360. v, err := r.ReadUint()
  361. if err != nil {
  362. return ix, fmt.Errorf("while reading value at %d: %w", i, err)
  363. }
  364. ix[k] = uint(v)
  365. }
  366. return ix, nil
  367. }
  368. func unmarshalNameIndex(timetableHome, filename string) (NameIndex, error) {
  369. ix := NameIndex{}
  370. ixFile, err := os.Open(filepath.Join(timetableHome, filename))
  371. if err != nil {
  372. return ix, fmt.Errorf("while opening file: %w", err)
  373. }
  374. defer ixFile.Close()
  375. for err == nil {
  376. nameOffset := NameOffset{}
  377. err = bare.UnmarshalReader(ixFile, &nameOffset)
  378. if err != nil {
  379. if err == io.EOF {
  380. break
  381. } else {
  382. return ix, fmt.Errorf("while unmarshaling: %w", err)
  383. }
  384. }
  385. ix = append(ix, nameOffset)
  386. }
  387. return ix, nil
  388. }
  389. func unmarshalStopCodeIndex(timetableHome string) (CodeIndex, error) {
  390. return unmarshalCodeIndex(timetableHome, "ix_stop_codes.bare")
  391. }
  392. func unmarshalLineCodeIndex(timetableHome string) (CodeIndex, error) {
  393. return unmarshalCodeIndex(timetableHome, "ix_line_codes.bare")
  394. }
  395. func unmarshalLineIndex(timetableHome string) (NameIndex, error) {
  396. return unmarshalNameIndex(timetableHome, "ix_lines.bare")
  397. }
  398. func unmarshalStopNameIndex(timetableHome string) (NameIndex, error) {
  399. return unmarshalNameIndex(timetableHome, "ix_stop_names.bare")
  400. }
  401. func unmarshalTripIndex(timetableHome string) (NameIndex, error) {
  402. return unmarshalNameIndex(timetableHome, "ix_trips.bare")
  403. }
  404. func readIndexes(feedHome string, versions []Version) (FeedCodeIndex,
  405. FeedNameIndex, FeedNameIndex, FeedCodeIndex, FeedNameIndex, error) {
  406. codeIndex := FeedCodeIndex{}
  407. nameIndex := FeedNameIndex{}
  408. lineIndex := FeedNameIndex{}
  409. tripIndex := FeedNameIndex{}
  410. lineIdIndex := FeedCodeIndex{}
  411. for _, v := range versions {
  412. validity := Validity(v.String())
  413. timetableHome := filepath.Join(feedHome, string(validity))
  414. cIx, err := unmarshalStopCodeIndex(timetableHome)
  415. if err != nil {
  416. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex,
  417. fmt.Errorf("while unmarshalling code index: %w", err)
  418. }
  419. liIx, err := unmarshalLineCodeIndex(timetableHome)
  420. if err != nil {
  421. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex,
  422. fmt.Errorf("while unmarshalling code index: %w", err)
  423. }
  424. nIx, err := unmarshalStopNameIndex(timetableHome)
  425. if err != nil {
  426. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex,
  427. fmt.Errorf("while unmarshalling name index: %w", err)
  428. }
  429. lIx, err := unmarshalLineIndex(timetableHome)
  430. if err != nil {
  431. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex,
  432. fmt.Errorf("while unmarshalling line index: %w", err)
  433. }
  434. tIx, err := unmarshalTripIndex(timetableHome)
  435. if err != nil {
  436. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex,
  437. fmt.Errorf("while unmarshalling trip index: %w", err)
  438. }
  439. codeIndex[validity] = cIx
  440. nameIndex[validity] = nIx
  441. lineIndex[validity] = lIx
  442. lineIdIndex[validity] = liIx
  443. tripIndex[validity] = tIx
  444. }
  445. return codeIndex, nameIndex, lineIndex, lineIdIndex, tripIndex, nil
  446. }
  447. func unmarshalCalendar(timetableHome string) ([]Schedule, error) {
  448. calendar := []Schedule{}
  449. calendarFile, err := os.Open(filepath.Join(timetableHome, "calendar.bare"))
  450. if err != nil {
  451. return calendar, fmt.Errorf("while opening file: %w", err)
  452. }
  453. defer calendarFile.Close()
  454. for err == nil {
  455. schedule := Schedule{}
  456. err = bare.UnmarshalReader(calendarFile, &schedule)
  457. if err != nil {
  458. if err == io.EOF {
  459. break
  460. } else {
  461. return calendar, fmt.Errorf("while unmarshaling: %w", err)
  462. }
  463. }
  464. calendar = append(calendar, schedule)
  465. }
  466. return calendar, nil
  467. }
  468. func readCalendar(feedHome string, versions []Version) (FeedCalendar, error) {
  469. calendars := FeedCalendar{}
  470. for _, v := range versions {
  471. validity := Validity(v.String())
  472. timetableHome := filepath.Join(feedHome, string(validity))
  473. schedule, err := unmarshalCalendar(timetableHome)
  474. if err != nil {
  475. return calendars, fmt.Errorf("while unmarshaling for %s: %w", v, err)
  476. }
  477. calendars[validity] = schedule
  478. }
  479. return calendars, nil
  480. }
  481. func unmarshalVehicles(timetableHome string) (Vehicles, error) {
  482. vehicles := Vehicles{}
  483. vehiclesFile, err := os.Open(filepath.Join(timetableHome, "vehicles.bare"))
  484. if err != nil {
  485. return vehicles, fmt.Errorf("while opening file: %w", err)
  486. }
  487. defer vehiclesFile.Close()
  488. for err == nil {
  489. vehicle := Vehicle{}
  490. err = bare.UnmarshalReader(vehiclesFile, &vehicle)
  491. if err != nil {
  492. if err == io.EOF {
  493. break
  494. } else {
  495. return vehicles, fmt.Errorf("while unmarshaling: %w", err)
  496. }
  497. }
  498. vehicles[vehicle.Id] = vehicle
  499. }
  500. return vehicles, nil
  501. }
  502. func readVehicles(feedHome string, versions []Version) (FeedVehicles, error) {
  503. vehicles := FeedVehicles{}
  504. for _, v := range versions {
  505. validity := Validity(v.String())
  506. timetableHome := filepath.Join(feedHome, string(validity))
  507. versionVehicles, err := unmarshalVehicles(timetableHome)
  508. if err != nil {
  509. return vehicles, fmt.Errorf("while unmarshaling for %s: %w", v, err)
  510. }
  511. vehicles[validity] = versionVehicles
  512. }
  513. return vehicles, nil
  514. }
  515. func createPositionIndex(feedHome string, versions []Version) (FeedPositionIndex, error) {
  516. feedPositionIndex := FeedPositionIndex{}
  517. for _, v := range versions {
  518. positionIndex := rtreego.NewTree(2, 25, 50)
  519. validity := Validity(v.String())
  520. timetableHome := filepath.Join(feedHome, string(validity))
  521. stopsFile, err := os.Open(filepath.Join(timetableHome, "stops.bare"))
  522. if err != nil {
  523. return feedPositionIndex, fmt.Errorf("while opening stops file: %w", err)
  524. }
  525. defer stopsFile.Close()
  526. for err == nil {
  527. stop := Stop{}
  528. err = bare.UnmarshalReader(stopsFile, &stop)
  529. if err != nil {
  530. if err == io.EOF {
  531. break
  532. } else {
  533. return feedPositionIndex, fmt.Errorf("while unmarshaling: %w", err)
  534. }
  535. }
  536. stop.Name = ""
  537. stop.NodeName = ""
  538. stop.ChangeOptions = nil
  539. stop.Zone = ""
  540. stop.Order = nil
  541. positionIndex.Insert(stop)
  542. feedPositionIndex[validity] = positionIndex
  543. }
  544. }
  545. return feedPositionIndex, nil
  546. }
  547. func unmarshalTripFromFile(tripsFile *os.File) Trip {
  548. trip := Trip{}
  549. _ = bare.UnmarshalReader(tripsFile, &trip)
  550. return trip
  551. }
  552. func EnableFeeds(cfg config.Config, traffic *Traffic) {
  553. feedsMap := RegisterFeeds()
  554. feeds := map[string]Feed{}
  555. for _, enabledFeed := range cfg.EnabledFeeds {
  556. if _, ok := feedsMap[enabledFeed]; !ok {
  557. log.Printf("feed %s not registered, ignoring\n", enabledFeed)
  558. continue
  559. }
  560. feeds[enabledFeed] = feedsMap[enabledFeed]
  561. }
  562. traffic.Feeds = feeds
  563. }
  564. func Initialise(sigChan chan os.Signal, doneChan chan bool, initedChan chan bool, cfg config.Config,
  565. traffic *Traffic) {
  566. bare.MaxMapSize(12288)
  567. alreadyInitialised := false
  568. for {
  569. sig := <-sigChan
  570. if sig == os.Interrupt {
  571. break
  572. } // else it's SIGUSR1, reloading config
  573. allVersions := GlobalVersions{}
  574. codeIndexes := GlobalCodeIndex{}
  575. nameIndexes := GlobalNameIndex{}
  576. lineIndexes := GlobalNameIndex{}
  577. lineIdIndexes := GlobalCodeIndex{}
  578. tripIndexes := GlobalNameIndex{}
  579. calendars := GlobalCalendar{}
  580. vehicles := GlobalVehicles{}
  581. positionIndexes := GlobalPositionIndex{}
  582. feedInfos := map[Validity]map[string]FeedInfo{}
  583. for _, feed := range traffic.Feeds {
  584. feedID := feed.String()
  585. feedHome := filepath.Join(cfg.FeedsPath, feedID)
  586. err := file.UnpackTraffic(cfg.FeedsPath, feedID)
  587. if err != nil {
  588. log.Printf("while unpacking TRAFFIC in feed %s: %v\n", feed, err)
  589. continue
  590. }
  591. feedValidities, err := ListVersions(cfg, feed)
  592. if err != nil {
  593. log.Printf("while listing TRAFFIC versions in feed %s: %v\n", feed, err)
  594. continue
  595. }
  596. for _, version := range feedValidities {
  597. feedInfo, err := getFeedInfo(cfg.FeedsPath, feedID, Validity(version))
  598. if err != nil {
  599. log.Printf("while getting feed info for feed %s, version %s: %v\n", feed, version, err)
  600. continue
  601. }
  602. if feedInfos[Validity(feedInfo.ValidSince+"_"+feedInfo.ValidTill)] == nil {
  603. feedInfos[Validity(feedInfo.ValidSince+"_"+feedInfo.ValidTill)] = map[string]FeedInfo{}
  604. }
  605. feedInfos[Validity(feedInfo.ValidSince+"_"+feedInfo.ValidTill)][feedID] = feedInfo
  606. }
  607. traffic.FeedInfos = feedInfos
  608. feedVersions, deletedValidities, err := CleanOldVersions(cfg, feed, traffic, feedID, feedValidities)
  609. if err != nil {
  610. log.Printf("while cleaning old TRAFFIC versions in feed %s: %v\n",
  611. feed, err)
  612. continue
  613. }
  614. for _, deletedVersion := range deletedValidities {
  615. delete(feedInfos, Validity(deletedVersion))
  616. }
  617. allVersions[feedID] = feedVersions
  618. codeIndexes[feedID], nameIndexes[feedID], lineIndexes[feedID], lineIdIndexes[feedID], tripIndexes[feedID],
  619. err = readIndexes(feedHome, feedVersions)
  620. if err != nil {
  621. log.Printf("while reading indexes in feed %s: %v\n", feed, err)
  622. continue
  623. }
  624. calendars[feedID], err = readCalendar(feedHome, feedVersions)
  625. if err != nil {
  626. log.Printf("while reading calendars in feed %s: %v\n", feed, err)
  627. continue
  628. }
  629. vehicles[feedID], err = readVehicles(feedHome, feedVersions)
  630. if err != nil {
  631. log.Printf("while reading vehicles in feed %s: %v\n", feed, err)
  632. continue
  633. }
  634. positionIndexes[feedID], err = createPositionIndex(feedHome, feedVersions)
  635. if err != nil {
  636. log.Printf("while creating position index in feed %s: %v\n", feed, err)
  637. continue
  638. }
  639. }
  640. traffic.CodeIndexes = codeIndexes
  641. traffic.NameIndexes = nameIndexes
  642. traffic.LineIndexes = lineIndexes
  643. traffic.LineIdIndexes = lineIdIndexes
  644. traffic.TripIndexes = tripIndexes
  645. traffic.Versions = allVersions
  646. traffic.Calendars = calendars
  647. traffic.Vehicles = vehicles
  648. traffic.PositionIndexes = positionIndexes
  649. traffic.FeedInfos = feedInfos
  650. log.Println("Initialised")
  651. if !alreadyInitialised {
  652. initedChan <- true
  653. }
  654. }
  655. doneChan <- true
  656. }
  657. func GetDepartures(stopCode, lineID string, ctx Context, traffic *Traffic, date time.Time,
  658. departuresType DeparturesType, languages []language.Tag) ([]DepartureRealtime, error) {
  659. codeIndex := traffic.CodeIndexes[ctx.FeedID][ctx.Version]
  660. calendar := traffic.Calendars[ctx.FeedID][ctx.Version]
  661. vehicles := traffic.Vehicles[ctx.FeedID][ctx.Version]
  662. result := _Result{
  663. Offset: codeIndex[stopCode],
  664. Filename: "stops.bare",
  665. Date: date,
  666. LineID: lineID,
  667. TimetableHome: filepath.Join(ctx.DataHome, ctx.FeedID, string(ctx.Version)),
  668. Calendar: calendar,
  669. DeparturesType: departuresType,
  670. Vehicles: vehicles,
  671. Feed: traffic.Feeds[ctx.FeedID],
  672. Ctx: ctx,
  673. Traffic: traffic,
  674. Languages: languages,
  675. }
  676. r, e := gott.NewResult(result).
  677. Bind(loadLocation).
  678. Map(loadTime).
  679. Bind(loadTodaySchedule).
  680. Bind(loadYesterdaySchedule).
  681. Recover(recoverYesterdaySchedule).
  682. Bind(openFile).
  683. Bind(seek).
  684. Bind(unmarshalStop).
  685. Bind(openTripsFile).
  686. Bind(readTrips).
  687. Bind(getDepartures).
  688. Bind(makeDeparturesRealtime).
  689. Map(addAlerts).
  690. Map(filterDepartures).
  691. Map(filterDeparturesByLine).
  692. Map(sortDepartures).
  693. Recover(closeFiles).
  694. Finish()
  695. if e != nil {
  696. return []DepartureRealtime{}, e
  697. } else {
  698. return r.(_Result).Departures, nil
  699. }
  700. }
  701. func GetTripFromStop(tripID string, stopCode string, context Context, traffic *Traffic) ([]TimedStopStub, error) {
  702. stubs := []TimedStopStub{}
  703. var (
  704. order = -1
  705. trip Trip
  706. err error
  707. baseTime uint = 0
  708. time uint = 0
  709. )
  710. if stopCode != "" {
  711. startingStop, err := GetStop(stopCode, context, traffic)
  712. if err != nil {
  713. return stubs, fmt.Errorf("while getting starting stop: %w", err)
  714. }
  715. tripOffset := -1
  716. order = -1
  717. o := startingStop.Order[tripID]
  718. tripOffset = int(o.TripOffset)
  719. order = o.Sequence
  720. if tripOffset == -1 {
  721. return stubs, fmt.Errorf("trip for starting stop not found")
  722. }
  723. trip, err = GetTripByOffset(uint(tripOffset), context, traffic)
  724. if err != nil {
  725. return stubs, fmt.Errorf("while getting trip: %w", err)
  726. }
  727. } else {
  728. trip, err = GetTrip(tripID, context, traffic)
  729. if err != nil {
  730. return stubs, fmt.Errorf("while getting trip: %w", err)
  731. }
  732. }
  733. for _, departure := range trip.Departures {
  734. if departure.StopSequence >= order {
  735. stop, err := getStopByOffset(uint(departure.StopOffset), context, traffic)
  736. if err != nil {
  737. return stubs, fmt.Errorf("while getting stop: %w", err)
  738. }
  739. if baseTime != 0 {
  740. time = departure.Time - baseTime
  741. }
  742. stubs = append(stubs, TimedStopStub{
  743. StopStub: StopStub{
  744. Code: stop.Code,
  745. Name: stop.Name,
  746. NodeName: stop.NodeName,
  747. Zone: stop.Zone,
  748. OnDemand: departure.Pickup == BY_DRIVER || departure.Dropoff == BY_DRIVER,
  749. },
  750. Time: time,
  751. })
  752. }
  753. }
  754. return stubs, nil
  755. }
  756. func getStopByOffset(offset uint, context Context, traffic *Traffic) (Stop, error) { // todo offset should be uint64 everywhere
  757. result := _Result{
  758. Filename: "stops.bare",
  759. Offset: offset,
  760. TimetableHome: filepath.Join(context.DataHome, context.FeedID, string(context.Version)),
  761. }
  762. r, e := gott.NewResult(result).
  763. Bind(openFile).
  764. Bind(seek).
  765. Bind(unmarshalStop).
  766. Finish()
  767. if e != nil {
  768. return Stop{}, e
  769. } else {
  770. return r.(_Result).Stop, nil
  771. }
  772. }
  773. func getLineByOffset(offset uint, dataHome string, feedName string,
  774. versionCode Validity) (Line, error) {
  775. result := _Result{
  776. Filename: "lines.bare",
  777. Offset: offset,
  778. TimetableHome: filepath.Join(dataHome, feedName, string(versionCode)),
  779. }
  780. r, e := gott.NewResult(result).
  781. Bind(openFile).
  782. Bind(seek).
  783. Bind(unmarshalLine).
  784. Finish()
  785. if e != nil {
  786. return Line{}, e
  787. } else {
  788. return r.(_Result).Line, nil
  789. }
  790. }
  791. func getFeedInfo(dataHome string, feedName string, versionCode Validity) (FeedInfo, error) {
  792. result := _Result{
  793. Filename: "feed_info.bare",
  794. TimetableHome: filepath.Join(dataHome, feedName, string(versionCode)),
  795. }
  796. r, e := gott.NewResult(result).
  797. Bind(openFile).
  798. Bind(unmarshalFeedInfo).
  799. Finish()
  800. if e != nil {
  801. return FeedInfo{}, e
  802. } else {
  803. return r.(_Result).FeedInfo, nil
  804. }
  805. }
  806. func GetTrips(ids []string, ctx Context, t *Traffic) (map[string]Trip, error) {
  807. idMap := map[string]struct{}{}
  808. for _, id := range ids {
  809. idMap[id] = struct{}{}
  810. }
  811. offsets := []uint{}
  812. tripIndex := t.TripIndexes[ctx.FeedID][ctx.Version]
  813. for _, o := range tripIndex {
  814. if _, ok := idMap[o.Name]; ok {
  815. offsets = append(offsets, o.Offsets[0])
  816. }
  817. }
  818. trips, err := GetTripsByOffset(offsets, ctx, func(_ Trip) bool { return true })
  819. resultTrips := map[string]Trip{}
  820. for _, trip := range trips {
  821. resultTrips[trip.Id] = trip
  822. }
  823. return resultTrips, err
  824. }
  825. func GetTripsByOffset(offsets []uint, context Context, filter func(Trip) bool) (map[uint]Trip, error) {
  826. trips := map[uint]Trip{}
  827. file, err := os.Open(filepath.Join(context.DataHome, context.FeedID, string(context.Version), "trips.bare"))
  828. if err != nil {
  829. return trips, fmt.Errorf("while opening file: %w", err)
  830. }
  831. defer file.Close()
  832. offsetsSet := map[uint]struct{}{}
  833. for _, offset := range offsets {
  834. offsetsSet[offset] = struct{}{}
  835. }
  836. for offset := range offsetsSet {
  837. _, err = file.Seek(int64(offset), 0)
  838. if err != nil {
  839. return trips, fmt.Errorf("while seeking to %d: %w", offset, err)
  840. }
  841. trip := Trip{}
  842. err = bare.UnmarshalReader(file, &trip)
  843. if err != nil {
  844. return trips, fmt.Errorf("while unmarshalling at %d: %w", offset, err)
  845. }
  846. if filter(trip) {
  847. trips[offset] = trip
  848. }
  849. }
  850. return trips, nil
  851. }
  852. func GetTripByOffset(offset uint, context Context, t *Traffic) (Trip, error) {
  853. result := _Result{
  854. Filename: "trips.bare",
  855. Offset: offset,
  856. TimetableHome: filepath.Join(context.DataHome, context.FeedID, string(context.Version)),
  857. }
  858. r, e := gott.NewResult(result).
  859. Bind(openFile).
  860. Bind(seek).
  861. Bind(unmarshalTrip).
  862. Finish()
  863. if e != nil {
  864. return Trip{}, e
  865. } else {
  866. return r.(_Result).Trip, nil
  867. }
  868. }
  869. func GetStop(stopCode string, context Context, traffic *Traffic) (Stop, error) {
  870. codeIndex := traffic.CodeIndexes[context.FeedID][context.Version]
  871. return getStopByOffset(codeIndex[stopCode], context, traffic)
  872. }
  873. func GetStopStub(stopCode string, lineID string, context Context, traffic *Traffic) (StopStub, error) {
  874. stop, err := GetStop(stopCode, context, traffic)
  875. if err != nil {
  876. return StopStub{}, err
  877. }
  878. var trip Trip
  879. var stopOrder = -1
  880. for _, order := range stop.Order {
  881. offset := order.TripOffset
  882. trip, _ = GetTripByOffset(offset, context, traffic)
  883. if trip.LineID == lineID {
  884. stopOrder = order.Sequence
  885. break
  886. }
  887. }
  888. if stopOrder == -1 {
  889. return StopStub{}, fmt.Errorf("cannot the stop on given line")
  890. }
  891. var departure *Departure
  892. for _, d := range trip.Departures {
  893. if d.StopSequence == stopOrder { // todo binary search
  894. departure = &d
  895. break
  896. }
  897. }
  898. if departure == nil {
  899. return StopStub{}, fmt.Errorf("cannot find departure at sequence %d", stopOrder)
  900. }
  901. stopStub := StopStub{
  902. Code: stop.Code,
  903. Name: stop.Name,
  904. NodeName: stop.NodeName,
  905. Zone: stop.Zone,
  906. OnDemand: departure.Pickup == BY_DRIVER || departure.Dropoff == BY_DRIVER,
  907. }
  908. return stopStub, nil
  909. }
  910. func GetLine(id string, context Context, traffic *Traffic) (Line, error) {
  911. index := traffic.LineIdIndexes[context.FeedID][context.Version]
  912. return getLineByOffset(index[id], context.DataHome, context.FeedID, context.Version)
  913. }
  914. func GetLineOld(name string, context Context, traffic *Traffic) (Line, error) {
  915. index := traffic.LineIndexes[context.FeedID][context.Version]
  916. for _, o := range index {
  917. cleanedName, err := CleanQuery(name, traffic.Feeds[context.FeedID])
  918. if err != nil {
  919. return Line{}, err
  920. }
  921. if o.Name == cleanedName {
  922. return getLineByOffset(o.Offsets[0], context.DataHome, context.FeedID, context.Version)
  923. }
  924. }
  925. return Line{}, nil
  926. }
  927. func GetTrip(id string, context Context, traffic *Traffic) (Trip, error) {
  928. tripIndex := traffic.TripIndexes[context.FeedID][context.Version]
  929. for _, o := range tripIndex {
  930. if o.Name == id {
  931. return GetTripByOffset(o.Offsets[0], context, traffic)
  932. }
  933. }
  934. return Trip{}, fmt.Errorf("trip by id %s not found", id)
  935. }
  936. func QueryLines(query string, dataHome string, feedName string,
  937. versionCode Validity, traffic *Traffic) ([]Line, error) {
  938. linesSet := map[string]Line{}
  939. index := traffic.LineIndexes[feedName][versionCode]
  940. cleanQuery, err := CleanQuery(query, traffic.Feeds[feedName])
  941. if err != nil {
  942. return []Line{}, fmt.Errorf("while cleaning query: %w", err)
  943. }
  944. results := fuzzy.FindFrom(cleanQuery, index)
  945. for _, result := range results {
  946. for _, offset := range index[result.Index].Offsets {
  947. line, err := getLineByOffset(offset, dataHome, feedName, versionCode)
  948. if err != nil {
  949. return []Line{}, fmt.Errorf("while getting line for %s: %w", result.Str, err)
  950. }
  951. linesSet[line.Id] = line
  952. }
  953. }
  954. lines := make([]Line, len(linesSet))
  955. i := 0
  956. for _, line := range linesSet {
  957. lines[i] = line
  958. i++
  959. }
  960. return lines, nil
  961. }
  962. func QueryStops(query string, context Context, traffic *Traffic) ([]Stop, error) {
  963. stopsSet := map[string]Stop{}
  964. nameIndex := traffic.NameIndexes[context.FeedID][context.Version]
  965. results := fuzzy.FindFrom(query, nameIndex)
  966. for _, result := range results {
  967. for _, offset := range nameIndex[result.Index].Offsets {
  968. stop, err := getStopByOffset(offset, context, traffic)
  969. if err != nil {
  970. return []Stop{}, err
  971. }
  972. stopsSet[stop.Id] = stop
  973. }
  974. }
  975. stops := make([]Stop, len(stopsSet))
  976. i := 0
  977. for _, stop := range stopsSet {
  978. stops[i] = stop
  979. i++
  980. }
  981. return stops, nil
  982. }
  983. func GetStopsNear(location Position, context Context, traffic *Traffic) ([]Stop, error) {
  984. stops := []Stop{}
  985. positionIndex := traffic.PositionIndexes[context.FeedID][context.Version]
  986. codeIndex := traffic.CodeIndexes[context.FeedID][context.Version]
  987. spatials := positionIndex.NearestNeighbors(12, rtreego.Point{location.Lat, location.Lon})
  988. for _, spatial := range spatials {
  989. stop, err := getStopByOffset(codeIndex[spatial.(Stop).Code], context, traffic)
  990. if err != nil {
  991. return stops, fmt.Errorf("while getting stop by offset for %s: %w", spatial.(Stop).Code, err)
  992. }
  993. stops = append(stops, stop)
  994. }
  995. return stops, nil
  996. }
  997. func GetLanguage(ctx Context) (string, error) {
  998. feedInfo, err := getFeedInfo(ctx.DataHome, ctx.FeedID, ctx.Version)
  999. return feedInfo.Language, err
  1000. }
  1001. func CleanOldVersions(cfg config.Config, feed Feed, t *Traffic, feedID string, allValidities []string) ([]Version, []string, error) {
  1002. feedVersions := []Version{}
  1003. deletedValidities := []string{}
  1004. timezone, err := GetTimezone(Stop{}, t, feedID)
  1005. if err != nil {
  1006. return feedVersions, deletedValidities, fmt.Errorf("while getting timezone: %w", err)
  1007. }
  1008. now := time.Now().In(timezone)
  1009. versionsMap := map[string]Version{}
  1010. allVersions := []Version{}
  1011. for _, validity := range allValidities {
  1012. version, err := MakeVersionTimezone(validity, timezone)
  1013. if err != nil {
  1014. return feedVersions, deletedValidities, fmt.Errorf("while making version of %s: %w", version, err)
  1015. }
  1016. allVersions = append(allVersions, version)
  1017. versionsMap[validity] = version
  1018. }
  1019. validVersions := FindValidVersions(allVersions, now)
  1020. validVersionsMap := map[string]bool{}
  1021. for _, version := range validVersions {
  1022. validVersionsMap[version.String()] = true
  1023. }
  1024. err = file.CleanOldVersions(FeedPath(cfg, feed), validVersionsMap)
  1025. if err != nil {
  1026. return feedVersions, deletedValidities, fmt.Errorf("while removing files: %w", err)
  1027. }
  1028. for _, version := range validVersions {
  1029. feedVersions = append(feedVersions, version)
  1030. }
  1031. for _, version := range allVersions {
  1032. if _, ok := validVersionsMap[version.String()]; !ok {
  1033. deletedValidities = append(deletedValidities, version.String())
  1034. }
  1035. }
  1036. return feedVersions, deletedValidities, nil
  1037. }
  1038. func createSmallerRect(side float64, rect *rtreego.Rect) (*rtreego.Rect, Position, Position, error) {
  1039. halfSide := side / 2
  1040. latMid := rect.PointCoord(0) + (rect.LengthsCoord(0) / 2)
  1041. lonMid := rect.PointCoord(1) + (rect.LengthsCoord(1) / 2)
  1042. lb := Position{Lat: latMid - halfSide, Lon: lonMid - halfSide}
  1043. rt := Position{Lat: latMid + halfSide, Lon: lonMid + halfSide}
  1044. rect, err := rtreego.NewRectFromPoints(rtreego.Point{lb.Lat, lb.Lon}, rtreego.Point{rt.Lat, rt.Lon})
  1045. return rect, lb, rt, err
  1046. }
  1047. func GetStopsIn(lb, rt Position, context Context, traffic *Traffic) ([]Stop, error) {
  1048. limit := 0.0005
  1049. side := 0.0224 // sqrt(0.0005)
  1050. stops := []Stop{}
  1051. // TODO does it take into account rect 179 -> -179 latitude?
  1052. rect, err := rtreego.NewRectFromPoints(rtreego.Point{lb.Lat, lb.Lon}, rtreego.Point{rt.Lat, rt.Lon})
  1053. if err != nil {
  1054. return stops, fmt.Errorf("while creating a rect: %w", err)
  1055. }
  1056. if rect.Size() > limit {
  1057. rect, _, _, err = createSmallerRect(side, rect)
  1058. if err != nil {
  1059. return stops, fmt.Errorf("while creating the smaller rect: %w", err)
  1060. }
  1061. }
  1062. positionIndex := traffic.PositionIndexes[context.FeedID][context.Version]
  1063. codeIndex := traffic.CodeIndexes[context.FeedID][context.Version]
  1064. spatials := positionIndex.SearchIntersect(rect)
  1065. for _, spatial := range spatials {
  1066. stop, err := getStopByOffset(codeIndex[spatial.(Stop).Code], context, traffic)
  1067. if err != nil {
  1068. return stops, fmt.Errorf("while getting stop by offset for %s: %w", spatial.(Stop).Code, err)
  1069. }
  1070. stops = append(stops, stop)
  1071. }
  1072. return stops, nil
  1073. }
  1074. func GetVehiclesIn(lb, rt Position, context Context, t *Traffic) ([]VehicleStatus, error) {
  1075. limit := 0.0005
  1076. side := 0.0224 // sqrt(0.0005)
  1077. rect, err := rtreego.NewRectFromPoints(rtreego.Point{lb.Lat, lb.Lon}, rtreego.Point{rt.Lat, rt.Lon})
  1078. if err != nil {
  1079. return []VehicleStatus{}, fmt.Errorf("while creating a rect: %w", err)
  1080. }
  1081. if rect.Size() > limit {
  1082. rect, lb, rt, err = createSmallerRect(side, rect)
  1083. if err != nil {
  1084. return []VehicleStatus{}, fmt.Errorf("while creating the smaller rect: %w", err)
  1085. }
  1086. }
  1087. vehicles := getVehiclePositions(context, t, lb, rt)
  1088. return vehicles, nil
  1089. }