amit01Xindus commited on
Commit
fca0b38
·
verified ·
1 Parent(s): be153ce

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +315 -0
  2. dockerfile +27 -0
  3. gemini.py +151 -0
app.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from flask import Flask, request, jsonify
3
+ import subprocess
4
+ import logging
5
+ from gemini import main
6
+
7
+ # Set up logging
8
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
+ logger = logging.getLogger(__name__)
10
+
11
+ app = Flask(__name__)
12
+
13
+ @app.route('/')
14
+ def hello_world():
15
+ logger.info('Received request for root endpoint')
16
+ return 'Cloud Run Python Script is Running!'
17
+
18
+ # Modify the route to accept the 'user_input' as a URL parameter
19
+ @app.route('/run-script', methods=['POST'])
20
+ def run_script():
21
+ logger.info('Received request to /run-script endpoint')
22
+
23
+ # Get the user_input from URL parameters or request body
24
+ data = request.get_json()
25
+ customer = data.get('customer')
26
+ user = data.get('user')
27
+ pwd = data.get('pwd')
28
+
29
+ logger.info(f'Request Parameters - customer: {customer}, user: {user}')
30
+
31
+ if not customer:
32
+ logger.error('No customer parameter provided!')
33
+ return jsonify({"error": "No customer parameter provided!"}), 400
34
+
35
+ try:
36
+ logger.info(f'Running script with customer: {customer}, user: {user}')
37
+ # Call the `main()` function from infiplex.py and pass the parameters
38
+ main(customer, user, pwd)
39
+
40
+ logger.info('Script ran successfully')
41
+ return jsonify({
42
+ 'status': 'success',
43
+ 'message': f'Processed input: {customer}'
44
+ })
45
+ except Exception as e:
46
+ logger.error(f'Error running script: {e}', exc_info=True)
47
+ return jsonify({
48
+ 'status': 'error',
49
+ 'message': str(e)
50
+ }), 500
51
+
52
+ if __name__ == '__main__':
53
+ logger.info('Starting Flask application')
54
+ app.run(host='0.0.0.0', port=8080)
55
+
56
+
57
+ # from selenium import webdriver
58
+ # from selenium.webdriver.chrome.service import Service
59
+ # from selenium.webdriver.chrome.options import Options
60
+ # from webdriver_manager.chrome import ChromeDriverManager
61
+ # from selenium.webdriver.common.by import By
62
+ # from selenium.webdriver.common.keys import Keys
63
+ # from selenium.webdriver.common.action_chains import ActionChains
64
+ # from selenium.webdriver.support.ui import WebDriverWait
65
+ # from selenium.webdriver.support import expected_conditions as EC
66
+ # import time
67
+ # import sys
68
+
69
+
70
+ # chrome_options = Options()
71
+ # # chrome_options.add_argument("--headless") # Uncomment to run headless
72
+ # chrome_options.add_argument("--no-sandbox")
73
+ # chrome_options.add_argument("--disable-dev-shm-usage")
74
+ # chrome_options.add_argument("start-maximized")
75
+
76
+ # service = Service()
77
+ # driver = webdriver.Chrome(service=service, options=chrome_options)
78
+ # wait = WebDriverWait(driver, 20)
79
+
80
+
81
+
82
+ # driver.get("https://xindus-01.infiplex.com/admin/admin_login.php")
83
+ # driver.maximize_window()
84
+
85
+
86
+ # user_input = sys.argv[0]
87
+
88
+
89
+ # # Step 3: Locate and fill the username field
90
+ # username_field = driver.find_element(By.ID, 'uname') # Replace with the actual element's ID
91
+ # username_field.send_keys('saptarshi@xindus.net')
92
+
93
+ # # Step 4: Locate and fill the password field
94
+ # password_field = driver.find_element(By.ID, 'password') # Replace with the actual element's ID
95
+ # #password_field.send_keys('xindusAdmin95672!')
96
+ # password_field.send_keys('2ZLcrwZu838QBnBYFz4bRK2h5Njt1l')
97
+ # # Step 5: Locate and click the login button
98
+ # login_button = driver.find_element(By.ID, 'submit') # Replace with the actual button's ID
99
+ # login_button.click()
100
+
101
+ # # Wait for login to complete
102
+ # time.sleep(3)
103
+ # print(f"Current URL after login: {driver.current_url}")
104
+ # print(f"Page title after login: {driver.title}")
105
+
106
+ # ######################################################
107
+
108
+ # driver.get("https://xindus-01.infiplex.com//admin/sitearea/siteareaadd.php")
109
+
110
+ # # Wait for the page to load
111
+ # time.sleep(3)
112
+ # print(f"Current URL: {driver.current_url}")
113
+ # print(f"Page title: {driver.title}")
114
+
115
+ # # Check if we're on the right page by looking for the form
116
+ # try:
117
+ # # Wait for the element to be present
118
+ # name_field = WebDriverWait(driver, 10).until(
119
+ # EC.presence_of_element_located((By.ID, "sitearea_name"))
120
+ # )
121
+ # except:
122
+ # print("Element 'sitearea_name' not found. Let's check what's on the page...")
123
+ # # Save page source for debugging
124
+ # with open('/Users/prasanth/Desktop/debug_page.html', 'w') as f:
125
+ # f.write(driver.page_source)
126
+ # print("Page source saved to debug_page.html")
127
+ # # Try to find any input fields to see what's available
128
+ # input_fields = driver.find_elements(By.TAG_NAME, "input")
129
+ # print(f"Found {len(input_fields)} input fields:")
130
+ # for i, field in enumerate(input_fields[:10]): # Show first 10
131
+ # field_id = field.get_attribute("id")
132
+ # field_name = field.get_attribute("name")
133
+ # field_type = field.get_attribute("type")
134
+ # print(f" {i+1}. ID: {field_id}, Name: {field_name}, Type: {field_type}")
135
+ # driver.quit()
136
+ # exit(1)
137
+
138
+ # # Form filling logic (replace with your actual field names and values)
139
+ # name_field.send_keys(user_input)
140
+
141
+ # description_field = driver.find_element(By.ID, "base_folder")
142
+ # description_field.send_keys(user_input)
143
+
144
+ # description_field = driver.find_element(By.ID, "content_section_name")
145
+ # description_field.send_keys(user_input)
146
+
147
+ # rbutton = driver.find_element(By.ID, "_content_section_security_group_all_users_yes")
148
+ # rbutton.click()
149
+
150
+
151
+ # #time.sleep(2) # Adjust wait time as needed
152
+
153
+
154
+ # # Navigate to the "Applications" tab
155
+ # applications_tab = driver.find_element(By.LINK_TEXT, "Applications")
156
+ # applications_tab.click()
157
+
158
+
159
+ # # Select the specific radio button
160
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_325")
161
+ # rbutton.click()
162
+
163
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_320")
164
+ # rbutton.click()
165
+
166
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_317")
167
+ # rbutton.click()
168
+
169
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_342")
170
+ # rbutton.click()
171
+
172
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_322")
173
+ # rbutton.click()
174
+
175
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_346")
176
+ # rbutton.click()
177
+
178
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_393")
179
+ # rbutton.click()
180
+
181
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_387")
182
+ # rbutton.click()
183
+
184
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_336")
185
+ # rbutton.click()
186
+
187
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_31")
188
+ # rbutton.click()
189
+
190
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_195")
191
+ # rbutton.click()
192
+
193
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_293")
194
+ # rbutton.click()
195
+
196
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_5")
197
+ # rbutton.click()
198
+
199
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_384")
200
+ # rbutton.click()
201
+
202
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_340")
203
+ # rbutton.click()
204
+
205
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_344")
206
+ # rbutton.click()
207
+
208
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_3")
209
+ # rbutton.click()
210
+
211
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_334")
212
+ # rbutton.click()
213
+
214
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_327")
215
+ # rbutton.click()
216
+
217
+ # rbutton = driver.find_element(By.ID, "install_app_yes_no_7")
218
+ # rbutton.click()
219
+
220
+ # #time.sleep(2) # Adjust wait time as needed
221
+
222
+
223
+ # #save_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "submit")))
224
+
225
+ # save_buttons = driver.find_elements(By.ID, "submit")
226
+ # save_button = save_buttons[1]
227
+
228
+
229
+
230
+ # time.sleep(2)
231
+
232
+ # if save_button.is_displayed():
233
+ # driver.execute_script("arguments[0].scrollIntoView();", save_button)
234
+ # save_button.click()
235
+ # else:
236
+ # # Handle the case where the button is not visible
237
+ # print("Save button is not visible!")
238
+
239
+ # ############################################################
240
+
241
+ # driver.get("https://xindus-01.infiplex.com/admin/index.php")
242
+
243
+ # links = driver.find_elements(By.TAG_NAME, "a")
244
+
245
+ # # Loop through the links and click on the one with the matching display_name
246
+ # for link in links:
247
+ # href_value = link.get_attribute("href")
248
+ # print(href_value)
249
+
250
+ # if href_value and user_input in href_value: # Check if href_value is not None and contains user_input
251
+ # link.click()
252
+ # break
253
+
254
+ # # Close the browser after some time (optional)
255
+ # time.sleep(1)
256
+ # #input("Form submitted. Press Enter to close the browser...")
257
+
258
+ # try:
259
+ # iframe = WebDriverWait(driver, 10).until(
260
+ # EC.presence_of_element_located((By.TAG_NAME, 'iframe'))
261
+ # )
262
+ # driver.switch_to.frame(iframe)
263
+ # except Exception as e:
264
+ # print(f"Could not find iframe: {e}")
265
+ # # Debugging: print page source or take screenshot
266
+ # with open('debug_page.html', 'w') as f:
267
+ # f.write(driver.page_source)
268
+ # print("Saved page source to debug_page.html")
269
+ # driver.save_screenshot('debug_screenshot.png')
270
+ # print("Saved screenshot to debug_screenshot.png")
271
+
272
+
273
+ # link = WebDriverWait(driver, 10).until(
274
+ # EC.presence_of_element_located((By.CSS_SELECTOR, "a[href*='product_upload']"))
275
+ # )
276
+ # link.click()
277
+ # time.sleep(1)
278
+
279
+
280
+ # link=driver.find_element(By.PARTIAL_LINK_TEXT, "API")
281
+ # link.click()
282
+ # time.sleep(1)
283
+
284
+ # link=driver.find_element(By.PARTIAL_LINK_TEXT, "Create New")
285
+ # link.click()
286
+
287
+ # time.sleep(1)
288
+
289
+ # iframe = driver.find_element(By.XPATH, "//iframe[@src='admin_api_add_edit.php?aid=0']")
290
+ # driver.switch_to.frame(iframe)
291
+
292
+ # name_field = driver.find_element(By.ID, "reference_name")
293
+ # name_field.send_keys("StoreAPI")
294
+
295
+
296
+
297
+ # # Locate all checkboxes in the specific table cell
298
+ # checkboxes = driver.find_elements(By.XPATH, "//td[@style='text-align:left;vertical-align:top;']//input[@type='checkbox']")
299
+
300
+ # # Loop through all checkboxes and select them
301
+ # for checkbox in checkboxes:
302
+ # if not checkbox.is_selected():
303
+ # checkbox.click()
304
+
305
+ # # driver.execute_script("parent.swcm_show_admin_page({page_id:'sitearea_26_510',page_path:'admin/sitearea/26/510/index.php',display_name:'"+user_input+" - Shop'})")
306
+
307
+ # save_button = driver.find_element(By.ID, "submit")
308
+ # save_button.click()
309
+ # time.sleep(5) # Adjust wait time as needed
310
+
311
+
312
+ # input("Press enter to quit the browser")
313
+
314
+ # driver.quit()
315
+
dockerfile ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.12 slim base
2
+ FROM python:3.12-slim
3
+
4
+ # Avoid interactive prompts during apt installs
5
+ ENV DEBIAN_FRONTEND=noninteractive
6
+
7
+ # Install Chrome & dependencies
8
+ RUN apt-get update && apt-get install -y \
9
+ wget gnupg unzip curl \
10
+ fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 \
11
+ libatk1.0-0 libcups2 libdbus-1-3 libgdk-pixbuf2.0-0 \
12
+ libnspr4 libnss3 libx11-xcb1 libxcomposite1 libxdamage1 \
13
+ libxfixes3 libxrandr2 libgbm1 libgtk-3-0 libu2f-udev \
14
+ xdg-utils chromium chromium-driver \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ # Install Python dependencies
18
+ RUN pip install --no-cache-dir selenium webdriver_manager
19
+
20
+ # Set working directory
21
+ WORKDIR /app
22
+
23
+ # Copy your script into the container
24
+ COPY . /app
25
+
26
+ # By default, run your script
27
+ CMD ["python", "infiplex.py"]
gemini.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import time
3
+ import sys
4
+ from selenium import webdriver
5
+ from selenium.webdriver.chrome.service import Service
6
+ from selenium.webdriver.chrome.options import Options
7
+ from selenium.webdriver.common.by import By
8
+ from selenium.webdriver.support.ui import WebDriverWait
9
+ from selenium.webdriver.support import expected_conditions as EC
10
+ from selenium.webdriver import ActionChains
11
+ from webdriver_manager.chrome import ChromeDriverManager
12
+
13
+ # Setup logging
14
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
15
+ logger = logging.getLogger(__name__)
16
+
17
+ def switch_to_iframe_with_text(driver, text_to_find, timeout=5):
18
+ """Switch to the iframe containing specific text."""
19
+ driver.switch_to.default_content()
20
+ all_iframes = driver.find_elements(By.TAG_NAME, "iframe")
21
+ logger.info(f"Found {len(all_iframes)} iframes on page")
22
+
23
+ for idx, iframe in enumerate(all_iframes):
24
+ driver.switch_to.default_content()
25
+ driver.switch_to.frame(iframe)
26
+ try:
27
+ if text_to_find.lower() in driver.page_source.lower():
28
+ logger.info(f"Found '{text_to_find}' in iframe #{idx}")
29
+ return True
30
+ except Exception as e:
31
+ logger.warning(f"Error reading iframe #{idx}: {e}")
32
+ driver.switch_to.default_content()
33
+ return False
34
+
35
+ def main(customer, user, pwd):
36
+ logger.info(f"Starting sitearea creation for customer: {customer}")
37
+
38
+ chrome_options = Options()
39
+ chrome_options.add_argument("--headless=new") # Headless mode
40
+ chrome_options.add_argument("--no-sandbox")
41
+ chrome_options.add_argument("--disable-dev-shm-usage")
42
+ chrome_options.add_argument("start-maximized")
43
+
44
+ service = Service(ChromeDriverManager().install())
45
+ driver = webdriver.Chrome(service=service, options=chrome_options)
46
+ wait = WebDriverWait(driver, 20)
47
+
48
+ try:
49
+ # --- LOGIN ---
50
+ driver.get("https://xindus-01.infiplex.com/admin/admin_login.php")
51
+ wait.until(EC.presence_of_element_located((By.ID, 'uname'))).send_keys(user)
52
+ driver.find_element(By.ID, 'password').send_keys(pwd)
53
+ driver.find_element(By.ID, 'submit').click()
54
+ logger.info("Logged in successfully")
55
+ time.sleep(2)
56
+
57
+ # --- CREATE SITEAREA ---
58
+ driver.get("https://xindus-01.infiplex.com/admin/sitearea/siteareaadd.php")
59
+ wait.until(EC.presence_of_element_located((By.ID, "sitearea_name"))).send_keys(customer)
60
+ driver.find_element(By.ID, "base_folder").send_keys(customer)
61
+ driver.find_element(By.ID, "content_section_name").send_keys(customer)
62
+ driver.find_element(By.ID, "_content_section_security_group_all_users_yes").click()
63
+
64
+ # Applications tab
65
+ driver.find_element(By.LINK_TEXT, "Applications").click()
66
+ app_ids = [325, 320, 317, 342, 322, 346, 393, 387, 336, 31, 195, 293, 5, 384, 340, 344, 3, 334, 327, 7]
67
+ for app_id in app_ids:
68
+ driver.find_element(By.ID, f"install_app_yes_no_{app_id}").click()
69
+
70
+ save_buttons = driver.find_elements(By.ID, "submit")
71
+ save_button = save_buttons[1]
72
+ driver.execute_script("arguments[0].scrollIntoView();", save_button)
73
+ save_button.click()
74
+ logger.info("Sitearea created and saved")
75
+
76
+ # --- NAVIGATE TO CUSTOMER SHOP PAGE ---
77
+ driver.get("https://xindus-01.infiplex.com/admin/index.php")
78
+ links = driver.find_elements(By.TAG_NAME, "a")
79
+ for link in links:
80
+ href_value = link.get_attribute("href")
81
+ if href_value and customer in href_value:
82
+ driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", link)
83
+ driver.execute_script("arguments[0].click();", link)
84
+ logger.info(f"Clicked customer link for {customer}")
85
+ break
86
+ time.sleep(3)
87
+
88
+ # --- SWITCH TO IFRAME WITH TOOLS ---
89
+ logger.info("Searching for iframe containing 'Tools'")
90
+ if not switch_to_iframe_with_text(driver, "Tools"):
91
+ logger.error("Could not find iframe containing 'Tools'")
92
+ return None
93
+
94
+ # --- TOOLS → SHOP ADMIN API ---
95
+ logger.info("Navigating to Tools → Shop Admin API")
96
+ tools_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(., 'Tools')]")))
97
+
98
+ # If hover menu
99
+ try:
100
+ ActionChains(driver).move_to_element(tools_link).perform()
101
+ time.sleep(1)
102
+ except:
103
+ pass
104
+ tools_link.click()
105
+
106
+ api_tab = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(., 'Shop Admin API')]")))
107
+ api_tab.click()
108
+ time.sleep(2)
109
+
110
+ # --- CHECK OR CREATE API KEY ---
111
+ no_results = driver.find_elements(By.XPATH, "//h3[text()='No Results Found']")
112
+ if no_results:
113
+ logger.info("No API key found, creating a new one")
114
+ create_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), 'Create New API Key')]")))
115
+ create_button.click()
116
+ time.sleep(1)
117
+ driver.switch_to.frame(driver.find_element(By.XPATH, "//iframe[contains(@src, 'admin_api_add_edit.php')]"))
118
+ wait.until(EC.presence_of_element_located((By.ID, "reference_name"))).send_keys("StoreAPI")
119
+ checkboxes = driver.find_elements(By.XPATH, "//td[@style='text-align:left;vertical-align:top;']//input[@type='checkbox']")
120
+ for cb in checkboxes:
121
+ if not cb.is_selected():
122
+ cb.click()
123
+ driver.find_element(By.ID, "submit").click()
124
+ logger.info("API key created")
125
+ driver.switch_to.default_content()
126
+ switch_to_iframe_with_text(driver, "Shop Admin API")
127
+
128
+ # --- FETCH API KEY ---
129
+ logger.info("Fetching API key from table")
130
+ api_key_elem = wait.until(EC.presence_of_element_located((By.XPATH, "//tr[td[1]]/td[2]")))
131
+ api_key = api_key_elem.text.strip()
132
+
133
+ if not api_key:
134
+ raise Exception("Found API key element but it was empty.")
135
+
136
+ logger.info(f"API Key for {customer}: {api_key}")
137
+ return api_key
138
+
139
+ except Exception as e:
140
+ logger.error(f"Error: {e}", exc_info=True)
141
+ try:
142
+ with open('debug_page_source.html', 'w', encoding='utf-8') as f:
143
+ f.write(driver.page_source)
144
+ driver.save_screenshot('debug_screenshot.png')
145
+ logger.info("Saved debug files: debug_page_source.html & debug_screenshot.png")
146
+ except:
147
+ pass
148
+ return None
149
+ finally:
150
+ driver.quit()
151
+