-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_post.py
More file actions
1189 lines (994 loc) · 47 KB
/
auto_post.py
File metadata and controls
1189 lines (994 loc) · 47 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import schedule
import threading
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import subprocess
import pyautogui
import pyperclip
import time
import pickle
import os
import json
import asyncio
import websockets
import platform
from selenium.webdriver.chrome.service import Service
import sys
from webdriver_manager.chrome import ChromeDriverManager
from logger_config import get_logger, setup_logging
import logging
# Set up logging globally at the start
setup_logging()
logger = get_logger('auto_post')
# Configure schedule library logging level
logging.getLogger('schedule').setLevel(logging.WARNING) # Only show WARNING and above
class Config:
@staticmethod
def get_app_support_dir():
"""Gets the application support directory for storing logs and data."""
if getattr(sys, 'frozen', False):
# Running as bundled app
app_support = os.path.join(
os.path.expanduser('~/Library/Application Support'),
'Facebook Scheduler'
)
else:
# Running in development
app_support = os.path.dirname(os.path.abspath(__file__))
# Create directory if it doesn't exist
os.makedirs(app_support, exist_ok=True)
return app_support
CONFIG_FILE = os.path.join(get_app_support_dir.__func__(), "group_config.json")
LOG_FILE = os.path.join(get_app_support_dir.__func__(), "auto_post_log.txt")
POST_TEXT = os.getenv("POST_TEXT", "")
IMAGE_PATH = os.getenv("IMAGE_PATH", "")
running_schedules = {} # Track running schedules per group
scheduler_thread = None # Track the scheduler thread
SYSTEM = platform.system()
async def notify_gui_to_refresh(group_name):
"""Notifies GUI to refresh via WebSocket."""
if not group_name.strip():
return
for attempt in range(3):
try:
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send(group_name)
return
except Exception as e:
logger.warning(f"WebSocket error (attempt {attempt + 1}/3): {str(e)}")
await asyncio.sleep(1)
def load_groups():
"""Loads groups and schedules from the configuration file."""
CONFIG_FILE = Config.CONFIG_FILE
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r") as file:
return json.load(file).get("groups", {})
return {}
def verify_login(driver):
"""Verifies if the current session is logged in."""
try:
# Wait for elements to load
time.sleep(3)
# Try different elements that indicate logged-in state
possible_elements = [
"//div[@aria-label='Your profile']",
"//div[@aria-label='Menu']",
"//div[@aria-label='Create']",
"//a[contains(@href, '/me/')]",
"//div[@role='banner']//div[@aria-label='Account']"
]
for xpath in possible_elements:
try:
element = driver.find_element(By.XPATH, xpath)
if element.is_displayed():
logger.info("Login verified - Found element: " + xpath)
return True
except:
continue
logger.warning("Login verification failed - No logged-in elements found")
return False
except Exception as e:
logger.error(f"Error verifying login: {str(e)}")
return False
def facebook_login(driver):
"""Logs into Facebook using saved cookies."""
driver.get("https://www.facebook.com/")
logger.info("Checking for existing cookies for login...")
cookie_path = get_cookie_path()
if os.path.exists(cookie_path):
cookies = pickle.load(open(cookie_path, "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
time.sleep(5)
# Verify login after loading cookies
if verify_login(driver):
logger.info("Successfully logged in using cookies")
return driver
else:
logger.warning("Cookie login failed, need manual login")
# If we get here, either no cookies or cookie login failed
logger.info("Waiting for manual login...")
input("Log in manually and press Enter after you have logged in...")
# Verify login after manual login
if verify_login(driver):
# Save new cookies
pickle.dump(driver.get_cookies(), open(cookie_path, "wb"))
logger.info("New login successful, cookies saved")
return driver
else:
raise Exception("Login verification failed after manual login")
last_log_time = datetime.now()
last_sleep_time = None
SIGNIFICANT_CHANGE_THRESHOLD = 5 # Only log if time changes by more than 5 seconds
active_operation = False # Flag to track if we're in the middle of an operation
def post_in_group(driver, group_url, text, image_path):
"""Posts text and an image to a specified Facebook group."""
global active_operation
active_operation = True # Set flag before starting post operation
driver.get(group_url)
time.sleep(2)
original_failsafe = pyautogui.FAILSAFE
pyautogui.FAILSAFE = False
try:
# Try different possible text labels for the posting area
post_area_labels = [
"//span[text()='Write something...']",
"//span[text()='Create a public post...']",
"//div[text()='Write something...']",
"//div[text()='Create a public post...']",
"//div[text()='Start a discussion...']",
"//div[@aria-label='Create a public post...']",
"//div[@aria-label='Write something...']",
"//div[@aria-label='Create post']",
# More flexible matches
"//span[contains(.,'Write')]",
"//span[contains(.,'Create')]",
"//div[contains(.,'Create a public')]",
"//div[contains(@aria-label,'Create')]",
"//div[contains(@aria-label,'Write')]"
]
posting_area = None
for label in post_area_labels:
try:
posting_area = driver.find_element(By.XPATH, label)
if posting_area.is_displayed():
driver.execute_script("arguments[0].click();", posting_area)
logger.info(f"Found posting area using: {label}")
break
except:
continue
if not posting_area:
raise Exception("Could not find posting area with any known label")
time.sleep(2)
# Try to upload image (optional - post can continue without image)
image_upload_success = False
try:
logger.info("Uploading image...")
# Try multiple selectors for the photo/video button (updated for new Facebook design)
image_button_selectors = [
# New Facebook design - camera icon
"//div[@aria-label='Photo/video']",
"//div[contains(@aria-label, 'Photo/video')]",
"//div[@aria-label='Add photo/video']",
"//div[contains(@aria-label, 'Add photo')]",
"//div[contains(@aria-label, 'Add video')]",
"//div[contains(@aria-label, 'photo')]",
"//div[contains(@aria-label, 'Photo')]",
"//div[contains(@aria-label, 'video')]",
# Camera icon selectors
"//div[@role='button' and contains(@aria-label, 'Photo')]",
"//div[@role='button' and contains(@aria-label, 'photo')]",
"//div[@role='button' and contains(@aria-label, 'camera')]",
"//div[@role='button' and contains(@aria-label, 'Camera')]",
# Icon-based selectors
"//svg[contains(@aria-label, 'photo')]",
"//svg[contains(@aria-label, 'Photo')]",
"//svg[contains(@aria-label, 'camera')]",
"//svg[contains(@aria-label, 'Camera')]",
# Generic media selectors
"//div[contains(@class, 'media') and @role='button']",
"//div[contains(@class, 'photo') and @role='button']",
"//div[contains(@class, 'image') and @role='button']"
]
image_button = None
for selector in image_button_selectors:
try:
image_button = driver.find_element(By.XPATH, selector)
logger.info(f"Found image button using selector: {selector}")
break
except:
continue
if not image_button:
logger.warning("Could not find photo/video button, trying alternative approach...")
# Try clicking on any element that might be the photo button
try:
# Look for common photo button patterns
photo_elements = driver.find_elements(By.XPATH, "//div[contains(@class, 'photo') or contains(@class, 'image') or contains(@class, 'media')]")
for element in photo_elements:
if element.is_displayed() and element.is_enabled():
image_button = element
logger.info("Found image button using alternative approach")
break
# If still not found, try to find any clickable element near the posting area
if not image_button:
logger.info("Trying to find any clickable elements near posting area...")
# Look for any clickable elements that might be media buttons
clickable_elements = driver.find_elements(By.XPATH, "//div[@role='button'] | //button | //span[@role='button']")
for element in clickable_elements:
try:
# Check if element is visible and near the posting area
if element.is_displayed() and element.is_enabled():
# Look for elements that might be media-related
text = element.text.lower()
aria_label = (element.get_attribute('aria-label') or '').lower()
if any(keyword in text or keyword in aria_label for keyword in ['photo', 'video', 'image', 'media', 'camera', 'add']):
image_button = element
logger.info(f"Found potential media button: text='{text}', aria-label='{aria_label}'")
break
except:
continue
except:
pass
if not image_button:
raise Exception("Could not find photo/video button with any known selector")
# Simple approach: Hover and click on the photo/video icon
logger.info("Hovering and clicking on photo/video icon...")
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.move_to_element(image_button).click().perform()
logger.info("Successfully hovered and clicked on photo/video icon")
time.sleep(2) # Wait for file dialog to open
# Use Command+Shift+G to open file dialog and navigate to file
logger.info("Sending Command+Shift+G to open file dialog...")
pyautogui.keyDown("command")
pyautogui.keyDown("shift")
pyautogui.press("g")
pyautogui.keyUp("shift")
pyautogui.keyUp("command")
time.sleep(1)
# Type the file path
logger.info(f"Typing file path: {image_path}")
pyautogui.write(image_path)
time.sleep(1)
pyautogui.press("enter")
time.sleep(1)
pyautogui.press("enter") # Confirm selection
time.sleep(2)
time.sleep(2)
image_upload_success = True
logger.info("Image upload completed successfully")
except Exception as e:
logger.warning(f"Image upload failed: {str(e)}")
logger.info("Continuing with text-only post...")
image_upload_success = False
# Enter post text
logger.info("Attempting to enter post text...")
time.sleep(2)
try:
# Try to find post box using keywords
keywords = ['Create a public post', 'Write something', 'Start a discussion']
post_box = None
for keyword in keywords:
try:
post_box = driver.find_element(By.XPATH, f"//div[contains(text(), '{keyword}')]")
if post_box:
break
except:
continue
if not post_box:
error_message = "Post box not found using any of the keywords."
logger.warning(error_message)
raise Exception(error_message)
driver.execute_script("arguments[0].click();", post_box)
pyperclip.copy(text)
if SYSTEM == 'Darwin': # macOS
pyautogui.keyDown("command")
time.sleep(0.1)
pyautogui.press("v")
time.sleep(0.1)
pyautogui.keyUp("command")
else: # Windows
pyautogui.keyDown("ctrl")
time.sleep(0.1)
pyautogui.press("v")
time.sleep(0.1)
pyautogui.keyUp("ctrl")
time.sleep(2)
except Exception as e:
logger.error(f"Failed to enter text: {str(e)}")
raise
# Click Post button with multiple fallback methods
try:
# First try: Regular click
post_button = driver.find_element(By.XPATH, "//span[text()='Post']")
post_button.click()
except:
try:
# Second try: JavaScript click
post_button = driver.find_element(By.XPATH, "//span[text()='Post']")
driver.execute_script("arguments[0].click();", post_button)
except:
try:
# Third try: Alternative button locator
post_button = driver.find_element(By.XPATH, "//div[@aria-label='Post']")
driver.execute_script("arguments[0].click();", post_button)
except Exception as e:
logger.error(f"Failed to click Post button: {str(e)}")
return False
# Wait for post to complete
time.sleep(5)
logger.info(f"Successfully posted in group: {group_url}")
return True
except Exception as e:
logger.error(f"Failed to post in group {group_url}: {str(e)}")
return False
finally:
active_operation = False # Reset flag when done
pyautogui.FAILSAFE = original_failsafe
def switch_to_business_profile(driver):
"""Switches to the specified business profile."""
try:
time.sleep(2)
logger.info("Switching to the business profile...")
# Try different methods to find the profile menu
profile_selectors = [
"//div[@aria-label='Your profile']",
"//div[@aria-label='Account']",
"//div[@aria-label='Account controls and settings']",
"//div[contains(@aria-label, 'profile')]"
]
account_menu = None
for selector in profile_selectors:
try:
account_menu = driver.find_element(By.XPATH, selector)
if account_menu.is_displayed():
break
except:
continue
if not account_menu:
logger.warning("Could not find profile menu")
return False
account_menu.click()
time.sleep(2)
# Try to find the business profile option
try:
business_profile_option = driver.find_element(By.XPATH, "//span[contains(text(), 'First Class')]")
driver.execute_script("arguments[0].click();", business_profile_option)
time.sleep(2)
return True
except:
logger.warning("Could not find business profile option")
return False
except Exception as e:
logger.error(f"Error switching to business profile: {str(e)}")
return False
def job_func_matches_group(job, group_name):
"""Checks if a scheduled job belongs to a specific group."""
try:
# Get the job's function arguments
job_args = job.job_func.args
# First argument should be the exact group name
return bool(job_args) and job_args[0] == group_name
except:
# If we can't get args, fall back to string matching but be more precise
job_str = str(job.job_func)
# Look for exact group name match
return f"group_name='{group_name}'" in job_str or f"('{group_name}'," in job_str
def main(group_name, group_data):
"""Handles login, profile switching, and posting for a specific group."""
logger.info(f"Executing scheduled post for {group_name} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
chrome_options = Options()
try:
driver = initialize_webdriver()
if not driver:
return False
# Login to Facebook
driver = facebook_login(driver)
# Switch to business profile if needed
profile_type = group_data.get("profile_type", "")
if profile_type == "business":
if not switch_to_business_profile(driver):
logger.warning("Failed to switch to business profile")
return False
# Continue with posting...
success = post_to_groups(driver, group_data, group_name)
return success
except Exception as e:
logger.error(f"Error in main execution: {str(e)}")
return False
finally:
if 'driver' in locals():
driver.quit()
def get_job_count(group_name=None):
"""Gets the total number of scheduled jobs, optionally filtered by group."""
jobs = schedule.get_jobs()
if group_name:
group_jobs = [job for job in jobs if job_func_matches_group(job, group_name)]
return len(group_jobs)
return len(jobs)
def schedule_group_posts(group_name, group_data):
"""Schedules posts for a specific group."""
logger.info(f"Starting scheduling for group: {group_name}")
if not group_data:
logger.error(f"No group data provided for {group_name}")
return False
if "schedules" not in group_data:
logger.error(f"No schedules found in group data for {group_name}")
return False
if not group_data["schedules"]:
logger.warning(f"Empty schedules list for {group_name}")
return False
try:
# Only clear existing schedules for THIS group
jobs_to_remove = [job for job in schedule.get_jobs()
if job_func_matches_group(job, group_name)]
for job in jobs_to_remove:
schedule.cancel_job(job)
logger.info(f"Cleared existing schedule for {group_name}")
logger.info(f"Processing {len(group_data['schedules'])} schedules for {group_name}")
scheduled_jobs = 0
for schedule_entry in group_data["schedules"]:
days = schedule_entry["days"]
start_time = datetime.strptime(schedule_entry["start_time"], "%H:%M")
end_time = datetime.strptime(schedule_entry["end_time"], "%H:%M")
num_posts = schedule_entry["num_posts"]
logger.info(f"Processing schedule for {group_name}: {days} from {start_time.strftime('%H:%M')} to {end_time.strftime('%H:%M')} with {num_posts} posts")
# Calculate available hours
total_hours = (end_time - start_time).seconds // 3600
if total_hours <= 0:
logger.warning(f"Invalid time range for {group_name}: end time must be after start time")
continue
# Select random posting times
selected_hours = random.sample(
range(start_time.hour, end_time.hour + 1),
min(num_posts, total_hours)
)
# Schedule posts for each day
for day in days:
for hour in sorted(selected_hours):
minute = random.randint(0, 59)
post_time = f"{hour:02d}:{minute:02d}"
logger.info(f"Scheduling post for {group_name} on {day} at {post_time}")
job = getattr(schedule.every(), day.lower()).at(post_time).do(
main, group_name, group_data
)
scheduled_jobs += 1
# Add weekly reset schedule only if it doesn't exist
if not any(job.job_func.__name__ == "reset_and_reschedule" for job in schedule.get_jobs()):
reset_job = schedule.every().monday.at("00:00").do(reset_and_reschedule)
logger.info("Weekly reset job scheduled for Monday at 00:00")
logger.debug(f"Created reset job: {reset_job}")
if scheduled_jobs > 0:
running_schedules[group_name] = True
total_jobs = get_job_count()
group_jobs = get_job_count(group_name)
logger.info(f"Completed scheduling for {group_name} with {scheduled_jobs} jobs")
logger.info(f"Total jobs for {group_name}: {group_jobs}")
logger.info(f"Total jobs across all groups: {total_jobs}")
# Force immediate status update
current_jobs = [job for job in schedule.get_jobs()
if job.job_func.__name__ != "reset_and_reschedule"]
if current_jobs:
next_job = min(current_jobs, key=lambda j: j.next_run)
time_until_next = next_job.next_run - datetime.now()
logger.info(f"Status after scheduling {group_name}: {len(current_jobs)} jobs scheduled. "
f"Next job at {next_job.next_run.strftime('%Y-%m-%d %H:%M:%S')} "
f"(in {time_until_next.total_seconds():.0f} seconds)")
# Update shared jobs file
get_scheduled_jobs()
return True
logger.warning(f"No jobs were scheduled for {group_name}")
return False
except Exception as e:
logger.error(f"Error scheduling posts for {group_name}: {str(e)}", exc_info=True)
return False
import concurrent.futures
def reset_and_reschedule():
"""Resets and reschedules all active groups on Monday evening."""
global active_operation, scheduler_thread
logger.info("Starting weekly reset and reschedule process...")
# Store currently running groups
active_groups = {name: True for name, is_running in running_schedules.items() if is_running}
logger.info(f"Active groups to reschedule: {', '.join(active_groups.keys())}")
# Clear all schedules
schedule.clear()
logger.info("Cleared all existing schedules")
# Reload and reschedule active groups
groups = load_groups()
for group_name in active_groups:
if group_name in groups:
logger.info(f"Rescheduling group: {group_name}")
schedule_group_posts(group_name, groups[group_name])
running_schedules[group_name] = True
# Re-add the weekly reset schedule
schedule.every().monday.at("18:00").do(reset_and_reschedule)
logger.info("Reset and rescheduling complete - Next reset on Monday at 18:00")
# Ensure active_operation is False after rescheduling
active_operation = False
# Only start a new scheduler if one isn't already running
if not scheduler_thread or not scheduler_thread.is_alive():
start_scheduler()
else:
logger.info("Scheduler already running, continuing with existing thread")
def start_scheduler():
"""Starts the scheduler in a background thread without blocking the GUI."""
global scheduler_thread
try:
# If there's an existing thread and it's alive, just return it
if scheduler_thread and scheduler_thread.is_alive():
logger.info("Scheduler already running, reusing existing thread")
# Verify the thread is actually running jobs
if schedule.get_jobs():
logger.info(f"Found {len(schedule.get_jobs())} active jobs")
else:
logger.warning("No jobs found, restarting scheduler thread")
scheduler_thread = None
return scheduler_thread
# If there's a dead thread, clean it up
if scheduler_thread:
logger.info("Cleaning up old scheduler thread...")
try:
scheduler_thread.stop_flag = True # Signal thread to stop
scheduler_thread.join(timeout=5) # Wait up to 5 seconds
except Exception as e:
logger.error(f"Error joining old thread: {str(e)}")
scheduler_thread = None
# Start new scheduler thread as daemon
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
scheduler_thread.start()
logger.info("Started new scheduler thread as daemon")
# Verify thread started successfully
time.sleep(1) # Give thread time to start
if scheduler_thread.is_alive():
logger.info("Scheduler thread is running")
else:
logger.error("Scheduler thread failed to start")
return scheduler_thread
except Exception as e:
logger.error(f"Error in start_scheduler: {str(e)}")
return None
def stop_scheduler(group_name):
"""Stops scheduling for a specific group."""
global scheduler_thread
if group_name in running_schedules:
# Get jobs before clearing to count them
jobs_before = len([job for job in schedule.get_jobs()
if job.job_func.__name__ != "reset_and_reschedule"])
# Clear jobs for this group
jobs_to_remove = [job for job in schedule.get_jobs()
if job_func_matches_group(job, group_name)]
for job in jobs_to_remove:
schedule.cancel_job(job)
logger.info(f"Removed scheduled job for {group_name}")
# Remove from running schedules
del running_schedules[group_name]
logger.info(f"Removed {group_name} from running schedules")
# Get remaining jobs after clearing
remaining_jobs = [job for job in schedule.get_jobs()
if job.job_func.__name__ != "reset_and_reschedule"]
# Log immediate status update
if remaining_jobs:
next_job = min(remaining_jobs, key=lambda j: j.next_run)
time_until_next = next_job.next_run - datetime.now()
logger.info(f"Status after stopping {group_name}: {len(remaining_jobs)} jobs remaining. "
f"Next job at {next_job.next_run.strftime('%Y-%m-%d %H:%M:%S')} "
f"(in {time_until_next.total_seconds():.0f} seconds)")
else:
logger.info(f"Status after stopping {group_name}: No jobs remaining")
# If no regular jobs remain, stop the scheduler thread
if scheduler_thread and scheduler_thread.is_alive():
logger.info("No regular jobs remaining, stopping scheduler thread...")
scheduler_thread.stop_flag = True
try:
scheduler_thread.join(timeout=5)
except Exception as e:
logger.error(f"Error stopping scheduler thread: {str(e)}")
finally:
scheduler_thread = None
# Clear all schedules including reset job
schedule.clear()
# Clear jobs file
with open("scheduled_jobs.json", "w") as file:
json.dump([], file, indent=4)
logger.info("Scheduler thread stopped and all schedules cleared")
# Update shared jobs file immediately
get_scheduled_jobs()
logger.info(f"Stopped scheduling for group: {group_name}")
def start_group_scheduler(group_name):
"""Starts scheduling for an individual group."""
global scheduler_thread
groups = load_groups()
if group_name in groups:
# If there's an existing scheduler thread, stop it first
if scheduler_thread and scheduler_thread.is_alive():
logger.info("Stopping existing scheduler thread...")
scheduler_thread.stop_flag = True
try:
scheduler_thread.join(timeout=5)
except Exception as e:
logger.error(f"Error stopping existing scheduler thread: {str(e)}")
finally:
scheduler_thread = None
schedule.clear()
# Schedule the posts
success = schedule_group_posts(group_name, groups[group_name])
if not success:
logger.error(f"Failed to schedule posts for {group_name}")
return False
# Start new scheduler thread
scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
scheduler_thread.start()
logger.info("Started new scheduler thread as daemon")
# Wait for thread to start and verify it's running
time.sleep(1)
if not scheduler_thread.is_alive():
logger.error("Failed to start scheduler thread")
return False
# Force immediate status update
current_jobs = [job for job in schedule.get_jobs()
if job.job_func.__name__ != "reset_and_reschedule"]
if current_jobs:
next_job = min(current_jobs, key=lambda j: j.next_run)
time_until_next = next_job.next_run - datetime.now()
logger.info(f"Status after starting {group_name}: {len(current_jobs)} jobs scheduled. "
f"Next job at {next_job.next_run.strftime('%Y-%m-%d %H:%M:%S')} "
f"(in {time_until_next.total_seconds():.0f} seconds)")
# Update thread state to ensure status is tracked
if scheduler_thread:
scheduler_thread.last_status_check = datetime.now()
scheduler_thread.last_jobs_hash = get_jobs_hash(current_jobs)
scheduler_thread.last_job_count = len(current_jobs)
scheduler_thread.last_logged_job_time = next_job.next_run
else:
logger.info(f"Status after starting {group_name}: No jobs scheduled")
# Update shared jobs file
get_scheduled_jobs()
logger.info(f"Started scheduling for group: {group_name}")
return True
return False
def get_next_post_time(group_name):
"""Fetches the next scheduled post time for a group from the scheduler."""
jobs = schedule.get_jobs()
# Filter jobs for this specific group using exact matching
group_jobs = [job for job in jobs
if job_func_matches_group(job, group_name) # Use helper function
and job.job_func.__name__ != "reset_and_reschedule"] # Exclude reset job
if not group_jobs:
return "N/A"
# Get all future run times for this group's jobs
future_runs = []
current_time = datetime.now()
for job in group_jobs:
next_run = job.next_run
if next_run > current_time:
future_runs.append(next_run)
if not future_runs:
return "N/A"
# Return the earliest future run time
next_run = min(future_runs)
return next_run.strftime("%Y-%m-%d %H:%M:%S")
def get_scheduled_jobs():
"""Retrieves and saves all scheduled jobs to a shared file for external access."""
jobs = schedule.get_jobs()
job_list = []
# Only include non-reset jobs
regular_jobs = [job for job in jobs if job.job_func.__name__ != "reset_and_reschedule"]
for job in regular_jobs:
job_list.append({
"next_run": job.next_run.strftime("%Y-%m-%d %H:%M:%S"),
"job_func": str(job.job_func)
})
# Save scheduled jobs to a shared file
with open("scheduled_jobs.json", "w") as file:
json.dump(job_list, file, indent=4)
# If no regular jobs, write empty list to indicate no scheduled jobs
if not regular_jobs:
with open("scheduled_jobs.json", "w") as file:
json.dump([], file, indent=4)
def run_scheduler():
"""Continuously runs the scheduler without blocking the GUI."""
global last_sleep_time
logger.info("Scheduler started. Waiting for jobs...")
# Store these as thread attributes for external access
current_thread = threading.current_thread()
current_thread.last_status_check = datetime.now()
current_thread.last_jobs_hash = None
current_thread.last_job_count = 0
current_thread.last_logged_job_time = None
current_thread.stop_flag = False
STATUS_CHECK_INTERVAL = 60 # Check status every minute
def get_jobs_hash(jobs):
"""Create a hash of current job schedule to detect changes."""
if not jobs:
return None
return hash(tuple(sorted(str(job.next_run) for job in jobs)))
def update_status(force=False):
"""Updates and logs scheduler status."""
if current_thread.stop_flag:
return []
current_time = datetime.now()
# Get current jobs and filter out reset jobs
current_jobs = schedule.get_jobs()
regular_jobs = [job for job in current_jobs if job.job_func.__name__ != "reset_and_reschedule"]
current_job_count = len(regular_jobs)
# Calculate current jobs hash
current_jobs_hash = get_jobs_hash(regular_jobs)
# Get next job time if any jobs exist
next_job_time = None
time_until_next = None
if regular_jobs:
next_job = min(regular_jobs, key=lambda j: j.next_run)
next_job_time = next_job.next_run
time_until_next = next_job_time - current_time
# Check if we should log status
should_log = force or (
# Log when job count changes
current_job_count != current_thread.last_job_count or
# Log when job schedule changes
current_jobs_hash != current_thread.last_jobs_hash or
# Log when next job is within 5 minutes
(next_job_time and time_until_next.total_seconds() <= 300 and
(not current_thread.last_logged_job_time or
current_thread.last_logged_job_time != next_job_time))
)
if should_log:
if current_job_count > 0:
logger.info(f"Status: {current_job_count} jobs scheduled. "
f"Next job at {next_job_time.strftime('%Y-%m-%d %H:%M:%S')} "
f"(in {time_until_next.total_seconds():.0f} seconds)")
current_thread.last_logged_job_time = next_job_time
else:
logger.info("No regular jobs scheduled, stopping scheduler...")
current_thread.stop_flag = True
current_thread.last_logged_job_time = None
# Clear all schedules including reset job
schedule.clear()
# Ensure jobs file is cleared
with open("scheduled_jobs.json", "w") as file:
json.dump([], file, indent=4)
current_thread.last_status_check = current_time
current_thread.last_job_count = current_job_count
current_thread.last_jobs_hash = current_jobs_hash
# Update shared jobs file whenever status changes
get_scheduled_jobs()
return regular_jobs
try:
# Force initial status update
regular_jobs = update_status(force=True)
while not current_thread.stop_flag:
try:
# Check stop flag first
if current_thread.stop_flag:
break
current_time = datetime.now()
# Run any pending jobs
schedule.run_pending()
# Update status and get current jobs
regular_jobs = update_status()
# Calculate sleep time - shorter interval when no jobs to be more responsive
if regular_jobs:
next_job = min(regular_jobs, key=lambda j: j.next_run)
sleep_time = (next_job.next_run - current_time).total_seconds()
sleep_time = max(1, min(sleep_time, STATUS_CHECK_INTERVAL))
else:
sleep_time = 5 # Check more frequently when no jobs are scheduled
# Check stop flag before sleeping
if current_thread.stop_flag:
break
time.sleep(sleep_time)
except Exception as e:
logger.error(f"Error in scheduler loop: {str(e)}", exc_info=True)
if not current_thread.stop_flag:
time.sleep(5) # Shorter sleep on error to recover faster
finally:
# Cleanup when thread exits
logger.info("Scheduler thread stopping - cleaning up...")
schedule.clear()
with open("scheduled_jobs.json", "w") as file:
json.dump([], file, indent=4)
logger.info("Scheduler thread stopped and cleaned up.")
def fast_forward_scheduler():
"""Fast-forwards the scheduler to the next scheduled job and runs it instantly."""
global active_operation
jobs = schedule.get_jobs()
# Filter out reset jobs to get only posting jobs
posting_jobs = [job for job in jobs if job.job_func.__name__ != "reset_and_reschedule"]
logger.info(f"Total jobs found: {len(jobs)}, Posting jobs: {len(posting_jobs)}")
if not posting_jobs:
logger.warning("No scheduled posting jobs found.")
return "No scheduled posting jobs found."
# Find the next scheduled posting job
next_job = min(posting_jobs, key=lambda job: job.next_run)
logger.info(f"Fast-forwarding to run job scheduled at {next_job.next_run}")
# Manually execute the job
next_job.job_func() # Runs the function tied to the next job
# Step 2: Extract group name from job arguments
try:
job_args = next_job.job_func.args
if not job_args or len(job_args) == 0:
logger.warning("No arguments found for the job, unable to identify the group.")
return "Failed to extract group name."
group_name = job_args[0] # Extract the group name
logger.info(f"Extracted group name: {group_name}")
except Exception as e:
logger.error(f"Error extracting job arguments: {str(e)}")
return "Failed to extract group name."
# Reset and reschedule (this will restart the scheduler with new schedules)
reset_and_reschedule()
# Check if `main()` is running in a background thread
if threading.current_thread() is threading.main_thread():
# If running in the main thread, use `asyncio.run()`
logger.info("running in the main thread")
asyncio.run(notify_gui_to_refresh(group_name))
else:
# If running in a background thread, set a new event loop
logger.info("running in the background thread")
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(notify_gui_to_refresh(group_name))
return f"Fast-forwarded to {next_job.next_run.strftime('%Y-%m-%d %H:%M:%S')}"
def initialize_webdriver():
"""Setup and validate WebDriver with automatic ChromeDriver download."""
try:
logger.info("Initializing Chrome WebDriver...")
# Setup Chrome options