-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
174 lines (153 loc) Β· 6.89 KB
/
app.py
File metadata and controls
174 lines (153 loc) Β· 6.89 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
import os
import requests
import threading
import time
from datetime import datetime, timedelta
from pyairtable import Table
from flask import Flask, request, jsonify
from dateutil.parser import parse
# --- Configuration ---
print("βοΈ CONFIG Loading environment variables...", flush=True)
AIRTABLE_API_KEY = os.getenv("AIRTABLE_API_KEY")
AIRTABLE_BASE_ID = os.getenv("AIRTABLE_BASE_ID")
GEELARK_API_KEY = os.getenv("GEELARK_API_KEY")
GEELARK_APP_ID = os.getenv("GEELARK_APP_ID")
GEELARK_API_URL = "https://openapi.geelark.com/open/v1"
TABLE_MAIN = "Main Table"
TABLE_MESSAGES = "Telegram Message"
DAY_SETUP = 1
AUTOMATION_NAME = "IG Setup - Day 1"
SEMAPHORE = threading.Semaphore(5)
if not AIRTABLE_API_KEY or not AIRTABLE_BASE_ID:
raise EnvironmentError("β Missing AIRTABLE_API_KEY or AIRTABLE_BASE_ID")
if not GEELARK_API_KEY or not GEELARK_APP_ID:
raise EnvironmentError("β Missing GEELARK_API_KEY or GEELARK_APP_ID")
print("[CONFIG] Initializing Airtable tables...", flush=True)
main_table = Table(AIRTABLE_API_KEY, AIRTABLE_BASE_ID, TABLE_MAIN)
message_table = Table(AIRTABLE_API_KEY, AIRTABLE_BASE_ID, TABLE_MESSAGES)
# --- Global Lock ---
main_lock = threading.Lock()
last_trigger_ts = datetime.utcnow()
# --- Helpers ---
def geelark_api(endpoint, payload=None, method="POST"):
headers = {
"Content-Type": "application/json",
"Authorization": GEELARK_API_KEY,
"appId": GEELARK_APP_ID
}
url = f"{GEELARK_API_URL}/{endpoint.lstrip('/')}"
print(f"π API Calling {endpoint}...", flush=True)
response = requests.post(url, headers=headers, json=payload) if method == "POST" else requests.get(url, headers=headers, params=payload)
if response.ok:
return response.json()
print(f"π¨ ERROR {endpoint} failed: {response.text}", flush=True)
return None
def get_flow_id_by_name(flow_name):
print("π DEBUG Retrieving all available flows...", flush=True)
print(f"βΉοΈ INFO Looking up flowId for '{flow_name}'...", flush=True)
response = geelark_api("/task/flow/list", payload={"page": 1, "pageSize": 100})
print(f"π§Ύ Full flow list response: {response}", flush=True)
if response and "data" in response and "items" in response["data"]:
for flow in response["data"]["items"]:
if flow.get("title") == flow_name:
print(f"β
FOUND Flow ID: {flow.get('id')}", flush=True)
return flow.get("id")
print(f"[ERROR] Flow name '{flow_name}' not found.", flush=True)
return None
def get_today_latest_schedule():
print("π SCHEDULE Calculating latest scheduleAt...", flush=True)
today_str = datetime.utcnow().strftime("%Y-%m-%d")
records = main_table.all(formula=f"AND(IS_SAME({{Date Task ID}}, '{today_str}', 'day'), {{Last Task ID}} != '')")
records.sort(key=lambda r: r['fields'].get("Date Task ID", ''), reverse=True)
if not records:
print("[SCHEDULE] No previous tasks today. Using now().", flush=True)
return datetime.utcnow()
last_start = parse(records[0]['fields'].get("Date Task ID"))
max_duration = max([int(r['fields'].get("Task Duration", 0)) for r in records[:5]])
print(f"[SCHEDULE] Last task ends at: {last_start + timedelta(seconds=max_duration)}", flush=True)
return last_start + timedelta(seconds=max_duration)
def build_param_map(fields):
return {
"Old Username": fields.get("Old Username", ""),
"Password": fields.get("Password", ""),
"Email": fields.get("Email", ""),
"Email PW": fields.get("Email PW", "")
}
def create_rpa_task(profile, flow_id, schedule_at):
param_map = build_param_map(profile['fields'])
payload = {
"flowId": flow_id,
"scheduleAt": int(schedule_at.timestamp() * 1000),
"paramMap": param_map
}
print(f"π TASK Creating task for profile {profile['fields'].get('Old Username')}...", flush=True)
response = geelark_api("/task/rpa/add", payload)
if response and response.get("data"):
return response["data"].get("taskId")
return None
def process_profile(profile, flow_id, schedule_at):
with SEMAPHORE:
record_id = profile["id"]
fields = profile["fields"]
print(f"π PROCESS Processing profile {fields.get('Old Username')}...", flush=True)
if not fields.get("Start Date Setup"):
main_table.update(record_id, {"Start Date Setup": datetime.utcnow().strftime("%Y-%m-%d")})
duration = fields.get("Task Duration")
if not duration:
duration = 270
main_table.update(record_id, {"Task Duration": duration})
task_id = create_rpa_task(profile, flow_id, schedule_at)
if task_id:
print(f"β
SUCCESS Task ID: {task_id}", flush=True)
main_table.update(record_id, {
"Scheduled Today": True,
"Last Task ID": task_id,
"Panel Status": f"Scheduled Day {DAY_SETUP}",
f"Day {DAY_SETUP} Completed?": True
})
message_table.create({
"Summary Report": f"β
Day 1 task scheduled for {fields.get('Old Username')} at {schedule_at}",
"IG Profiles": [record_id],
"Project Status": "Account Setup"
})
phone_id = fields.get("Phone ID")
if phone_id:
print(f"π§Ή CLEANUP Stopping phone {phone_id}...", flush=True)
geelark_api("/phone/stop", {"id": phone_id})
else:
print(f"β FAIL Task creation failed for {fields.get('Old Username')}", flush=True)
main_table.update(record_id, {"Panel Status": "Error"})
# --- Main Logic ---
def run_batches():
while True:
print("π¦ LOAD Loading unscheduled profiles...", flush=True)
profiles = main_table.all(formula=f"AND({{Day Setup}} = {DAY_SETUP}, NOT({{Scheduled Today}}), {{Panel Status}} != 'Error')")
if not profiles:
print("π DONE No more profiles to process.", flush=True)
break
batch = profiles[:5]
print(f"π€ BATCH Scheduling batch of {len(batch)} profiles...", flush=True)
schedule_at = get_today_latest_schedule()
threads = []
for profile in batch:
t = threading.Thread(target=process_profile, args=(profile, flow_id, schedule_at))
threads.append(t)
t.start()
for t in threads:
t.join()
time.sleep(3)
# --- Entry Point ---
app = Flask(__name__)
@app.route("/run", methods=["POST"])
def run():
global flow_id
print("π /run endpoint triggered", flush=True)
flow_id = get_flow_id_by_name(AUTOMATION_NAME)
if flow_id:
run_batches()
return jsonify({"status": "success"}), 200
else:
return jsonify({"status": "error", "message": "Flow ID not found"}), 400
if __name__ == "__main__":
print("π Script Day 1 starting...", flush=True)
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))