-
Notifications
You must be signed in to change notification settings - Fork 19
/
api.py
310 lines (275 loc) · 12.8 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
Lidl Plus api
"""
import base64
import html
import logging
import re
from datetime import datetime, timedelta
import requests
from lidlplus.exceptions import (
WebBrowserException,
LoginError,
LegalTermsException,
MissingLogin,
)
try:
from getuseragent import UserAgent
from oic.oic import Client
from oic.utils.authn.client import CLIENT_AUTHN_METHOD
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
from seleniumwire import webdriver
from seleniumwire.utils import decode
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.core.os_manager import ChromeType
except ImportError:
pass
class LidlPlusApi:
"""Lidl Plus api connector"""
_CLIENT_ID = "LidlPlusNativeClient"
_AUTH_API = "https://accounts.lidl.com"
_TICKET_API = "https://tickets.lidlplus.com/api/v2"
_COUPONS_API = "https://coupons.lidlplus.com/api"
_COUPONS_V1_API = "https://coupons.lidlplus.com/app/api/"
_PROFILE_API = "https://profile.lidlplus.com/profile/api"
_APP = "com.lidlplus.app"
_OS = "iOs"
_TIMEOUT = 10
def __init__(self, language, country, refresh_token=""):
self._login_url = ""
self._code_verifier = ""
self._refresh_token = refresh_token
self._expires = None
self._token = ""
self._country = country.upper()
self._language = language.lower()
@property
def refresh_token(self):
"""Lidl Plus api refresh token"""
return self._refresh_token
@property
def token(self):
"""Current token to query api"""
return self._token
def _register_oauth_client(self):
if self._login_url:
return self._login_url
client = Client(client_authn_method=CLIENT_AUTHN_METHOD, client_id=self._CLIENT_ID)
client.provider_config(self._AUTH_API)
code_challenge, self._code_verifier = client.add_code_challenge()
args = {
"client_id": client.client_id,
"response_type": "code",
"scope": ["openid profile offline_access lpprofile lpapis"],
"redirect_uri": f"{self._APP}://callback",
**code_challenge,
}
auth_req = client.construct_AuthorizationRequest(request_args=args)
self._login_url = auth_req.request(client.authorization_endpoint)
return self._login_url
def _init_chrome(self, headless=True):
user_agent = UserAgent(self._OS.lower()).Random()
logging.getLogger("WDM").setLevel(logging.NOTSET)
options = webdriver.ChromeOptions()
if headless:
options.add_argument("headless")
options.add_experimental_option("mobileEmulation", {"userAgent": user_agent})
for chrome_type in [ChromeType.GOOGLE, ChromeType.MSEDGE, ChromeType.CHROMIUM]:
try:
service = Service(ChromeDriverManager(chrome_type=chrome_type).install())
return webdriver.Chrome(service=service, options=options)
except AttributeError:
continue
raise WebBrowserException("Unable to find a suitable Chrome driver")
def _init_firefox(self, headless=True):
user_agent = UserAgent(self._OS.lower()).Random()
logging.getLogger("WDM").setLevel(logging.NOTSET)
options = webdriver.FirefoxOptions()
if headless:
options.headless = True
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", user_agent)
return webdriver.Firefox(
executable_path=GeckoDriverManager().install(),
firefox_binary="/usr/bin/firefox",
options=options,
firefox_profile=profile,
)
def _get_browser(self, headless=True):
try:
return self._init_chrome(headless=headless)
# pylint: disable=broad-except
except Exception as exc1:
try:
return self._init_firefox(headless=headless)
except Exception as exc2:
raise WebBrowserException from exc1 and exc2
def _auth(self, payload):
default_secret = base64.b64encode(f"{self._CLIENT_ID}:secret".encode()).decode()
headers = {
"Authorization": f"Basic {default_secret}",
"Content-Type": "application/x-www-form-urlencoded",
}
kwargs = {"headers": headers, "data": payload, "timeout": self._TIMEOUT}
response = requests.post(f"{self._AUTH_API}/connect/token", **kwargs).json()
self._expires = datetime.utcnow() + timedelta(seconds=response["expires_in"])
self._token = response["access_token"]
self._refresh_token = response["refresh_token"]
def _renew_token(self):
payload = {"refresh_token": self._refresh_token, "grant_type": "refresh_token"}
return self._auth(payload)
def _authorization_code(self, code):
payload = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": f"{self._APP}://callback",
"code_verifier": self._code_verifier,
}
return self._auth(payload)
@property
def _register_link(self):
args = {
"Country": self._country,
"language": f"{self._language}-{self._country}",
}
params = "&".join([f"{key}={value}" for key, value in args.items()])
return f"{self._register_oauth_client()}&{params}"
@staticmethod
def _accept_legal_terms(browser, wait, accept=True):
wait.until(expected_conditions.visibility_of_element_located((By.ID, "checkbox_Accepted"))).click()
if not accept:
title = browser.find_element(By.TAG_NAME, "h2").text
raise LegalTermsException(title)
browser.find_element(By.TAG_NAME, "button").click()
def _parse_code(self, browser, wait, accept_legal_terms=True):
for request in reversed(browser.requests):
if f"{self._AUTH_API}/connect" not in request.url:
continue
location = request.response.headers.get("Location", "")
if "legalTerms" in location:
self._accept_legal_terms(browser, wait, accept=accept_legal_terms)
return self._parse_code(browser, wait, False)
if code := re.findall("code=([0-9A-F]+)", location):
return code[0]
return ""
def _click(self, browser, button, request=""):
del browser.requests
browser.backend.storage.clear_requests()
browser.find_element(*button).click()
self._check_input_error(browser)
if request and browser.wait_for_request(request, 10):
self._check_input_error(browser)
@staticmethod
def _check_input_error(browser):
if errors := browser.find_elements(By.CLASS_NAME, "input-error-message"):
for error in errors:
if error.text:
raise LoginError(error.text)
def _check_login_error(self, browser):
response = browser.wait_for_request(f"{self._AUTH_API}/Account/Login.*", 10).response
body = html.unescape(decode(response.body, response.headers.get("Content-Encoding", "identity")).decode())
if error := re.findall('app-errors="\\{[^:]*?:.(.*?).}', body):
raise LoginError(error[0])
def _check_2fa_auth(self, browser, wait, verify_mode="phone", verify_token_func=None):
if verify_mode not in ["phone", "email"]:
raise ValueError(f'Unknown 2fa-mode "{verify_mode}" - Only "phone" or "email" supported')
response = browser.wait_for_request(f"{self._AUTH_API}/Account/Login.*", 10).response
if "/connect/authorize/callback" not in response.headers.get("Location"):
element = wait.until(expected_conditions.visibility_of_element_located((By.CLASS_NAME, verify_mode)))
element.find_element(By.TAG_NAME, "button").click()
verify_code = verify_token_func()
browser.find_element(By.NAME, "VerificationCode").send_keys(verify_code)
self._click(browser, (By.CLASS_NAME, "role_next"))
def login(self, phone, password, **kwargs):
"""Simulate app auth"""
browser = self._get_browser(headless=kwargs.get("headless", True))
browser.get(self._register_link)
wait = WebDriverWait(browser, 10)
wait.until(expected_conditions.visibility_of_element_located((By.ID, "button_welcome_login"))).click()
wait.until(expected_conditions.visibility_of_element_located((By.NAME, "EmailOrPhone"))).send_keys(phone)
self._click(browser, (By.ID, "button_btn_submit_email"))
self._click(
browser,
(By.ID, "button_btn_submit_email"),
request=f"{self._AUTH_API}/api/phone/exists.*",
)
wait.until(expected_conditions.element_to_be_clickable((By.ID, "field_Password"))).send_keys(password)
self._click(browser, (By.ID, "button_submit"))
self._check_login_error(browser)
self._check_2fa_auth(
browser,
wait,
kwargs.get("verify_mode", "phone"),
kwargs.get("verify_token_func"),
)
browser.wait_for_request(f"{self._AUTH_API}/connect.*")
code = self._parse_code(browser, wait, accept_legal_terms=kwargs.get("accept_legal_terms", True))
self._authorization_code(code)
def _default_headers(self):
if (not self._token and self._refresh_token) or datetime.utcnow() >= self._expires:
self._renew_token()
if not self._token:
raise MissingLogin("You need to login!")
return {
"Authorization": f"Bearer {self._token}",
"App-Version": "999.99.9",
"Operating-System": self._OS,
"App": "com.lidl.eci.lidl.plus",
"Accept-Language": self._language,
}
def tickets(self, only_favorite=False):
"""
Get a list of all tickets.
:param onlyFavorite: A boolean value indicating whether to only retrieve favorite tickets.
If set to True, only favorite tickets will be returned.
If set to False (the default), all tickets will be retrieved.
:type onlyFavorite: bool
"""
url = f"{self._TICKET_API}/{self._country}/tickets"
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
ticket = requests.get(f"{url}?pageNumber=1&onlyFavorite={only_favorite}", **kwargs).json()
tickets = ticket["tickets"]
for i in range(2, int(ticket["totalCount"] / ticket["size"] + 2)):
tickets += requests.get(f"{url}?pageNumber={i}", **kwargs).json()["tickets"]
return tickets
def ticket(self, ticket_id):
"""Get full data of single ticket by id"""
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
url = f"{self._TICKET_API}/{self._country}/tickets"
return requests.get(f"{url}/{ticket_id}", **kwargs).json()
def coupon_promotions_v1(self):
"""Get list of all coupons API V1"""
url = f"{self._COUPONS_V1_API}/v1/promotionslist"
kwargs = {"headers": {**self._default_headers(), "Country": self._country}, "timeout": self._TIMEOUT}
return requests.get(url, **kwargs).json()
def activate_coupon_promotion_v1(self, promotion_id):
"""Activate single coupon by id API V1"""
url = f"{self._COUPONS_V1_API}/v1/promotions/{promotion_id}/activation"
kwargs = {"headers": {**self._default_headers(), "Country": self._country}, "timeout": self._TIMEOUT}
return requests.post(url, **kwargs)
def coupons(self):
"""Get list of all coupons"""
url = f"{self._COUPONS_API}/v2/{self._country}"
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
return requests.get(url, **kwargs).json()
def activate_coupon(self, coupon_id):
"""Activate single coupon by id"""
url = f"{self._COUPONS_API}/v1/{self._country}/{coupon_id}/activation"
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
return requests.post(url, **kwargs).json()
def deactivate_coupon(self, coupon_id):
"""Deactivate single coupon by id"""
url = f"{self._COUPONS_API}/v1/{self._country}/{coupon_id}/activation"
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
return requests.delete(url, **kwargs).json()
def loyalty_id(self):
"""Get your loyalty ID"""
url = f"{self._PROFILE_API}/v1/{self._country}/loyalty"
kwargs = {"headers": self._default_headers(), "timeout": self._TIMEOUT}
response = requests.get(url, **kwargs)
response.raise_for_status()
return response.text