-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.py
246 lines (216 loc) · 10.4 KB
/
main.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
import platform
import random
from argparse import ArgumentParser
from distutils.util import strtobool
from json import load
from pathlib import Path
from time import sleep, time
from webbrowser import open_new_tab
from playsound import playsound
from requests import Response, get, post
from requests.structures import CaseInsensitiveDict
from rich.console import Console
from rich.text import Text
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from seleniumwire import webdriver
from webdriver_manager.chrome import ChromeDriverManager
if platform.system() == "Windows":
import ctypes
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
config = load(open(f"{Path(__file__).parent}/config/config.json"))
class ProlificUpdater:
def __init__(self, bearer=None):
if bearer:
self.bearer = bearer
else:
self.bearer = "Bearer " + self.get_bearer_token()
self.oldResults = list()
self.participantId = config["Prolific_ID"]
def getRequestFromProlific(self) -> Response:
url = "https://internal-api.prolific.com/api/v1/participant/studies/"
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json, text/plain, */*"
headers["Authorization"] = self.bearer
headers["x-legacy-auth"] = "false"
return get(url, headers=headers, timeout=10)
def reservePlace(self, id) -> Response:
url = "https://internal-api.prolific.com/api/v1/submissions/reserve/"
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = self.bearer
headers["x-legacy-auth"] = "false"
postObj = {"study_id": id, "participant_id": self.participantId}
return post(url, headers=headers, data=postObj)
def getResultsFromProlific(self) -> list:
try:
response = self.getRequestFromProlific()
except Exception:
console.print("[bold red][+] Network error[/bold red]")
return list()
if response.status_code == 200:
return response.json()["results"]
else:
if not strtobool(config["auto_renew_bearer"]):
print("Response error {}".format(response.status_code))
print("Response error {}".format(response.reason))
return list("bearer")
else:
self.bearer = self.get_bearer_token()
self.getResultsFromProlific()
def get_bearer_token(self) -> str:
isLoggedIn = False
# start = time()
while not isLoggedIn:
try:
print("[+] Getting a new bearer token...")
pageurl = "https://auth.prolific.com/u/login"
options = Options()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.add_argument("--disable-web-security")
options.add_argument("log-level=3")
options.add_argument("--disable-site-isolation-trials")
options.add_argument("--headless")
driver = webdriver.Chrome(
service=ChromeService(ChromeDriverManager().install()), options=options
)
print("Driver started")
driver.get(pageurl)
print("Logging in...")
# anchor_url = "https://www.recaptcha.net/recaptcha/api2/anchor?ar=1&k=6LeMGXkUAAAAAOlMpEUm2UOldiq38QgBPJz5-Q-7&co=aHR0cHM6Ly9pbnRlcm5hbC1hcGkucHJvbGlmaWMuY286NDQz&hl=fr&v=gWN_U6xTIPevg0vuq7g1hct0&size=invisible&cb=igv4yino6y0f"
# reCaptcha_response = reCaptchaV3(anchor_url)
# end = time()
# print(f"Captcha solved in {end-start}s")
# Wait for the page to be fully loaded
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//button[@type='submit']")))
# Continue with the rest of the code
driver.execute_script(
f'document.getElementsByName("username")[0].value = "{config["mail"]}"'
)
driver.execute_script(
f'document.getElementsByName("password")[0].value = "{config["password"]}"'
)
driver.find_element(By.XPATH, '//button[@type="submit"]').click()
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "image-container")))
if driver.current_url == "https://auth.prolific.com/u/login":
print("[-] Failed to log in, retrying in 3s...")
sleep(3)
continue
isLoggedIn = True
print("Logged in !")
except Exception:
print("[-] Failed to log in, retrying in 3s...")
sleep(3)
continue;
driver.refresh()
print('[+] Retrieving bearer token from requests...')
while True:
for request in driver.requests:
if "https://internal-api.prolific.com/api/v1/" in request.url:
try:
new_bearer = request.headers["Authorization"]
#print(new_bearer)
print(f"Got a new bearer token ! : {new_bearer}\n")
return new_bearer
except Exception:
pass
sleep(0.5)
def executeCycle(self) -> bool:
results = self.getResultsFromProlific()
print("results : ", results)
if results:
if results != self.oldResults:
currency_symbol = "£" if str(results[0]["study_reward"]["currency"]) == "GBP" else "$"
console.print(
f"""Trying to join {results[0]["name"]} ([bold green]{currency_symbol}{str(float(results[0]["study_reward"]["amount"])/100)}[/bold green])"""
)
reserve_place_res = self.reservePlace(id=results[0]["id"])
if reserve_place_res.status_code == 400:
console.print(f"""[bold red][+] Error code {str(reserve_place_res.json()["error"]["error_code"])}
\nTitle : {str(reserve_place_res.json()["error"]["title"])}
\nDetails : {str(reserve_place_res.json()["error"]["detail"])}""")
self.oldResults = results
return False
else:
a_website = "https://app.prolific.com/studies"
open_new_tab(a_website)
playsound(rf"{Path(__file__).parent}\alert.wav", True)
self.oldResults = results
if results:
return True
else:
if results == ["bearer"]:
exit("Bearer token not valid anymore, need to change it !")
return False
def parseArgs() -> dict:
parser = ArgumentParser(description="Keep updated with Prolific")
parser.add_argument("-b", "--bearer", type=str, help="bearer token")
args = parser.parse_args()
try:
return {"bearer": "Bearer " + args.bearer}
except TypeError:
pass
if platform.system() == "Windows":
class LASTINPUTINFO(ctypes.Structure):
_fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
def get_idle_duration():
lii = LASTINPUTINFO()
lii.cbSize = ctypes.sizeof(LASTINPUTINFO)
if ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lii)):
millis = ctypes.windll.kernel32.GetTickCount() - lii.dwTime
seconds = millis / 1000
return seconds
else:
error_code = (
ctypes.windll.kernel32.GetLastError()
) # Get the last error code
print(f"Error code: {error_code}")
return 0 # Handle the error as needed
def pause_script():
print("Pausing script...")
while True:
idle_duration = get_idle_duration()
if idle_duration > 600: # 10 minutes in seconds
print(
f"Idle Time: {idle_duration} seconds [script paused after 10 minutes of inactivity, to avoid temp ban from the API due to overuse]"
)
sleep(10)
else:
print("Resuming script...")
break
if __name__ == "__main__":
myArguments = parseArgs()
if strtobool(config["auto_renew_bearer"]) and not myArguments:
p_updater = ProlificUpdater()
else:
p_updater = ProlificUpdater(bearer=myArguments["bearer"])
console = Console()
status = console.status("[bold blue] Waiting for study...", spinner="arc")
status.start()
while True:
updateTime = config["wait_time"]
if p_updater.executeCycle():
status.stop()
text = Text("Study found !")
text.stylize("bold red")
console.print(text)
sleep(5)
input("Press enter to resume study search")
status.start()
if strtobool(config["pause_on_idle"]) and platform.system() == "Windows":
idle_duration = get_idle_duration()
if idle_duration >= 600: # 10 minutes in seconds
pause_script()
# else:
# print(f"Idle Time: {idle_duration} seconds [script not paused]") #leave commented if not debugging
# Generate a random integer between -5 and 5
random_offset = random.randint(-5, 5)
# Generate a random number which is +/- 5 from the updateTime variable
random_time = updateTime + random_offset
sleep(
random_time if random_time >= 0 else 0
) # if statement covers edge case, if the user sets up <5 wait_time (I found <20 results in a temp ban), which with the use of random above, could result in a negative number being passed to the sleep()