mvg-live 2.3.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +32 -0
  3. data/README.md +51 -46
  4. data/bin/mvg +8 -1
  5. data/bin/mvg_json +8 -1
  6. data/lib/mvg/live/cli.rb +28 -4
  7. data/lib/mvg/live/http.rb +93 -20
  8. data/lib/mvg/live/parser.rb +15 -48
  9. data/lib/mvg/live/version.rb +1 -1
  10. data/lib/mvg/live.rb +72 -30
  11. data/spec/fixtures/vcr_cassettes/MVG/Live/CLI/test_0002_resolves_the_hacked_station_names_in_CLI_mode.json +139 -0
  12. data/spec/fixtures/vcr_cassettes/MVG/Live/CLI/test_0005_resolves_the_hacked_station_names_in_CLI_mode.json +139 -0
  13. data/spec/fixtures/vcr_cassettes/MVG/Live/HTTP/test_0004_logs_the_request_when_a_logger_is_given.json +139 -0
  14. data/spec/fixtures/vcr_cassettes/MVG/Live/HTTP/test_0004_should_provide_the_response_object_after_retrieving.json +139 -0
  15. data/spec/fixtures/vcr_cassettes/MVG/Live/HTTP/test_0005_should_provide_the_response_object_after_retrieving.json +139 -0
  16. data/spec/fixtures/vcr_cassettes/MVG/Live/HTTP/test_0006_should_provide_the_response_object_after_retrieving.json +139 -0
  17. data/spec/fixtures/vcr_cassettes/MVG/Live/fetching_departures/test_0001_returns_a_usable_data_structure.json +139 -0
  18. data/spec/fixtures/vcr_cassettes/MVG/Live/fetching_departures/test_0002_returns_valid_UTF-8_destinations.json +139 -0
  19. data/spec/fixtures/vcr_cassettes/MVG/Live/fetching_departures/test_0003_sorts_the_sorted_result_by_departure_time.json +139 -0
  20. data/spec/fixtures/vcr_cassettes/MVG/Live/fetching_departures/test_0004_exposes_the_server_time.json +139 -0
  21. data/spec/fixtures/vcr_cassettes/MVG/Live/fetching_departures/test_0005_restricts_the_request_to_the_selected_transports.json +139 -0
  22. data/spec/fixtures/vcr_cassettes/MVG/Live/station_lookup/test_0001_suggests_alternatives_for_unknown_stations.json +72 -0
  23. data/spec/fixtures/vcr_cassettes/MVG/Live/station_lookup/test_0002_matches_station_names_case-insensitively.json +139 -0
  24. data/spec/fixtures/vcr_cassettes/MVG/Live/station_lookup/test_0003_strips_station_additions_in_parentheses.json +139 -0
  25. data/spec/fixtures/vcr_cassettes/MVG/Live/transport_filtering/test_0001_only_returns_U-Bahn_departures_when_only_U-Bahn_is_requested.json +139 -0
  26. data/spec/mvg_live_spec.rb +296 -139
  27. data/spec/spec_helper.rb +34 -16
  28. metadata +46 -174
  29. data/.gitignore +0 -4
  30. data/.travis.yml +0 -8
  31. data/Dockerfile +0 -23
  32. data/Gemfile +0 -4
  33. data/Gemfile.lock +0 -84
  34. data/Rakefile +0 -10
  35. data/fixtures/vcr_cassettes/MVG_Live/HTTP/should_build_the_right_query.json +0 -1
  36. data/fixtures/vcr_cassettes/MVG_Live/HTTP/should_provide_cached_access_to_the_response_object_through_response_obj.json +0 -1
  37. data/fixtures/vcr_cassettes/MVG_Live/Parser/unknown_station/should_inform_about_incorrent_stations_and_possible_fits.json +0 -1
  38. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/both/should_have_the_same_number_of_entries.json +0 -1
  39. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/display/should_display_the_correct_order.json +0 -1
  40. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/display/should_have_the_correct_entry_size.json +0 -1
  41. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/display/should_have_the_correct_order.json +0 -1
  42. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/sorted/should_have_the_correct_entry_size.json +0 -1
  43. data/fixtures/vcr_cassettes/MVG_Live/Parser/with_S-Bahn/sorted/should_have_the_correct_order.json +0 -1
  44. data/fixtures/vcr_cassettes/test_0001_should_apply_convenience_hacks_on_station_names.json +0 -1
  45. data/fixtures/vcr_cassettes/test_0001_should_apply_some_convenience_hacks_on_station_names.json +0 -1
  46. data/fixtures/vcr_cassettes/test_0001_should_have_the_correct_entry_size.json +0 -1
  47. data/fixtures/vcr_cassettes/test_0001_should_have_the_same_number_of_entries.json +0 -1
  48. data/fixtures/vcr_cassettes/test_0001_should_inform_about_incorrent_stations_and_possible_fits.json +0 -1
  49. data/fixtures/vcr_cassettes/test_0001_should_parse_the_response_and_return_a_usable_data_structure.json +0 -1
  50. data/fixtures/vcr_cassettes/test_0002_should_apply_the_following_convenince_hacks.json +0 -1
  51. data/fixtures/vcr_cassettes/test_0003_should_build_the_right_query.json +0 -1
  52. data/fixtures/vcr_cassettes/test_0004_should_provide_access_to_the_response_object_through_response_obj.json +0 -1
  53. data/fixtures/vcr_cassettes/test_0004_should_provide_access_to_the_response_through_response.json +0 -1
  54. data/fixtures/vcr_cassettes/test_0004_should_provide_cached_access_to_the_response_object_through_response_obj.json +0 -1
  55. data/lib/mvg/live/encoding.rb +0 -13
  56. data/mvg-live.gemspec +0 -39
  57. data/spec/factories.rb +0 -24
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: bf43ceefc66c8be51152687efde6f2902a6d60be
4
- data.tar.gz: 2a0406e6b58f103321c9d137cd2bf15b0a9b10f5
2
+ SHA256:
3
+ metadata.gz: 8b089f1bdfce04d6bd17622ec087ff4ad62f0c38e55ee8786b6df348a7fd41ef
4
+ data.tar.gz: d85f7d508d7e4428b06dd881f55a9976e836ef44fc780d50902a2808a58bd0e4
5
5
  SHA512:
6
- metadata.gz: a3b343843c424e1b9612ebdff13e7663ab6f4aeffed8c5b7da355c5c5d4492262422dcc5607a75dd00db99d5a2ff9a90fd9ae8758b922dd8f777058b360af161
7
- data.tar.gz: 311e55fe5c8a574ea0afda6eb44648ab9b769da867078e66f50142c7265049f9234150a545f3fa6b2abebb2d611251a3bded677e3b7f4c42437bd9ae1b565e5a
6
+ metadata.gz: c188ba43921084631ff69a6712fe05f1dd40b0663811cc4ceb284cf6e38e223c6c86ed9c79e5989f31ed09ac2726854764e17b2b59953fb8ef14e43fcee014bd
7
+ data.tar.gz: 3e9dd08ee5918a8918e25ad1b570e0870a4c137aab931123c2694b6ef794deaaeb35d4ee0dffc61c18af536149db2095744f2cbcf4720bd3bccb1a27529fff98
data/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ ## 3.0.0 (2026-11-23)
4
+
5
+ Complete modernization after the shutdown of the old
6
+ `www.mvg-live.de/ims/dfiStaticAuswahl.svc` endpoint.
7
+
8
+ - Replace HTML scraping with the JSON API of mvg.de
9
+ (`/api/bgw-pt/v3/locations` and `/api/bgw-pt/v3/departures`).
10
+ - Drop Nokogiri and multi_json, the response is parsed as JSON.
11
+ - Drop all runtime dependencies: plain Net::HTTP and JSON instead of
12
+ Faraday, an internal `MVG::Live::Errors` instead of ActiveModel.
13
+ - Require Ruby >= 3.3; replace the dead Travis CI setup with GitHub Actions.
14
+ - Replace the `schema:`/`host:`/`path:` options with `base_url:`.
15
+ - Fix `MVG::Live.new` crashing when user defaults are loaded without a station.
16
+ - Skip cancelled departures and clamp departures in the past to 0 minutes.
17
+ - Limit departures to the next 60 minutes by default; `--all` shows the full
18
+ API response.
19
+ - Read the server time from the local clock, the new API does not send one.
20
+ - Refresh the Docker image (Ruby 4.0 Alpine, no build dependencies).
21
+
22
+ ## 2.3.0
23
+
24
+ - Downgrade mocha, update dependencies.
25
+
26
+ ## 2.2.0
27
+
28
+ - Update dependencies, cleanup.
29
+
30
+ ## 2.1.0
31
+
32
+ - Prepare release.
data/README.md CHANGED
@@ -1,20 +1,15 @@
1
1
  # MVG-LIVE
2
2
 
3
- A ruby client and CLI for mvg-live.de the real-time interface for Munich's public transportation service.
3
+ A ruby client and CLI for Munich's public transport (MVG) real-time departure monitor.
4
4
 
5
-
6
- [![Build](https://img.shields.io/travis-ci/rmoriz/mvg-live.svg?style=flat-square)](https://travis-ci.org/rmoriz/mvg-live)
7
- [![Dependencies](https://img.shields.io/gemnasium/rmoriz/mvg-live.svg?style=flat-square)](https://gemnasium.com/rmoriz/mvg-live)
5
+ [![CI](https://github.com/rmoriz/mvg-live/actions/workflows/ci.yml/badge.svg)](https://github.com/rmoriz/mvg-live/actions/workflows/ci.yml)
8
6
  [![Downloads](https://img.shields.io/gem/dtv/mvg-live.svg?style=flat-square)](https://rubygems.org/gems/mvg-live)
9
7
  [![Tags](https://img.shields.io/github/tag/rmoriz/mvg-live.svg?style=flat-square)](https://github.com/rmoriz/mvg-live/tags)
10
8
  [![Issues](https://img.shields.io/github/issues/rmoriz/mvg-live.svg?style=flat-square)](https://github.com/rmoriz/mvg-live/issues)
11
9
  [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](http://opensource.org/licenses/MIT)
12
10
  [![Version](https://img.shields.io/gem/v/mvg-live.svg?style=flat-square)](https://rubygems.org/gems/mvg-live)
13
11
 
14
- [![Flattr](https://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/submit/auto?user_id=flattr&url=https://github.com/rmoriz/mvg-live&title=mvg-live%20rubygem&description=mvg-live%20rubygem&language=de_DE&tags=fahrplan,mvg,swm,ruby,code,u-bahn,s-bahn,tram,muenchen&category=software)
15
-
16
-
17
- ## Installation
12
+ ## Installation
18
13
 
19
14
 
20
15
  ### Docker
@@ -29,18 +24,20 @@ docker run -it --rm rmoriz/mvg-live Marienplatz
29
24
  gem install mvg-live
30
25
  ```
31
26
 
32
- Please use Ruby 2.2.x or greater.
27
+ Please use Ruby 3.3.x or greater.
33
28
 
34
29
 
35
30
  ## Ruby
36
31
 
37
32
  require 'mvg/live'
38
-
39
- result = MVG::Live.fetch 'Sendlinger Tor'
40
- => [{:line=>"U7", :destination=>"Westfriedhof", :minutes=>0}, {:line=>"U3", :destination=>"Olympiazentrum", :minutes=>0}, {:line=>"17", :destination=>"Schwanseestraße", :minutes=>0}, {:line=>"U3", :destination=>"Fürstenried West", :minutes=>0}, {:line=>"16", :destination=>"Romanplatz", :minutes=>0}, {:line=>"27", :destination=>"Petuelring", :minutes=>0}, {:line=>"152", :destination=>"Landshuter Allee", :minutes=>1}, {:line=>"U2", :destination=>"Feldmoching", :minutes=>1}, {:line=>"18", :destination=>"Effnerplatz", :minutes=>1}, {:line=>"U1", :destination=>"Olympia-Einkaufsz.", :minutes=>2}, {:line=>"U7", :destination=>"Neuperlach Zentrum", :minutes=>2}, {:line=>"U6", :destination=>"Klinikum Großhadern", :minutes=>2}, {:line=>"U6", :destination=>"Garching-Forschungs.", :minutes=>3}, {:line=>"18", :destination=>"Gondrellplatz", :minutes=>3}, {:line=>"16", :destination=>"St. Emmeram", :minutes=>4}, {:line=>"17", :destination=>"Amalienburgstraße", :minutes=>4}, {:line=>"U3", :destination=>"Moosach", :minutes=>4}, {:line=>"U3", :destination=>"Fürstenried West", :minutes=>5}, {:line=>"U2", :destination=>"Messestadt Ost", :minutes=>5}, {:line=>"U1", :destination=>"Mangfallplatz", :minutes=>6}]
41
33
 
42
- result = MVG::Live.fetch 'Sendlinger Tor', :transports => [ :tram ]
43
- => [{:line=>"17", :destination=>"Schwanseestraße", :minutes=>0}, {:line=>"16", :destination=>"Romanplatz", :minutes=>1}, {:line=>"27", :destination=>"Petuelring", :minutes=>1}, {:line=>"18", :destination=>"Effnerplatz", :minutes=>2}, {:line=>"18", :destination=>"Gondrellplatz", :minutes=>3}, {:line=>"16", :destination=>"St. Emmeram", :minutes=>4}, {:line=>"17", :destination=>"Amalienburgstraße", :minutes=>5}, {:line=>"16", :destination=>"Romanplatz", :minutes=>8}, {:line=>"17", :destination=>"Schwanseestraße", :minutes=>9}, {:line=>"27", :destination=>"Petuelring", :minutes=>9}, {:line=>"18", :destination=>"Effnerplatz", :minutes=>9}, {:line=>"18", :destination=>"Gondrellplatz", :minutes=>12}, {:line=>"16", :destination=>"St. Emmeram", :minutes=>13}, {:line=>"17", :destination=>"Amalienburgstraße", :minutes=>16}, {:line=>"27", :destination=>"Petuelring", :minutes=>16}, {:line=>"16", :destination=>"Romanplatz", :minutes=>17}, {:line=>"18", :destination=>"Effnerplatz", :minutes=>17}, {:line=>"17", :destination=>"Schwanseestraße", :minutes=>19}, {:line=>"18", :destination=>"Gondrellplatz", :minutes=>22}, {:line=>"16", :destination=>"St. Emmeram", :minutes=>23}]
34
+ result = MVG::Live.fetch 'Sendlinger Tor', transports: [:u, :tram]
35
+ => [{:line=>"U3", :destination=>"Fürstenried West", :minutes=>1}, ...]
36
+
37
+ result = MVG::Live.fetch 'Sendlinger Tor', transports: [:tram]
38
+ => [{:line=>"17", :destination=>"Schwanseestraße", :minutes=>0}, ...]
39
+
40
+ Every entry is a hash with `:line`, `:destination` and `:minutes`.
44
41
 
45
42
  ## CLI (command line interface)
46
43
 
@@ -48,17 +45,20 @@ This gem provides two scripts:
48
45
 
49
46
  ### mvg
50
47
 
51
- Returns a human readable listing of the next depatures
48
+ Returns a human readable listing of the next departures
52
49
 
53
50
  $ mvg Hauptbahnhof
54
51
  $ mvg Marienplatz
55
52
  $ mvg Moosach Bf.
56
53
 
57
- example output:
54
+ Only departures within the next 60 minutes are shown. Pass `--all` to see
55
+ everything the API returns:
56
+
57
+ $ mvg --all Marienplatz
58
58
 
59
+ `mvg --help` lists both flags.
59
60
 
60
- <img src="http://i.imgur.com/LLGYs.jpg">
61
- <img src="http://i.imgur.com/rO6Fz.jpg">
61
+ example output:
62
62
 
63
63
  ================================================
64
64
  Hauptbahnhof: U, Bus, Tram, S
@@ -68,22 +68,7 @@ example output:
68
68
  U2 | Feldmoching | 1 Minuten
69
69
  U1 | Mangfallplatz | 1 Minuten
70
70
  S8 | Herrsching | 2 Minuten
71
- U2 | Messestadt Ost | 3 Minuten
72
- 17 | Schwanseestraße | 3 Minuten
73
- S7 | Aying | 4 Minuten
74
- U4 | Arabellapark | 4 Minuten
75
- U4 | Theresienwiese | 5 Minuten
76
- S6 | Ostbahnhof | 5 Minuten
77
- U2 | Messestadt Ost | 6 Minuten
78
- S2 | Petershausen | 6 Minuten
79
- 20 | Moosach Bf. | 6 Minuten
80
- U1 | Olympia - Einkaufszentrum | 6 Minuten
81
- 19 | Pasing | 8 Minuten
82
- U5 | Neuperlach Süd | 8 Minuten
83
- 16 | Romanplatz | 8 Minuten
84
- U5 | Laimer Platz | 9 Minuten
85
- U1 | Mangfallplatz | 11 Minuten
86
-
71
+ ...
87
72
 
88
73
  displays alternates/suggestions in case of unclear/invalid station name:
89
74
 
@@ -91,8 +76,8 @@ displays alternates/suggestions in case of unclear/invalid station name:
91
76
  ================================================
92
77
  /!\ Station unknown! Did you mean...? /!\
93
78
  ================================================
94
- - Am Münchner Tor
95
79
  - Sendlinger Tor
80
+ - Schwabinger Tor
96
81
 
97
82
 
98
83
  ### mvg_json
@@ -103,9 +88,6 @@ Returns JSON
103
88
  $ mvg_json Marienplatz
104
89
  $ mvg_json Moosach Bf.
105
90
 
106
- <img src="http://i.imgur.com/7pxh9.jpg">
107
-
108
-
109
91
  ### User Preferences
110
92
 
111
93
  You can specify a default station or a default transports list (e.g. only specific transport systems) in a JSON file. This only affects the CLI version!
@@ -118,7 +100,7 @@ The first available file will be loaded:
118
100
  Example .mvg file:
119
101
 
120
102
  {"default_transports":["u"],"default_station":"Hauptbahnhof"}
121
-
103
+
122
104
  This limits the transports to U-Bahn and uses "Hauptbahnhof" as default station:
123
105
 
124
106
  $ mvg
@@ -128,7 +110,6 @@ This limits the transports to U-Bahn and uses "Hauptbahnhof" as default station:
128
110
  U1 | Mangfallplatz | 0 Minuten
129
111
  U2 | Feldmoching | 0 Minuten
130
112
  U4 | Arabellapark | 3 Minuten
131
- U4 | Theresienwiese | 4 Minuten
132
113
  ...
133
114
 
134
115
  You can overwrite the station as mentioned above but the transport limitation is currently *global*!
@@ -139,7 +120,6 @@ You can overwrite the station as mentioned above but the transport limitation is
139
120
  ======================================[ 13:37 ]=
140
121
  U5 | Neuperlach Süd | 2 Minuten
141
122
  U5 | Laimer Platz | 8 Minuten
142
- U5 | Neuperlach Süd | 12 Minuten
143
123
  ...
144
124
 
145
125
  The default transports list (= all available) is:
@@ -153,9 +133,36 @@ JSON:
153
133
  ["u", "bus", "tram", "s"]
154
134
 
155
135
 
136
+ ## Data source
137
+
138
+ The client talks to the (undocumented) JSON API that powers [mvg.de](https://www.mvg.de):
139
+
140
+ - `GET https://www.mvg.de/api/bgw-pt/v3/locations?query=<station>` to resolve a station name
141
+ - `GET https://www.mvg.de/api/bgw-pt/v3/departures?globalId=<id>` for the departures
142
+
143
+ Requests are sent with the public API key used by the MVG web app. It can be
144
+ overridden by passing `api_key:` to `MVG::Live.new`, the base URL by passing
145
+ `base_url:`. The client only uses the standard library (`net/http`, `json`);
146
+ the gem has no runtime dependencies.
147
+
148
+ ## Upgrading from 2.x
149
+
150
+ - Nokogiri/HTML scraping was replaced by the JSON API, the old
151
+ `www.mvg-live.de` endpoint is gone.
152
+ - All runtime dependencies were dropped; Ruby 3.3+ is required.
153
+ - `schema:`, `host:` and `path:` options were replaced by `base_url:`.
154
+ - `faraday_adapter:` and `faraday_logger:` became `logger:`.
155
+
156
+
156
157
  ## Minitest-Specs
157
158
 
158
- see "specs/"-directory
159
+ see "spec/"-directory. The HTTP fixtures are recorded from the live API and
160
+ replayed with VCR, so the suite runs offline. Refresh them with:
161
+
162
+ rm -rf spec/fixtures/vcr_cassettes
163
+ bundle exec rake test
164
+ ruby script/rewrite_cassettes.rb
165
+ bundle exec rake test
159
166
 
160
167
 
161
168
  ## Disclaimer
@@ -172,9 +179,7 @@ see LICENSE file (MIT)
172
179
  Copyright
173
180
  ---------
174
181
 
175
- Copyright © 2016 [Roland Moriz](https://roland.io), [Moriz GmbH](https://moriz.de/)
182
+ Copyright © 2016 [Roland Moriz](https://roland.io)
176
183
 
177
- [![LinkedIn](http://www.linkedin.com/img/webpromo/btn_viewmy_160x25.png)](http://www.linkedin.com/in/rmoriz)
184
+ [![LinkedIn](http://www.linkedin.com/img/webpromo/btn_viewmy_160x25.png)](https://www.linkedin.com/in/rmoriz)
178
185
  [![Twitter](http://i.imgur.com/1kYFHlu.png)](https://twitter.com/rmoriz)
179
-
180
-
data/bin/mvg CHANGED
@@ -3,4 +3,11 @@
3
3
  require 'rubygems'
4
4
  require 'mvg/live'
5
5
 
6
- puts MVG::Live.fetch_to_display ARGV.join(' '), load_user_defaults: true, cli: true
6
+ options = MVG::Live::CLI.parse_argv(ARGV)
7
+
8
+ if options[:help]
9
+ puts MVG::Live::CLI.usage
10
+ exit
11
+ end
12
+
13
+ puts MVG::Live.fetch_to_display options[:station], load_user_defaults: true, cli: true, all: options[:all]
data/bin/mvg_json CHANGED
@@ -3,4 +3,11 @@
3
3
  require 'rubygems'
4
4
  require 'mvg/live'
5
5
 
6
- puts MVG::Live.fetch_to_json ARGV.join(' '), load_user_defaults: true, cli: true
6
+ options = MVG::Live::CLI.parse_argv(ARGV)
7
+
8
+ if options[:help]
9
+ puts MVG::Live::CLI.usage
10
+ exit
11
+ end
12
+
13
+ puts MVG::Live.fetch_to_json options[:station], load_user_defaults: true, cli: true, all: options[:all]
data/lib/mvg/live/cli.rb CHANGED
@@ -3,6 +3,27 @@ require 'json'
3
3
  module MVG
4
4
  class Live
5
5
  module CLI
6
+ def self.usage
7
+ <<~TEXT
8
+ Usage: mvg [--all] <station>
9
+ mvg_json [--all] <station>
10
+
11
+ --all show all departures returned by the API instead of
12
+ only those within the next #{MVG::Live::DEFAULT_MAX_MINUTES} minutes
13
+ --help show this help
14
+ TEXT
15
+ end
16
+
17
+ def self.parse_argv(argv)
18
+ args = argv.dup
19
+
20
+ {
21
+ all: !args.delete('--all').nil?,
22
+ help: !(args.delete('--help') || args.delete('-h')).nil?,
23
+ station: args.join(' ')
24
+ }
25
+ end
26
+
6
27
  module ClassMethods
7
28
  def fetch(*args)
8
29
  MVG::Live.new(*args).fetch
@@ -51,7 +72,9 @@ module MVG
51
72
  end
52
73
 
53
74
  else
54
- txt += "#{@station}: #{@transports.map(&:to_s).map(&:capitalize).join(', ')}\n"
75
+ txt += "#{@station}: #{@transports.map(&:to_s).map(&:capitalize).join(', ')}"
76
+ txt += " (alle Abfahrten)" unless @max_minutes
77
+ txt += "\n"
55
78
  txt += '=' * 38 + "[ #{@server_time} ]=\n"
56
79
 
57
80
  @result_sorted.each do |e|
@@ -68,6 +91,7 @@ module MVG
68
91
  response[:station] = station
69
92
  response[:server_time] = server_time
70
93
  response[:transports] = transports
94
+ response[:max_minutes] = max_minutes
71
95
  response[:using_config_file] = using_config_file
72
96
 
73
97
  response[:result_sorted] = result_sorted
@@ -90,7 +114,7 @@ module MVG
90
114
  next unless file && File.exist?(file)
91
115
  data = JSON.parse File.read(file)
92
116
 
93
- if @station.empty? && data['default_station']
117
+ if @station.to_s.empty? && data['default_station']
94
118
  @station = data['default_station']
95
119
  end
96
120
 
@@ -104,8 +128,8 @@ module MVG
104
128
  case station
105
129
  when 'Stachus', 'Karlsplatz'
106
130
  'Karlsplatz (Stachus)'
107
- when 'Moosach Bf', 'Moosach Bahnhof'
108
- 'Moosach Bf.'
131
+ when 'Moosach Bf', 'Moosach Bf.', 'Moosach Bahnhof'
132
+ 'Moosach'
109
133
  else
110
134
  station
111
135
  end
data/lib/mvg/live/http.rb CHANGED
@@ -1,39 +1,78 @@
1
- require 'faraday'
1
+ require 'json'
2
+ require 'net/http'
3
+ require 'uri'
2
4
 
3
5
  module MVG
4
6
  class Live
5
7
  module HTTP
6
- def connection
7
- @conn ||= Faraday.new(url: "#{@schema}://#{@host}") do |builder|
8
- builder.use @faraday_adapter
9
- builder.response :logger if @faraday_logger
10
- end
11
- @conn
12
- end
8
+ DEFAULT_BASE_URL = 'https://www.mvg.de/api/bgw-pt/v3'
9
+ API_KEY = '33d2f2c1b7b3b6a7e5f0d4c3b2a1908f'
10
+
11
+ LOCATION_LIMIT = 10
12
+ MAX_DEPARTURES = 30
13
+ MAX_STATION_FAILS = 5
14
+
15
+ OPEN_TIMEOUT = 5
16
+ READ_TIMEOUT = 15
17
+
18
+ Response = Struct.new(:status, :body)
13
19
 
14
20
  def retrieve
15
21
  return unless valid?
22
+
16
23
  @response_obj = nil
24
+ @station_unknown = false
25
+ @station_alternates = []
17
26
 
18
- res = connection.get do |req|
19
- req.url @path, build_request_params
20
- req.headers['Content-Type'] = 'text/html; charset=UTF-8'
21
- end
22
- @response_obj = res
27
+ resolve_station
28
+ return if @station_unknown
29
+
30
+ @response_obj = request('departures', build_request_params)
23
31
  end
24
32
 
25
- def build_request_params
26
- params = {}
27
- params[:haltestelle] = station_to_mvg(@station)
33
+ # Looks up the station and stores the matching station id. Ambiguous or
34
+ # unknown names are recorded as suggestions instead.
35
+ def resolve_station
36
+ query = station_to_mvg(@station)
37
+ wanted = normalize_station(query)
38
+
39
+ response = request('locations', query: query, limit: LOCATION_LIMIT)
40
+ @response_obj = response
28
41
 
29
- transports.each do |available_transport|
30
- params[transport_to_mvg(available_transport)] = 'checked' if @transports.include? available_transport
42
+ candidates = response.body.is_a?(Array) ? response.body.select { |l| l['type'] == 'STATION' } : []
43
+ match = candidates.find { |location| station_names(location).include?(wanted) }
44
+
45
+ if match
46
+ @global_id = match['globalId']
47
+ else
48
+ @station_unknown = true
49
+ @station_alternates = candidates.first(MAX_STATION_FAILS).map { |location| to_utf8(location['name']) }
31
50
  end
51
+ end
52
+
53
+ def build_request_params
54
+ params = { globalId: @global_id, limit: MAX_DEPARTURES }
55
+ params[:transportTypes] = transports.map { |transport| transport_to_mvg(transport).upcase }.join(',')
32
56
  params
33
57
  end
34
58
 
59
+ def station_names(location)
60
+ [location['name'], location['aliases']]
61
+ .compact
62
+ .flat_map { |value| normalize_station(value).split(',') }
63
+ .map(&:strip)
64
+ end
65
+
66
+ def normalize_station(value)
67
+ to_utf8(value)
68
+ .gsub(/\([^)]*\)/, ' ')
69
+ .squeeze(' ')
70
+ .strip
71
+ .downcase
72
+ end
73
+
35
74
  def station_to_mvg(station)
36
- station = to_encoding(station)
75
+ station = to_utf8(station)
37
76
 
38
77
  if @cli
39
78
  cli_station_hacks_for(station)
@@ -49,9 +88,43 @@ module MVG
49
88
  when :s
50
89
  'sbahn'
51
90
  else
52
- transport
91
+ transport.to_s
53
92
  end
54
93
  end
94
+
95
+ def build_request_headers
96
+ {
97
+ 'Accept' => 'application/json',
98
+ 'x-mvg-authority-check-api-key' => @api_key
99
+ }
100
+ end
101
+
102
+ private
103
+
104
+ def request(path, params)
105
+ uri = URI.join("#{@base_url}/", path)
106
+ uri.query = URI.encode_www_form(params)
107
+
108
+ http = Net::HTTP.new(uri.host, uri.port)
109
+ http.use_ssl = uri.scheme == 'https'
110
+ http.open_timeout = OPEN_TIMEOUT
111
+ http.read_timeout = READ_TIMEOUT
112
+
113
+ http_request = Net::HTTP::Get.new(uri)
114
+ build_request_headers.each { |name, value| http_request[name] = value }
115
+
116
+ response = http.request(http_request)
117
+ @logger&.debug("#{http_request.method} #{uri} -> #{response.code}")
118
+
119
+ Response.new(response.code.to_i, parse_body(response))
120
+ end
121
+
122
+ def parse_body(response)
123
+ body = response.body.to_s.dup.force_encoding('UTF-8')
124
+ JSON.parse(body)
125
+ rescue JSON::ParserError
126
+ body
127
+ end
55
128
  end
56
129
  end
57
130
  end
@@ -1,61 +1,28 @@
1
- require 'nokogiri'
2
-
3
1
  module MVG
4
2
  class Live
5
3
  module Parser
6
4
  def parse(_args = {})
5
+ return if @station_unknown
7
6
  return unless @response_obj
8
7
 
9
- @doc = Nokogiri::HTML(@response_obj.body)
10
-
11
- # <table class="departureTable departureView">
12
- # ...
13
- # <tr class="rowOdd">
14
- # <td class="lineColumn">N16</td>
15
- # <td class="stationColumn">
16
- # Effnerplatz
17
- # <span class="spacer">&nbsp;</span>
18
- # </td>
19
- # <td class="inMinColumn">13</td>
20
- # </tr>
21
-
22
- # <tr class="rowEven">
23
- # <td class="lineColumn">N16</td>
24
- # <td class="stationColumn">
25
- # Amalienburgstraße
26
- # <span class="spacer">&nbsp;</span>
27
- # </td>
28
- # <td class="inMinColumn">28</td>
29
- # </tr>
30
-
31
- # <tr>
32
- # <td colspan="4" class="sBahnHeader">S-Bahn M&uuml;nchen (Daten DB Regio AG)</td>
8
+ @server_time = Time.now.strftime('%H:%M')
9
+ now = (@now || Time.now).to_f * 1000
33
10
 
34
- @server_time = @doc.xpath('//td[@class="serverTimeColumn"]/text()')
11
+ body = @response_obj.body
12
+ results = (body.is_a?(Array) ? body : []).reject { |entry| entry['cancelled'] }.map do |entry|
13
+ departure = entry['realtimeDepartureTime'] || entry['plannedDepartureTime']
35
14
 
36
- results = []
37
-
38
- @doc.xpath('//table[@class="departureTable departureView"]/tr[@class="rowOdd" or @class="rowEven"]').each do |entry|
39
- result = {}
40
- result[:line] = entry.at('td[@class="lineColumn"]/text()').to_s.strip
41
- result[:destination] = to_utf8(entry.at('td[@class="stationColumn"]/text()').to_s.strip)
42
- result[:minutes] = entry.at('td[@class="inMinColumn"]/text()').to_s.to_i
43
-
44
- results << result
15
+ {
16
+ line: to_utf8(entry['label'].to_s.strip),
17
+ destination: to_utf8(entry['destination'].to_s.strip),
18
+ minutes: departure ? [((departure - now) / 60_000.0).round, 0].max : 0
19
+ }
45
20
  end
21
+ results = results.select { |entry| entry[:minutes] <= @max_minutes } if @max_minutes
46
22
 
47
- if results.empty?
48
- @station_unknown = true
49
- @station_alternates = []
50
-
51
- @doc.xpath('//table[@class="departureTable header"]//li/a/text()').each do |alt|
52
- @station_alternates << to_utf8(alt.to_s.strip)
53
- end
54
- else
55
- @result_display = results
56
- @result_sorted = results.sort_by { |i,| [i[:minutes], i[:line], i[:destination]] }
57
- @result_sorted
58
- end
23
+ @result_display = results
24
+ @result_sorted = results.sort_by { |entry| [entry[:minutes], entry[:line], entry[:destination]] }
25
+ @result_sorted
59
26
  end
60
27
  end
61
28
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module MVG
4
4
  class Live
5
- VERSION = '2.3.0'.freeze
5
+ VERSION = '3.0.0'.freeze
6
6
  end
7
7
  end