sim-meter-au 0.1.0 → 0.1.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e71372ec0601bc9629010ed55c2a980570d729cac3f8919ffb4899a689231a28
4
- data.tar.gz: a00ea1d08ab83fd4e61bba171de9d5565ca71da34e276e246b7c68cb8b49de45
3
+ metadata.gz: e990183acbc9eed9c89602c66aa52717bb18c6ba7b43cccbd97e2b70ad2122da
4
+ data.tar.gz: 36ede4c541cccf8a2eb8672a43da4879ee29e0a1f1ee2e3ad7127feaacfb1d77
5
5
  SHA512:
6
- metadata.gz: c9cf1f8112060047adff81045cceb2673c61963743d2800852760bafdc46c35feaa87b395cb94134bf5a0a2757d0952ff5a001b9fb339cad26b79f82bfa05024
7
- data.tar.gz: 31773f757c185ead61ecaf975b7b37df4b15d844a3b22c9b175e830c10aebe65b740495c8de15d78ee693bb9df985757a729a4c2b9fbeb744c54cd2051d8d695
6
+ metadata.gz: cb88dd2fb8c77d7843adc8316b7408d45c3d2526bb1e5c588fa9647c4c22f53034107cff9d087023204d83a45c5817d8482de3edbbb81d2b42543e55645903fb
7
+ data.tar.gz: 1b5649eff592d270fec37cd3b4b968f4a3ac64a342dd34fb961f0745a7249272e2908d6af075e07e932e0d5747ed2be62238ceee63d5bb91150cd156f61dab41
data/README.md CHANGED
@@ -3,10 +3,6 @@
3
3
  Sim Meter AU provides a unified Ruby API for retrieving services, plan details,
4
4
  data balances, expiry dates and usage from Australian mobile providers.
5
5
 
6
- It currently supports ALDImobile through authenticated HTTP requests and
7
- HTML/JSON parsing. It does not execute the provider portal's JavaScript and does
8
- not require a web browser.
9
-
10
6
  ## Installation
11
7
 
12
8
  Add the gem to your Gemfile:
@@ -28,12 +24,25 @@ The currently available provider is:
28
24
  - `:aldi_mobile` — ALDImobile
29
25
 
30
26
  Every provider inherits from `SimMeterAU::Provider` and implements the same
31
- operations: authentication, services, service details, usage and orders. This
32
- keeps application code consistent as additional Australian providers are
33
- added.
27
+ operations: authentication, services, service details, usage and orders. **Pull requests welcome**.
34
28
 
35
29
  Use `SimMeterAU.providers` to get the registered provider names.
36
30
 
31
+ It currently supports ALDImobile through direct HTTPS requests to the JSON API
32
+ used by the current My ALDI Mobile portal. It uses Ruby's `Net::HTTP` and does
33
+ not require a web browser, headless browser, JavaScript runtime or Rails.
34
+
35
+ Version 0.1.1 replaces the HTML login integration that stopped working when
36
+ ALDImobile migrated its portal in November 2026. Update applications using 0.1.0:
37
+
38
+ ```sh
39
+ bundle update sim-meter-au
40
+ ```
41
+
42
+ The Ruby methods and returned models are unchanged. Provider service IDs have
43
+ changed, so use a mobile number to find a service previously stored with an old
44
+ numeric ID, then save the new `details.service.id`.
45
+
37
46
  ## Ruby API
38
47
 
39
48
  Create a client by selecting a provider and supplying that provider's
@@ -120,6 +129,18 @@ details.to_h
120
129
  - `client.authenticated?` reports whether the current provider session is
121
130
  authenticated.
122
131
 
132
+ Usage dates are inclusive and may span up to 366 days. Usage and orders retrieve
133
+ all pages. Data quantities use bytes (1024 bytes per KB); call usage is in seconds.
134
+ The API does not provide summary charges, so `UsageSummary#charge_dollars` is
135
+ `nil`; individual usage records retain their reported charges. Unavailable
136
+ roaming status and other optional fields are returned as `nil`.
137
+
138
+ Authentication failures (including an expired session or required password
139
+ change) raise `SimMeterAU::AuthenticationError`. Temporary network errors,
140
+ rate limits and provider outages raise `SimMeterAU::ConnectionError`.
141
+ Malformed or incomplete responses raise `SimMeterAU::UnexpectedResponseError`
142
+ instead of being returned as zero balances or empty results.
143
+
123
144
  ## Command-line utility
124
145
 
125
146
  The gem includes a provider-aware `sim-meter-au` command. For local development,
@@ -293,7 +293,8 @@ module SimMeterAU
293
293
  @out.puts
294
294
 
295
295
  summary_rows = report.summaries.map do |summary|
296
- [summary.type, summary.count.to_s, summary.rounded_usage, "$#{summary.charge_dollars}"]
296
+ charge = summary.charge_dollars.nil? ? "Unknown" : "$#{summary.charge_dollars}"
297
+ [summary.type, summary.count.to_s, summary.rounded_usage, charge]
297
298
  end
298
299
  print_table(["TYPE", "COUNT", "ROUNDED USAGE", "CHARGE"], summary_rows)
299
300
  @out.puts "No usage found." if summary_rows.empty?
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ module SimMeterAU
6
+ module Providers
7
+ class AldiMobile
8
+ module Parsers
9
+ class Api
10
+ BYTE_UNITS = {"bytes" => 1, "b" => 1, "kb" => 1024, "mb" => 1024**2,
11
+ "gb" => 1024**3, "tb" => 1024**4}.freeze
12
+ PLAN_TYPES = {"data plan" => "data", "mobile plan" => "mobile",
13
+ "family plan" => "family", "super pack" => "super_pack"}.freeze
14
+
15
+ def service_details(result, service:, roaming_enabled:, retrieved_at: Time.now)
16
+ hash!(result)
17
+ if blank?(result["plan_type"]) || blank?(result["plan_name"])
18
+ invalid!("plan details were not found")
19
+ end
20
+ type = result["plan_type"].to_s.downcase
21
+ plan = unless ["payg", "pay as you go"].include?(type)
22
+ Plan.new(name: result["plan_name"], type: PLAN_TYPES.fetch(type, "unknown"),
23
+ expires_on: date(result["plan_expiry_date"]), days_remaining: integer(result["plan_expiry_days"]),
24
+ auto_recharge: boolean(result["autoRecharge"]))
25
+ end
26
+ usage = result["data_usage"]
27
+ invalid!("data balances were not found") unless usage.is_a?(Array)
28
+ values = usage.reduce({}) { |all, item| all.merge(hash!(item)) }
29
+ remaining = bytes(values["plan_data_remaining_value"], values["plan_data_unit"])
30
+ rollover = bytes(values["rollover_data_remaining_value"], values["rollover_unit"])
31
+ invalid!("plan data balance was not found") if plan && remaining.nil?
32
+ data = if remaining || rollover
33
+ DataBalance.new(plan_remaining_bytes: remaining, rollover_bytes: rollover,
34
+ total_remaining_bytes: remaining.to_i + rollover.to_i)
35
+ end
36
+ payg = result["payg"]
37
+ payg = if payg.is_a?(Hash)
38
+ Payg.new(balance_cents: cents(payg["balance"]), expires_on: date(payg["end_date"]),
39
+ days_until_expiry: integer(payg["days_left"]))
40
+ end
41
+ SimMeterAU::ServiceDetails.new(service:, status: plan ? "active_plan" : "no_active_plan",
42
+ plan:, data:, payg:, roaming_enabled:, retrieved_at:)
43
+ rescue ArgumentError, TypeError
44
+ invalid!("returned invalid plan or balance values")
45
+ end
46
+
47
+ def usage_summaries(result)
48
+ array!(result).map do |item|
49
+ hash!(item)
50
+ category = item.fetch("category")
51
+ UsageSummary.new(type: category, count: Integer(item.fetch("count")),
52
+ rounded_usage: usage_quantity(category, item.fetch("total_unitquantity")),
53
+ charge_dollars: nil)
54
+ end
55
+ rescue KeyError, ArgumentError, TypeError
56
+ invalid!("returned invalid usage summaries")
57
+ end
58
+
59
+ def usage_records(result, service:)
60
+ array!(hash!(result).fetch("response")).flat_map do |group|
61
+ hash!(group)
62
+ category = group.fetch("category")
63
+ array!(group.fetch("details")).map do |item|
64
+ hash!(item)
65
+ UsageRecord.new(type: item.fetch("type"),
66
+ number: local_number(item["originatingNumber"] || service.number),
67
+ destination: item.fetch("destination"),
68
+ usage: usage_quantity(category, item.fetch("volume")),
69
+ charge_dollars: decimal(item.fetch("charge")).to_s("F"),
70
+ date_label: item.fetch("dateTime"))
71
+ end
72
+ end
73
+ rescue KeyError, ArgumentError, TypeError
74
+ invalid!("returned invalid usage records")
75
+ end
76
+
77
+ def orders(result, service:)
78
+ array!(hash!(result).fetch("SalesOrder")).map do |item|
79
+ hash!(item)
80
+ Order.new(id: item.fetch("orderNo"), number: local_number(item["serviceIdentifier"] || service.number),
81
+ type: item.fetch("type"), plan_name: item["basePackageName"],
82
+ date_label: item.fetch("createdTime"), total_cents: cents(item["soTotal"]),
83
+ transaction_reference: item["transactionId"])
84
+ end
85
+ rescue KeyError, ArgumentError, TypeError
86
+ invalid!("returned invalid orders")
87
+ end
88
+
89
+ private
90
+
91
+ def blank?(value)
92
+ value.nil? || value.to_s.strip.empty?
93
+ end
94
+
95
+ def hash!(value)
96
+ invalid!("returned an unexpected object") unless value.is_a?(Hash)
97
+ value
98
+ end
99
+
100
+ def array!(value)
101
+ invalid!("returned an unexpected list") unless value.is_a?(Array)
102
+ value
103
+ end
104
+
105
+ def invalid!(message)
106
+ raise UnexpectedResponseError, "ALDImobile #{message}"
107
+ end
108
+
109
+ def decimal(value)
110
+ number = BigDecimal(value.to_s)
111
+ invalid!("returned a non-finite quantity") unless number.finite?
112
+ number
113
+ end
114
+
115
+ def bytes(value, unit)
116
+ return if blank?(value)
117
+ multiplier = BYTE_UNITS[unit.to_s.downcase]
118
+ invalid!("returned an unknown data unit") unless multiplier
119
+ amount = decimal(value)
120
+ invalid!("returned a negative data balance") if amount.negative?
121
+ (amount * multiplier).round
122
+ end
123
+
124
+ def cents(value)
125
+ (decimal(value) * 100).round unless blank?(value)
126
+ end
127
+
128
+ def date(value)
129
+ return if blank?(value)
130
+ Date.strptime(value, "%d-%m-%Y")
131
+ end
132
+
133
+ def integer(value)
134
+ Integer(value) unless blank?(value)
135
+ end
136
+
137
+ def boolean(value)
138
+ return true if [true, "true", 1, "1"].include?(value)
139
+ return false if [false, "false", 0, "0"].include?(value)
140
+ nil
141
+ end
142
+
143
+ def local_number(value)
144
+ value.to_s.gsub(/\D/, "").sub(/\A61/, "0")
145
+ end
146
+
147
+ def usage_quantity(category, value)
148
+ quantity = decimal(value)
149
+ case category.to_s.downcase
150
+ when "data" then "#{(quantity * 1024).to_s("F")} B"
151
+ when "call", "calls" then "#{quantity.to_s("F")} s"
152
+ else quantity.to_s("F")
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
158
+ end
159
+ end
@@ -1,9 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "mechanize"
3
+ require "net/http"
4
4
  require "openssl"
5
5
  require "json"
6
6
  require "date"
7
+ require "securerandom"
7
8
 
8
9
  module SimMeterAU
9
10
  module Providers
@@ -11,218 +12,246 @@ module SimMeterAU
11
12
  provider_key :aldi_mobile
12
13
  display_name "ALDImobile"
13
14
  credential_names :login, :password
14
- DEFAULT_BASE_URL = "https://my.aldimobile.com.au"
15
- LOGIN_PATH = "/login/"
16
- LOGIN_FORM_ACTION = %r{/login_check/?\z}
17
- SERVICE_SWITCH_PATH = %r{\A/admin/s/(?<id>\d+)/switch/?\z}
18
- MOBILE_NUMBER = /(?:\+?61[\s-]?|0)4(?:[\s-]?\d){8}/
19
-
20
- attr_reader :page
21
-
22
- def initialize(login:, password:, base_url: DEFAULT_BASE_URL, agent: nil)
23
- raise ConfigurationError, "login cannot be empty" if login.to_s.strip.empty?
24
- raise ConfigurationError, "password cannot be empty" if password.to_s.empty?
25
-
26
- @login = login.to_s
27
- @password = password.to_s
28
- @base_url = base_url.delete_suffix("/")
29
- @agent = agent || build_agent
30
- @authenticated = false
31
- end
32
-
33
- def authenticate!
34
- login_page = @agent.get("#{@base_url}#{LOGIN_PATH}")
35
- form = find_login_form(login_page)
36
-
37
- unless form
38
- raise UnexpectedResponseError, "ALDImobile login form was not found"
39
- end
40
15
 
41
- form["login_user[login]"] = @login
42
- form["login_user[password]"] = @password
16
+ DEFAULT_BASE_URL = "https://skyhigh-api.symbio.global/dx-sync"
17
+ APP_ID = "8b1a2963-3c28-35b4-9c9a-8a15ffc8dea2"
18
+ TENANCY_ID = "SP_ALDIMOBILE_AUS"
19
+ PAGE_SIZE = 100
43
20
 
44
- submit_button = form.button_with(name: "login_user[save]")
45
- @page = submit_button ? @agent.submit(form, submit_button) : form.submit
21
+ def initialize(login:, password:, base_url: DEFAULT_BASE_URL, http: Net::HTTP)
22
+ raise ConfigurationError, "login cannot be empty" if login.to_s.strip.empty?
23
+ raise ConfigurationError, "password cannot be empty" if password.to_s.empty?
46
24
 
47
- unless authenticated_page?(@page)
48
- @authenticated = false
49
- raise AuthenticationError, authentication_error_message(@page)
25
+ @login = login.to_s.gsub(/\s+/, "")
26
+ @password = password.to_s
27
+ @base_url = base_url.delete_suffix("/")
28
+ @http = http
50
29
  end
51
30
 
52
- @authenticated = true
53
- self
54
- rescue Mechanize::ResponseCodeError => error
55
- raise ConnectionError, "ALDImobile returned HTTP #{error.response_code}"
56
- rescue SocketError, Timeout::Error, EOFError, Errno::ECONNREFUSED,
57
- Errno::ECONNRESET, OpenSSL::SSL::SSLError => error
58
- raise ConnectionError, "Could not connect to ALDImobile: #{error.class}"
59
- end
60
-
61
- def authenticated?
62
- @authenticated
63
- end
64
-
65
- def services
66
- ensure_authenticated!
67
-
68
- @page.links.filter_map do |link|
69
- match = SERVICE_SWITCH_PATH.match(link.href.to_s)
70
- next unless match
71
-
72
- number = link.text.to_s[MOBILE_NUMBER]
73
- next unless number
74
-
75
- Service.new(
76
- id: match[:id],
77
- name: service_name(link.text, number),
78
- number: normalize_mobile_number(number)
79
- )
80
- end.uniq(&:id)
81
- end
82
-
83
- def service(identifier)
84
- ensure_authenticated!
85
- return identifier if identifier.is_a?(Service)
86
-
87
- query = identifier.to_s.strip
88
- matches = services.select do |candidate|
89
- candidate.id == query ||
90
- candidate.number == normalize_identifier_number(query) ||
91
- candidate.name.casecmp?(query)
31
+ def authenticate!
32
+ clear_session
33
+ mobile = @login.match?(/\A(?:04|\+?614)/)
34
+ result = request(:post, "/crm/v1/login", "customerLogin",
35
+ headers: {"appId" => APP_ID, "type" => mobile ? "msisdn" : "accountNo"},
36
+ body: {username: mobile ? international_number(@login) : @login,
37
+ password: @password, source: "app"})
38
+ require_hash(result)
39
+ if [true, "true", 1, "1"].include?(result["isPasswordExpired"])
40
+ raise AuthenticationError, "ALDImobile requires a password update; sign in to My ALDI Mobile"
41
+ end
42
+ @account_token = access_token(result)
43
+ profile = request(:get, "/crm/v1/profile", "profile", token: @account_token)
44
+ require_hash(profile)
45
+ list = profile["serviceList"]
46
+ unless list.is_a?(Array) && list.all? { |item| item.is_a?(Hash) }
47
+ raise UnexpectedResponseError, "ALDImobile service list was not found"
48
+ end
49
+ @services = list.filter_map do |item|
50
+ next if item["msisdn"].to_s.empty? || item["serviceAccountNo"].to_s.empty?
51
+
52
+ Service.new(id: item["serviceAccountNo"].to_s,
53
+ name: item["servicename"].to_s, number: local_number(item["msisdn"]))
54
+ end.uniq(&:id).freeze
55
+ self
56
+ rescue Error
57
+ clear_session
58
+ raise
92
59
  end
93
60
 
94
- if matches.empty?
95
- raise ServiceNotFoundError, "No ALDImobile service matches #{query.inspect}"
96
- end
97
- if matches.length > 1
98
- raise AmbiguousServiceError, "More than one ALDImobile service matches #{query.inspect}"
61
+ def authenticated?
62
+ !@account_token.nil? && !@services.nil?
99
63
  end
100
64
 
101
- matches.first
102
- end
103
-
104
- def service_details(identifier)
105
- selected_service = service(identifier)
106
- overview = request { @agent.get("#{@base_url}/admin/s/#{selected_service.id}/switch") }
107
- roaming_enabled = roaming_enabled?(selected_service)
108
-
109
- Parsers::ServiceDetails.new.parse(
110
- page: overview,
111
- service: selected_service,
112
- roaming_enabled:
113
- )
114
- end
115
-
116
- def usage(identifier, from: Date.today - 30, to: Date.today)
117
- selected_service = service(identifier)
118
- from = coerce_date(from)
119
- to = coerce_date(to)
120
- raise ConfigurationError, "usage start date must not be after end date" if from > to
121
-
122
- page = request { @agent.get("#{@base_url}/admin/s/#{selected_service.id}/usage") }
123
- form = page.forms.find { |candidate| candidate.action.to_s.end_with?("/usage") }
124
- unless form
125
- raise UnexpectedResponseError, "ALDImobile usage form was not found"
65
+ def services
66
+ ensure_authenticated!
67
+ @services.dup
126
68
  end
127
69
 
128
- form["usage[start]"] = from.iso8601
129
- form["usage[end]"] = to.iso8601
130
- submit_button = form.button_with(name: "usage[getusage]")
131
- result = request { submit_button ? @agent.submit(form, submit_button) : form.submit }
132
-
133
- Parsers::Usage.new.parse(page: result, service: selected_service, from:, to:)
134
- end
135
-
136
- def orders(identifier)
137
- selected_service = service(identifier)
138
- page = request { @agent.get("#{@base_url}/admin/s/#{selected_service.id}/orders") }
139
- Parsers::Orders.new.parse(page)
140
- end
141
-
142
- private
143
-
144
- def ensure_authenticated!
145
- raise AuthenticationError, "Log in before requesting services" unless authenticated?
146
- end
147
-
148
- def roaming_enabled?(selected_service)
149
- response = request do
150
- @agent.get("#{@base_url}/admin/roaming/status/#{selected_service.number}")
70
+ def service(identifier)
71
+ query = identifier.is_a?(Service) ? identifier.id : identifier.to_s.strip
72
+ matches = services.select do |candidate|
73
+ candidate.id == query || candidate.number == local_number(query) ||
74
+ candidate.name.casecmp?(query)
75
+ end
76
+ raise ServiceNotFoundError, "No ALDImobile service matches #{query.inspect}" if matches.empty?
77
+ if matches.length > 1
78
+ raise AmbiguousServiceError, "More than one ALDImobile service matches #{query.inspect}"
79
+ end
80
+
81
+ matches.first
151
82
  end
152
- status = JSON.parse(response.body).fetch("roaming_status", nil)
153
- return true if status.to_s == "1"
154
- return false if status.to_s == "0"
155
83
 
156
- nil
157
- rescue JSON::ParserError
158
- nil
159
- end
84
+ def service_details(identifier)
85
+ selected = service(identifier)
86
+ token = service_token(selected)
87
+ details = request(:get, "/crm/v1/fetch/currentPlanDetails", "getCurrentPlanDetails", token:)
88
+ profile = request(:get, "/crm/v1/profile", "profile", token:)
89
+ require_hash(profile)
90
+ ir_services = profile["irServices"]
91
+ roaming = ir_services.first["selfcare_ir_status"] if ir_services.is_a?(Array) && ir_services.first.is_a?(Hash)
92
+ roaming_enabled = {"Enable" => true, "Disable" => false}[roaming]
93
+ Parsers::Api.new.service_details(details, service: selected, roaming_enabled:)
94
+ end
160
95
 
161
- def request
162
- yield
163
- rescue Mechanize::ResponseCodeError => error
164
- raise ConnectionError, "ALDImobile returned HTTP #{error.response_code}"
165
- rescue SocketError, Timeout::Error, EOFError, Errno::ECONNREFUSED,
166
- Errno::ECONNRESET, OpenSSL::SSL::SSLError => error
167
- raise ConnectionError, "Could not connect to ALDImobile: #{error.class}"
168
- end
96
+ def usage(identifier, from: Date.today - 30, to: Date.today)
97
+ from = coerce_date(from)
98
+ to = coerce_date(to)
99
+ raise ConfigurationError, "usage start date must not be after end date" if from > to
100
+ raise ConfigurationError, "usage date range cannot exceed 366 days" if to - from > 366
101
+
102
+ selected = service(identifier)
103
+ token = service_token(selected)
104
+ params = {start: from.strftime("%m-%d-%Y"), end: to.strftime("%m-%d-%Y")}
105
+ summary = request(:get, "/usage/v1/Usagesummary", "getUsageSummary", token:, params:)
106
+ parser = Parsers::Api.new
107
+ records = %w[Call SMS Data].flat_map do |category|
108
+ paginate do |page|
109
+ result = request(:get, "/usage/v1/Usagedetails", "getUsageDetails", token:,
110
+ params: params.merge(usageType: "ALL", category:, size: PAGE_SIZE, page:))
111
+ require_hash(result)
112
+ [parser.usage_records(result, service: selected), result["totalRecords"]]
113
+ end
114
+ end
115
+ UsageReport.new(service: selected, from:, to:,
116
+ summaries: parser.usage_summaries(summary), records:)
117
+ end
169
118
 
170
- def coerce_date(value)
171
- return value if value.is_a?(Date)
119
+ def orders(identifier)
120
+ selected = service(identifier)
121
+ token = service_token(selected)
122
+ parser = Parsers::Api.new
123
+ paginate do |page|
124
+ result = request(:get, "/crm/v1/getSalesOrders", "getSalesOrders", token:,
125
+ params: {pageNo: page, noOfRecords: PAGE_SIZE})
126
+ require_hash(result)
127
+ [parser.orders(result, service: selected), result["totalRecords"]]
128
+ end
129
+ end
172
130
 
173
- Date.iso8601(value.to_s)
174
- rescue Date::Error
175
- raise ConfigurationError, "invalid ISO date: #{value.inspect}"
176
- end
131
+ private
177
132
 
178
- def build_agent
179
- Mechanize.new.tap do |agent|
180
- agent.user_agent = "sim_meter_au/#{VERSION} aldi_mobile"
181
- agent.open_timeout = 10
182
- agent.read_timeout = 30
133
+ def clear_session
134
+ @account_token = @services = nil
183
135
  end
184
- end
185
136
 
186
- def find_login_form(login_page)
187
- return unless login_page.respond_to?(:form_with)
188
-
189
- login_page.form_with(id: "login-specific") ||
190
- login_page.form_with(action: LOGIN_FORM_ACTION)
191
- end
137
+ def ensure_authenticated!
138
+ raise AuthenticationError, "Log in before requesting services" unless authenticated?
139
+ end
192
140
 
193
- def authenticated_page?(response_page)
194
- path = response_page.uri.path
195
- on_account_page = path == "/admin" || path.start_with?("/admin/")
196
- has_login_form = !find_login_form(response_page).nil?
197
- has_logout_link = !response_page.link_with(href: %r{/logout/?\z}).nil?
141
+ def service_token(selected)
142
+ # Tenant/app headers invoke password authentication, rather than service switching.
143
+ result = request(:post, "/crm/v1/login", "customerLogin", tenant: false,
144
+ token: @account_token, headers: {"type" => "msisdn"},
145
+ body: {username: international_number(selected.number), password: nil,
146
+ source: "app", accountNo: selected.id})
147
+ require_hash(result)
148
+ primary = result["primaryDevice"]
149
+ unless primary.is_a?(Hash) && primary["accountNo"].to_s == selected.id
150
+ raise UnexpectedResponseError, "ALDImobile returned a different SIM after switching services"
151
+ end
152
+ access_token(result)
153
+ end
198
154
 
199
- !has_login_form && (on_account_page || has_logout_link)
200
- end
155
+ def request(method, path, operation, body: nil, params: {}, headers: {}, tenant: true, token: nil)
156
+ uri = URI("#{@base_url}#{path}")
157
+ uri.query = URI.encode_www_form(params) unless params.empty?
158
+ http_request = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
159
+ request_headers = {
160
+ "Accept" => "application/json", "Content-Type" => "application/json;charset=UTF-8",
161
+ "source" => "Selfcare", "destination" => "CrmServices", "operation" => operation,
162
+ "correlationId" => SecureRandom.uuid, "srDate" => (Time.now.to_f * 1000).to_i.to_s,
163
+ "User-Agent" => "sim_meter_au/#{VERSION} aldi_mobile"
164
+ }
165
+ request_headers["tenancyId"] = TENANCY_ID if tenant
166
+ request_headers["token"] = token if token
167
+ request_headers.merge(headers).each { |key, value| http_request[key] = value }
168
+ http_request.body = JSON.generate(body) if body
169
+ response = @http.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
170
+ open_timeout: 10, read_timeout: 30) { |http| http.request(http_request) }
171
+ status = response.code.to_i
172
+ if status >= 500 || [408, 429].include?(status)
173
+ raise ConnectionError, "ALDImobile returned HTTP #{status}"
174
+ end
175
+ if [401, 403].include?(status)
176
+ clear_session
177
+ raise AuthenticationError, "ALDImobile rejected authentication (HTTP #{status})"
178
+ end
179
+ unless status.between?(200, 299)
180
+ raise UnexpectedResponseError, "ALDImobile returned HTTP #{status}"
181
+ end
182
+ payload = JSON.parse(response.body)
183
+ envelope = payload["response"] if payload.is_a?(Hash)
184
+ unless envelope.is_a?(Hash) && envelope.key?("result")
185
+ raise UnexpectedResponseError, "ALDImobile returned an unexpected API response"
186
+ end
187
+ unless [true, "true"].include?(envelope["success"])
188
+ result = envelope["result"]
189
+ arguments = result["arguments"] if result.is_a?(Hash)
190
+ code = arguments["statusCode"].to_i if arguments.is_a?(Hash)
191
+ code = status if code.nil? || code.zero?
192
+ error_class = if code >= 500 || [408, 429].include?(code)
193
+ ConnectionError
194
+ elsif [401, 403].include?(code) || operation == "customerLogin"
195
+ AuthenticationError
196
+ else
197
+ UnexpectedResponseError
198
+ end
199
+ clear_session if error_class == AuthenticationError
200
+ raise error_class, "ALDImobile #{operation} failed (status #{code})"
201
+ end
202
+ envelope["result"]
203
+ rescue JSON::ParserError
204
+ raise UnexpectedResponseError, "ALDImobile returned invalid JSON"
205
+ rescue SocketError, Timeout::Error, EOFError, IOError, Errno::ECONNREFUSED,
206
+ Errno::ECONNRESET, Errno::EHOSTUNREACH, Errno::ENETUNREACH, OpenSSL::SSL::SSLError => error
207
+ raise ConnectionError, "Could not connect to ALDImobile: #{error.class}"
208
+ end
201
209
 
202
- def authentication_error_message(response_page)
203
- error_element = response_page.at(
204
- ".alert-danger, .form-error-message, .error, [role='alert']"
205
- )
206
- message = error_element&.text.to_s.gsub(/\s+/, " ").strip
210
+ def require_hash(result)
211
+ raise UnexpectedResponseError, "ALDImobile returned an unexpected API result" unless result.is_a?(Hash)
212
+ end
207
213
 
208
- message.empty? ? "ALDImobile login failed" : message
209
- end
214
+ def access_token(result)
215
+ token = result["accessToken"]
216
+ unless token.is_a?(String) && !token.empty?
217
+ raise UnexpectedResponseError, "ALDImobile did not return an access token"
218
+ end
219
+ token
220
+ end
210
221
 
211
- def service_name(link_text, number)
212
- link_text.to_s.sub(number, "").sub(/\s*-\s*\z/, "").strip
213
- end
222
+ def paginate
223
+ records = []
224
+ page = 1
225
+ loop do
226
+ items, total = yield page
227
+ total = Integer(total)
228
+ if total.negative? || (items.empty? && records.length < total)
229
+ raise UnexpectedResponseError, "ALDImobile returned incomplete pagination"
230
+ end
231
+ records.concat(items)
232
+ break if records.length >= total
233
+ raise UnexpectedResponseError, "ALDImobile pagination limit exceeded" if page >= 10_000
234
+ page += 1
235
+ end
236
+ records
237
+ rescue ArgumentError, TypeError
238
+ raise UnexpectedResponseError, "ALDImobile returned an invalid record count"
239
+ end
214
240
 
215
- def normalize_mobile_number(number)
216
- digits = number.gsub(/\D/, "")
217
- digits.start_with?("61") ? "0#{digits.delete_prefix("61")}" : digits
218
- end
241
+ def coerce_date(value)
242
+ return value if value.is_a?(Date)
243
+ Date.iso8601(value.to_s)
244
+ rescue Date::Error
245
+ raise ConfigurationError, "invalid ISO date: #{value.inspect}"
246
+ end
219
247
 
220
- def normalize_identifier_number(identifier)
221
- digits = identifier.gsub(/\D/, "")
222
- return "" if digits.length < 9
248
+ def local_number(value)
249
+ value.to_s.gsub(/\D/, "").sub(/\A61/, "0")
250
+ end
223
251
 
224
- digits.start_with?("61") ? "0#{digits.delete_prefix("61")}" : digits
225
- end
252
+ def international_number(value)
253
+ local_number(value).sub(/\A0/, "61")
254
+ end
226
255
  end
227
256
  end
228
257
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module SimMeterAU
4
- VERSION = "0.1.0"
4
+ VERSION = "0.1.1"
5
5
  end
data/lib/sim_meter_au.rb CHANGED
@@ -7,6 +7,7 @@ require_relative "sim_meter_au/service"
7
7
  require_relative "sim_meter_au/models"
8
8
  require_relative "sim_meter_au/provider"
9
9
  require_relative "sim_meter_au/providers/aldi_mobile"
10
+ require_relative "sim_meter_au/providers/aldi_mobile/parsers/api"
10
11
  require_relative "sim_meter_au/providers/aldi_mobile/parsers/service_details"
11
12
  require_relative "sim_meter_au/providers/aldi_mobile/parsers/usage"
12
13
  require_relative "sim_meter_au/providers/aldi_mobile/parsers/orders"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: sim-meter-au
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Darren Jeacocke
@@ -10,19 +10,45 @@ cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
- name: mechanize
13
+ name: bigdecimal
14
14
  requirement: !ruby/object:Gem::Requirement
15
15
  requirements:
16
- - - "~>"
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '3.1'
19
+ - - "<"
17
20
  - !ruby/object:Gem::Version
18
- version: '2.14'
21
+ version: '5'
19
22
  type: :runtime
20
23
  prerelease: false
21
24
  version_requirements: !ruby/object:Gem::Requirement
22
25
  requirements:
23
- - - "~>"
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '3.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '5'
32
+ - !ruby/object:Gem::Dependency
33
+ name: net-http
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: '0.6'
39
+ - - "<"
40
+ - !ruby/object:Gem::Version
41
+ version: '1'
42
+ type: :runtime
43
+ prerelease: false
44
+ version_requirements: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0.6'
49
+ - - "<"
24
50
  - !ruby/object:Gem::Version
25
- version: '2.14'
51
+ version: '1'
26
52
  - !ruby/object:Gem::Dependency
27
53
  name: dotenv
28
54
  requirement: !ruby/object:Gem::Requirement
@@ -79,6 +105,20 @@ dependencies:
79
105
  - - "~>"
80
106
  - !ruby/object:Gem::Version
81
107
  version: '3.24'
108
+ - !ruby/object:Gem::Dependency
109
+ name: nokogiri
110
+ requirement: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - "~>"
113
+ - !ruby/object:Gem::Version
114
+ version: '1.19'
115
+ type: :development
116
+ prerelease: false
117
+ version_requirements: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - "~>"
120
+ - !ruby/object:Gem::Version
121
+ version: '1.19'
82
122
  description: Exposes mobile services, balances, expiry and usage through provider
83
123
  adapters.
84
124
  email:
@@ -98,6 +138,7 @@ files:
98
138
  - lib/sim_meter_au/models.rb
99
139
  - lib/sim_meter_au/provider.rb
100
140
  - lib/sim_meter_au/providers/aldi_mobile.rb
141
+ - lib/sim_meter_au/providers/aldi_mobile/parsers/api.rb
101
142
  - lib/sim_meter_au/providers/aldi_mobile/parsers/orders.rb
102
143
  - lib/sim_meter_au/providers/aldi_mobile/parsers/service_details.rb
103
144
  - lib/sim_meter_au/providers/aldi_mobile/parsers/usage.rb