Coverage for amazonorders/session.py: 65.29%

121 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-12 15:20 +0000

1import logging 

2import sys 

3from io import BytesIO 

4 

5from PIL import Image 

6from bs4 import BeautifulSoup 

7from requests import Session 

8 

9__author__ = "Alex Laird" 

10__copyright__ = "Copyright 2024, Alex Laird" 

11__version__ = "0.0.3" 

12 

13from amazonorders.exception import AmazonOrdersAuthError 

14 

15logger = logging.getLogger(__name__) 

16 

17BASE_URL = "https://www.amazon.com" 

18BASE_HEADERS = { 

19 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", 

20 "Accept-Encoding": "gzip, deflate, br", 

21 "Accept-Language": "en-US,en;q=0.9", 

22 "Cache-Control": "max-age=0", 

23 "Content-Type": "application/x-www-form-urlencoded", 

24 "Origin": BASE_URL, 

25 "Referer": "{}/ap/signin".format(BASE_URL), 

26 "Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"', 

27 "Sec-Ch-Ua-Mobile": "?0", 

28 "Sec-Ch-Ua-Platform": "macOS", 

29 "Sec-Ch-Viewport-Width": "1393", 

30 "Sec-Fetch-Dest": "document", 

31 "Sec-Fetch-Mode": "navigate", 

32 "Sec-Fetch-Site": "same-origin", 

33 "Sec-Fetch-User": "?1", 

34 "Viewport-Width": "1393", 

35 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", 

36} 

37SIGN_IN_FORM_NAME = "signIn" 

38MFA_DEVICE_SELECT_FORM_ID = "auth-select-device-form" 

39MFA_FORM_ID = "auth-mfa-form" 

40CAPTCHA_DIV_ID = "cvf-page-content" 

41CAPTCHA_FORM_CLASS = "cvf-widget-form" 

42 

43 

44class AmazonSession: 

45 def __init__(self, 

46 username, 

47 password, 

48 debug=False, 

49 max_auth_attempts=10) -> None: 

50 self.username = username 

51 self.password = password 

52 

53 self.debug = debug 

54 self.max_auth_attempts = max_auth_attempts 

55 

56 self.session = Session() 

57 self.last_response = None 

58 self.last_response_parsed = None 

59 self.is_authenticated = False 

60 

61 def request(self, method, url, **kwargs): 

62 if "headers" not in kwargs: 

63 kwargs["headers"] = {} 

64 kwargs["headers"].update(BASE_HEADERS) 

65 

66 logger.debug("{} request to {}".format(method, url)) 

67 

68 self.last_response = self.session.request(method, url, **kwargs) 

69 self.last_response_parsed = BeautifulSoup(self.last_response.text, "html.parser") 

70 

71 logger.debug("Response: {} - {}".format(self.last_response.url, self.last_response.status_code)) 

72 

73 if self.debug: 

74 page_name = self._get_page_from_url(self.last_response.url) 

75 with open(page_name, "w") as html_file: 

76 html_file.write(self.last_response.text) 

77 

78 return self.last_response 

79 

80 def get(self, url, **kwargs): 

81 return self.request("GET", url, **kwargs) 

82 

83 def post(self, url, **kwargs): 

84 return self.request("POST", url, **kwargs) 

85 

86 def login(self): 

87 self.get("{}/gp/sign-in.html".format(BASE_URL)) 

88 

89 attempts = 0 

90 while not self.is_authenticated and attempts < self.max_auth_attempts: 

91 if self._is_form_found(SIGN_IN_FORM_NAME, attr_name="name"): 

92 self._sign_in() 

93 elif self._is_form_found(CAPTCHA_FORM_CLASS, attr_name="class"): 

94 self._captcha_submit() 

95 elif self._is_form_found(MFA_DEVICE_SELECT_FORM_ID): 

96 self._mfa_device_select() 

97 elif self._is_form_found(MFA_FORM_ID): 

98 self._mfa_submit() 

99 else: 

100 raise AmazonOrdersAuthError( 

101 "An error occurred, this is an unknown page: {}".format(self.last_response.url)) 

102 

103 if "Hello, sign in" not in self.last_response.text and "nav-item-signout" in self.last_response.text: 

104 self.is_authenticated = True 

105 else: 

106 attempts += 1 

107 

108 if attempts == self.max_auth_attempts: 

109 raise AmazonOrdersAuthError("Max authentication flow attempts reached.") 

110 

111 def close(self): 

112 self.session.close() 

113 

114 def _sign_in(self): 

115 data = self._build_from_form(SIGN_IN_FORM_NAME, 

116 {"email": self.username, 

117 "password": self.password, 

118 "rememberMe": "true"}, 

119 attr_name="name") 

120 

121 self.post(self._get_form_action(SIGN_IN_FORM_NAME), 

122 data=data) 

123 

124 self._handle_errors(critical=True) 

125 

126 def _mfa_device_select(self): 

127 form = self.last_response_parsed.find("form", 

128 {"id": MFA_DEVICE_SELECT_FORM_ID}) 

129 contexts = form.find_all("input", 

130 name="otpDeviceContext") 

131 i = 1 

132 for field in contexts: 

133 print("{}: {}".format(i, field.attrs["value"].strip())) 

134 i += 1 

135 otp_device = int(input("Where would you like your one-time passcode sent? ")) 

136 

137 data = self._build_from_form(MFA_DEVICE_SELECT_FORM_ID, 

138 {"otpDeviceContext": contexts[otp_device - 1].attrs["value"]}) 

139 

140 self.post(self._get_form_action(SIGN_IN_FORM_NAME), 

141 data=data) 

142 

143 self._handle_errors() 

144 

145 def _mfa_submit(self): 

146 otp = input("Enter the one-time passcode sent to your device: ") 

147 

148 # TODO: figure out why Amazon doesn't respect rememberDevice 

149 data = self._build_from_form(MFA_FORM_ID, 

150 {"otpCode": otp, "rememberDevice": ""}) 

151 

152 self.post(self._get_form_action(MFA_FORM_ID), 

153 data=data) 

154 

155 self._handle_errors() 

156 

157 def _captcha_submit(self): 

158 captcha = self.last_response_parsed.find("div", {"id": CAPTCHA_DIV_ID}) 

159 

160 img_src = captcha.find("img", {"alt": "captcha"}).attrs["src"] 

161 img_response = self.session.get(img_src) 

162 img = Image.open(BytesIO(img_response.content)) 

163 img.show() 

164 

165 captcha_response = input("Enter the Captcha seen on the opened image: ") 

166 

167 data = self._build_from_form(CAPTCHA_FORM_CLASS, 

168 {"cvf_captcha_input": captcha_response}, 

169 attr_name="class") 

170 

171 self.post(self._get_form_action(CAPTCHA_FORM_CLASS, 

172 attr_name="class", 

173 prefix="{}/ap/cvf/".format(BASE_URL)), 

174 data=data) 

175 

176 self._handle_errors("cvf-widget-alert", "class") 

177 

178 def _build_from_form(self, form_name, additional_attrs, attr_name="id"): 

179 data = {} 

180 form = self.last_response_parsed.find("form", {attr_name: form_name}) 

181 for field in form.find_all("input"): 

182 try: 

183 data[field["name"]] = field["value"] 

184 except: 

185 pass 

186 data.update(additional_attrs) 

187 return data 

188 

189 def _get_form_action(self, form_name, attr_name="name", prefix=None): 

190 form = self.last_response_parsed.find("form", {attr_name: form_name}) 

191 action = form.attrs.get("action", self.last_response.url) 

192 if prefix and "/" not in action: 

193 action = prefix + action 

194 return action 

195 

196 def _is_form_found(self, form_name, attr_name="id"): 

197 return self.last_response_parsed.find("form", {attr_name: form_name}) is not None 

198 

199 def _get_page_from_url(self, url): 

200 page_name = url.rsplit("/", 1)[-1].split("?")[0] 

201 if not page_name.endswith(".html"): 

202 page_name += ".html" 

203 return page_name 

204 

205 def _handle_errors(self, error_div="auth-error-message-box", attr_name="id", critical=False): 

206 error_div = self.last_response_parsed.find("div", 

207 {attr_name: error_div}) 

208 if error_div: 

209 error_msg = "An error occurred: {}".format(error_div.text.strip()) 

210 

211 if critical: 

212 raise AmazonOrdersAuthError(error_msg) 

213 else: 

214 print(error_msg)