Handle new special route listing for mtr buses

This commit is contained in:
2025-12-16 11:10:27 +08:00
parent 0ed4c618dc
commit 6e94adbed4
3 changed files with 250 additions and 239 deletions

View File

@@ -6,6 +6,7 @@ import (
type BusStop struct {
RouteId string
ReferenceId string
Direction string
StationSeq int
StationId string
@@ -15,40 +16,40 @@ type BusStop struct {
Name_en string
// RouteStops[ StationSeq ] = BusStop
RouteStops *map[int] *BusStop
RouteStops *map[int]*BusStop
i18n.Generics
}
func ( this *BusStop ) PrevStop() *BusStop {
if v, hasKey := (*this.RouteStops)[ this.StationSeq - 1 ]; hasKey {
func (this *BusStop) PrevStop() *BusStop {
if v, hasKey := (*this.RouteStops)[this.StationSeq-1]; hasKey {
return v
}
return nil
}
func ( this *BusStop ) NextStop() *BusStop {
if v, hasKey := (*this.RouteStops)[ this.StationSeq + 1 ]; hasKey {
func (this *BusStop) NextStop() *BusStop {
if v, hasKey := (*this.RouteStops)[this.StationSeq+1]; hasKey {
return v
}
return nil
}
func ( this *BusStop ) Reload() {
i18n_Name := map[string] string{}
func (this *BusStop) Reload() {
i18n_Name := map[string]string{}
i18n_Name["en"] = this.Name_en
i18n_Name["zh-Hant"] = this.Name_zh
searchData := [] *string{}
searchData = append( searchData, &this.Name_en )
searchData = append( searchData, &this.Name_zh )
searchData := []*string{}
searchData = append(searchData, &this.Name_en)
searchData = append(searchData, &this.Name_zh)
this.Name = &i18n_Name
this.Key = &this.RouteId
this.SearchData = &searchData
}
type ByRoute [] *BusStop
type ByRoute []*BusStop
func (a ByRoute) Len() int { return len(a) }
func (a ByRoute) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

View File

@@ -1,9 +1,9 @@
package bus
import (
"fmt"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
@@ -31,7 +31,7 @@ type Bus struct {
}
type BusStopBuses struct {
Buses [] Bus `json:"bus"`
Buses []Bus `json:"bus"`
BusStopId string `json:"busStopId"`
Suspended string `json:"isSuspended"`
}
@@ -42,7 +42,7 @@ type ScheduleStatusTime struct {
type BusSchedule struct {
RefreshTime int `json:"appRefreshTimeInSecond,string"`
BusStops [] BusStopBuses `json:"busStop"`
BusStops []BusStopBuses `json:"busStop"`
StatusTime ScheduleStatusTime `json:"routeStatusTime"`
RemarksTitle string `json:"routeStatusRemarkTitle"`
// 0 = OK
@@ -59,11 +59,11 @@ func (t *ScheduleStatusTime) UnmarshalJSON(b []byte) (err error) {
return
}
func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
func getSchedule(lang string, routeName string) (*BusSchedule, error) {
CACHE_PATH := filepath.Join(
utils.WORKDIR,
"mtr_bsch" + "-" + lang + "-" + routeName + ".json",
"mtr_bsch"+"-"+lang+"-"+routeName+".json",
)
postLang := "en"
@@ -71,14 +71,14 @@ func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
postLang = "zh"
}
QUERY_FUNC := func() ( io.ReadCloser, error ) {
QUERY_FUNC := func() (io.ReadCloser, error) {
// Query Remote
values := map[string]string { "language": postLang, "routeName": routeName }
values := map[string]string{"language": postLang, "routeName": routeName}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post(
"https://rt.data.gov.hk/v1/transport/mtr/bus/getSchedule",
"application/json",
bytes.NewBuffer( jsonValue ),
bytes.NewBuffer(jsonValue),
)
if err != nil {
@@ -88,7 +88,7 @@ func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
return resp.Body, nil
}
cs, err := utils.CacheStreamEx( CACHE_PATH, QUERY_FUNC )
cs, err := utils.CacheStreamEx(CACHE_PATH, QUERY_FUNC)
if err != nil {
return nil, err
}
@@ -98,7 +98,7 @@ func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
}
if cs.Local != nil {
err = json.Unmarshal( cs.Local.Bytes(), &oldSch )
err = json.Unmarshal(cs.Local.Bytes(), &oldSch)
if err != nil {
return nil, err
}
@@ -108,10 +108,10 @@ func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
Status: -1,
}
for i := 0; i < 3; i ++ {
for i := 0; i < 3; i++ {
if cs.Remote != nil {
err = json.Unmarshal( cs.Remote.Bytes(), &newSch )
err = json.Unmarshal(cs.Remote.Bytes(), &newSch)
if err != nil {
return nil, err
}
@@ -123,23 +123,23 @@ func getSchedule( lang string, routeName string ) ( *BusSchedule, error ) {
}
if oldSch.Status == 0 {
if cs.NotExpired( 60 ) || oldSch.StatusTime.Time == newSch.StatusTime.Time {
log.Printf( "Using cache: %s", CACHE_PATH )
if cs.NotExpired(60) || oldSch.StatusTime.Time == newSch.StatusTime.Time {
log.Printf("Using cache: %s", CACHE_PATH)
return &oldSch, nil
}
}
// First time + try again i times
err = cs.Reload()
log.Printf( "Reloading (%d): %s", i, CACHE_PATH )
log.Printf("Reloading (%d): %s", i, CACHE_PATH)
if err != nil {
err = fmt.Errorf( "Error retrieving data: %s", err )
err = fmt.Errorf("Error retrieving data: %s", err)
return nil, err
}
}
if newSch.Status != 0 {
err = fmt.Errorf( "%s (%d)", newSch.RemarksTitle, newSch.Status )
err = fmt.Errorf("%s (%d)", newSch.RemarksTitle, newSch.Status)
}
return &newSch, err

View File

@@ -4,6 +4,7 @@ import (
"encoding/csv"
"fmt"
"io"
"log"
"net/http"
"path/filepath"
"strconv"
@@ -12,18 +13,18 @@ import (
"github.com/tgckpg/golifehk/utils"
)
var CSV_BUSSTOPS string = filepath.Join( utils.WORKDIR, "mtr_bus_stops.csv" )
var CSV_BUSSTOPS string = filepath.Join(utils.WORKDIR, "mtr_bus_stops.csv")
func readBusStopData( r io.Reader ) ( *map[string] *BusStop, error ) {
func readBusStopData(r io.Reader) (*map[string]*BusStop, error) {
reader := csv.NewReader( r )
reader := csv.NewReader(r)
entries, err := reader.ReadAll()
if err != nil {
return nil, err
}
busStops := map[string] *BusStop{}
routeStops := map[string] map[string] map[int] *BusStop{}
busStops := map[string]*BusStop{}
routeStops := map[string]map[string]map[int]*BusStop{}
var headers []string
for i, line := range entries {
@@ -41,78 +42,87 @@ func readBusStopData( r io.Reader ) ( *map[string] *BusStop, error ) {
case "DIRECTION":
entry.Direction = value
case "STATION_SEQNO":
v, _ := strconv.ParseFloat( value, 64 )
entry.StationSeq = int( v )
v, _ := strconv.ParseFloat(value, 64)
entry.StationSeq = int(v)
case "STATION_ID":
entry.StationId = value
case "STATION_LATITUDE":
v, _ := strconv.ParseFloat( value, 64 )
v, _ := strconv.ParseFloat(value, 64)
entry.Latitude = v
case "STATION_LONGITUDE":
v, _ := strconv.ParseFloat( value, 64 )
v, _ := strconv.ParseFloat(value, 64)
entry.Longtitude = v
case "STATION_NAME_CHI":
entry.Name_zh = value
case "STATION_NAME_ENG":
entry.Name_en = value
case "REFERENCE_ID":
entry.ReferenceId = value
default:
return nil, fmt.Errorf( "Unknown header \"%s\"", headers[j] )
return nil, fmt.Errorf("Unknown header \"%s\"", headers[j])
}
}
if busStops[ entry.StationId ] != nil {
return nil, fmt.Errorf( "Duplicated entry %+v", entry )
// Ignoring special route for now as getSchedule does not reflect
// which bus is a special route
if entry.ReferenceId != entry.RouteId {
log.Printf("Ignoring special Route: %s", entry.ReferenceId)
continue
}
routeDir, hasKey := routeStops[ entry.RouteId ]
if busStops[entry.StationId] != nil {
return nil, fmt.Errorf("Duplicated entry %+v", entry)
}
routeDir, hasKey := routeStops[entry.RouteId]
if !hasKey {
routeStops[ entry.RouteId ] = map[string] map[int] *BusStop{}
routeDir = routeStops[ entry.RouteId ]
routeStops[entry.RouteId] = map[string]map[int]*BusStop{}
routeDir = routeStops[entry.RouteId]
}
route, hasKey := routeDir[ entry.Direction ]
route, hasKey := routeDir[entry.Direction]
if !hasKey {
routeDir[ entry.Direction ] = map[int] *BusStop{}
route = routeDir[ entry.Direction ]
routeDir[entry.Direction] = map[int]*BusStop{}
route = routeDir[entry.Direction]
}
_, hasKey = route[ entry.StationSeq ]
_, hasKey = route[entry.StationSeq]
if !hasKey {
route[ entry.StationSeq ] = &entry
route[entry.StationSeq] = &entry
}
entry.RouteStops = &route
entry.Reload()
busStops[ entry.StationId ] = &entry
busStops[entry.StationId] = &entry
}
return &busStops, nil
}
func getBusStops() (*[] query.ISearchable, error) {
func getBusStops() (*[]query.ISearchable, error) {
QUERY_FUNC := func() ( io.ReadCloser, error ) {
resp, err := http.Get( "https://opendata.mtr.com.hk/data/mtr_bus_stops.csv" )
QUERY_FUNC := func() (io.ReadCloser, error) {
resp, err := http.Get("https://opendata.mtr.com.hk/data/mtr_bus_stops.csv")
if err != nil {
return nil, err
}
return resp.Body, nil
}
buff, err := utils.CacheStream( CSV_BUSSTOPS, QUERY_FUNC, 7 * 24 * 3600 )
buff, err := utils.CacheStream(CSV_BUSSTOPS, QUERY_FUNC, 7*24*3600)
if err != nil {
return nil, err
}
utils.ReadBOM( buff )
busStopMap, err := readBusStopData( buff )
utils.ReadBOM(buff)
busStopMap, err := readBusStopData(buff)
if err != nil {
return nil, err
}
searchables := [] query.ISearchable{}
searchables := []query.ISearchable{}
for _, busStop := range *busStopMap {
searchables = append( searchables, busStop )
searchables = append(searchables, busStop)
}
return &searchables, nil