-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset_availability.py
More file actions
186 lines (156 loc) · 6.48 KB
/
Copy pathset_availability.py
File metadata and controls
186 lines (156 loc) · 6.48 KB
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
import contextlib
import os
import time
import zoneinfo
from datetime import datetime, timedelta
from playwright.sync_api import sync_playwright
BASE_URL = os.environ.get("BASE_URL")
USERNAME = os.environ.get("USERNAME")
PASSWORD = os.environ.get("PASSWORD")
_raw_status = os.environ.get("STATUS_CHOICE", "available")
STATUS_CHOICE = _raw_status.lower()
PAGE_TIMEOUT = int(os.environ.get("PAGE_TIMEOUT") or "30000")
MAX_RETRIES = int(os.environ.get("MAX_RETRIES") or "3")
RETRY_DELAY = int(os.environ.get("RETRY_DELAY") or "10")
def validate_env():
required = (
("BASE_URL", BASE_URL),
("USERNAME", USERNAME),
("PASSWORD", PASSWORD),
)
missing = [v for v, val in required if val is None]
if missing:
raise SystemExit(f"Missing required env vars: {', '.join(missing)}")
if STATUS_CHOICE not in ("available", "unavailable"):
raise SystemExit(
f"STATUS_CHOICE must be 'available' or 'unavailable' "
f"(case-insensitive), got '{_raw_status}'"
)
def _today():
"""Return the current date in the America/New_York timezone."""
return datetime.now(zoneinfo.ZoneInfo("America/New_York")).date()
def _build_toggle_urls():
"""Build list of toggle URLs. On Friday, may include Saturday + Monday."""
today = _today()
urls = []
if today.weekday() == 4: # Friday
work_saturday = os.environ.get("WORK_SATURDAY", "false").lower() == "true"
if work_saturday:
saturday = today + timedelta(days=1)
print(f"Friday — including Saturday {saturday.isoformat()}")
urls.append(
f"{BASE_URL}/change-availability-for-tomorrow/"
f"{STATUS_CHOICE}?date={saturday.isoformat()}"
)
monday = today + timedelta(days=3)
print(f"Friday — including Monday {monday.isoformat()}")
urls.append(
f"{BASE_URL}/change-availability-for-tomorrow/"
f"{STATUS_CHOICE}?date={monday.isoformat()}"
)
else:
urls.append(f"{BASE_URL}/change-availability-for-tomorrow/{STATUS_CHOICE}")
return urls
def attempt_set_status():
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(locale="en-US", timezone_id="America/New_York")
page = context.new_page()
try:
print(f"Logging into {BASE_URL}/user/login ...")
page.goto(
f"{BASE_URL}/user/login",
wait_until="domcontentloaded",
timeout=PAGE_TIMEOUT,
)
page.fill("#edit-name", USERNAME, timeout=PAGE_TIMEOUT)
page.fill("#edit-pass", PASSWORD, timeout=PAGE_TIMEOUT)
page.click("#edit-submit", timeout=PAGE_TIMEOUT)
page.wait_for_function(
'!window.location.href.includes("/user/login")',
timeout=PAGE_TIMEOUT,
)
print("Login successful.")
# Build list of URLs to toggle
toggle_urls = _build_toggle_urls()
results = []
for toggle_url in toggle_urls:
print(f"Navigating to {toggle_url} ...")
page.goto(
toggle_url,
wait_until="domcontentloaded",
timeout=PAGE_TIMEOUT,
)
page.wait_for_timeout(4000)
# Handle confirmation dialog
page_content = page.content()
if (
"Make yourself available" in page_content
or "Make yourself unavailable" in page_content
):
print("Confirmation dialog detected.")
page.screenshot(path="confirmation-dialog.png", full_page=True)
try:
page.click("text=Make yourself", timeout=10000)
print("Clicked confirmation.")
except Exception:
print(
"Could not click confirmation — "
"the GET request may have already "
"toggled status."
)
# Wait for the page to settle after toggle/redirect
page.wait_for_load_state("networkidle", timeout=PAGE_TIMEOUT)
page.wait_for_timeout(3000)
page_content = page.content()
if (
"You're made available" in page_content
or "You're made unavailable" in page_content
):
print("SUCCESS: Status change confirmed via message")
results.append("success")
elif f"availunavail-header-top {STATUS_CHOICE}" in page_content:
print("SUCCESS: Status change confirmed via header")
results.append("success")
elif "/user/" in page.url:
print("Back on profile page — assuming success")
results.append("success")
else:
print("WARNING: Could not verify status change")
results.append("unknown")
page.screenshot(path="final-status.png", full_page=True)
if all(r == "success" for r in results):
return "success"
elif any(r == "success" for r in results):
return "success" # partial success still counts
return "unknown"
except Exception as e:
print(f"ERROR: {e}")
with contextlib.suppress(Exception):
page.screenshot(path="error-screenshot.png", full_page=True)
raise
finally:
browser.close()
def main():
validate_env()
last_exception = None
for attempt in range(1, MAX_RETRIES + 1):
try:
result = attempt_set_status()
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"result={result}\n")
return
except Exception as e:
last_exception = e
if attempt < MAX_RETRIES:
print(
f"Attempt {attempt}/{MAX_RETRIES} failed: {e}. "
f"Retrying in {RETRY_DELAY}s..."
)
time.sleep(RETRY_DELAY)
print(f"All {MAX_RETRIES} attempts failed.")
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write("result=failure\n")
raise last_exception
if __name__ == "__main__":
main()