-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
211 lines (164 loc) · 6.62 KB
/
main.py
File metadata and controls
211 lines (164 loc) · 6.62 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
"""
AutoPoll — PollEverywhere Auto-Vote Tool
Usage:
python main.py # Interactive mode (notify + wait for user choice)
python main.py --auto # Auto mode (silent random vote)
python main.py --gui # GUI mode
python main.py --help # Help
On first run, config.json is auto-generated — fill in your cookie and rerun.
"""
import argparse
import sys
import time
import signal
from autopoll.config import Config, ConfigError
from autopoll.auth import Auth, AuthError, CookieExpiredError
from autopoll.monitor import PollMonitor
from autopoll.voter import Voter
from autopoll.logger import setup_logger, VoteHistoryLogger
from autopoll.i18n import _, get_language
logger = setup_logger("autopoll")
# Graceful shutdown flag
_shutdown = False
def signal_handler(signum, frame):
global _shutdown
_shutdown = True
print()
logger.info(_("main.shutdown"))
def print_banner():
lang = get_language()
subtitle = _("banner.subtitle")
# Fixed-width banner: pad subtitle to 36 chars
padded = subtitle.ljust(36)
banner = f"""
\033[96m╔══════════════════════════════════════════╗
║ 🗳️ AutoPoll v2.0.0 🗳️ ║
║ {padded}║
╚══════════════════════════════════════════╝\033[0m
"""
print(banner)
def print_history(history_logger: VoteHistoryLogger):
stats = history_logger.get_stats()
history = history_logger.get_history(limit=10)
print(f"\n\033[96m{'='*45}")
print(f" {_('history.title')}")
print(f"{'='*45}\033[0m")
print(_("history.total", total=stats['total']))
print(f" \033[92m{_('history.success', n=stats['success'])}\033[0m")
print(f" \033[91m{_('history.failed', n=stats['failed'])}\033[0m")
if history:
print(f"\n\033[96m {_('history.recent', n=len(history))}\033[0m")
for record in history:
ts = record['timestamp'][:19]
status_icon = "✅" if record['status'] == 'success' else "❌"
print(f" {status_icon} [{ts}] {record['poll_title'][:25]} → {record['selected_option']}")
print()
def run_cli(config: Config, auto_mode: bool = False):
global _shutdown
signal.signal(signal.SIGINT, signal_handler)
history_logger = VoteHistoryLogger(config.log_dir)
logger.info(_("main.target_host", host=config.host))
mode_key = "main.mode.auto" if auto_mode else "main.mode.interactive"
logger.info(_("main.mode", mode=_(mode_key)))
logger.info(_("main.validating_cookie"))
auth = Auth(host=config.host, cookies=config.cookies)
try:
auth.validate_cookie()
logger.info(_("main.cookie_ok"))
except CookieExpiredError as e:
logger.error(f"❌ {e}")
logger.error(_("main.cookie_expired_update"))
return 1
except AuthError as e:
logger.warning(_("main.cookie_warn", error=e))
logger.info(_("main.continue_anyway"))
monitor = PollMonitor(auth, poll_interval=config.poll_interval)
voter = Voter(auth, history_logger)
monitor.start()
try:
while not _shutdown and monitor.is_running:
try:
poll_info = monitor.check_new_poll()
if poll_info:
poll_uid = poll_info.get('uid', '')
poll_type = poll_info.get('type', 'unknown')
logger.info(_("main.new_poll", type=poll_type, uid=poll_uid))
if config.answer_delay > 0:
logger.info(_("main.answer_delay", delay=config.answer_delay))
time.sleep(config.answer_delay)
if _shutdown:
break
if auto_mode:
result = voter.vote(poll_uid)
else:
result = voter.interactive_vote(
poll_uid,
timeout=config.user_choice_timeout
)
if result and result.get("status") == "success":
monitor.mark_answered(poll_uid)
logger.info(_("main.voted_count", count=monitor.answered_count))
else:
# Do not mark as answered if 'locked', 'failed', or None (error).
# Monitor will wait out the 15s cooldown and check again.
pass
for _tick in range(int(config.poll_interval * 10)):
if _shutdown:
break
time.sleep(0.1)
except CookieExpiredError as e:
logger.error(f"❌ {e}")
logger.info(_("main.cookie_expired_input"))
try:
input()
config = Config()
auth.refresh_session(config.cookies)
auth.validate_cookie()
logger.info(_("main.cookie_refreshed"))
except (ConfigError, AuthError) as e:
logger.error(f"❌ {e}")
continue
except EOFError:
break
finally:
monitor.stop()
auth.close()
print_history(history_logger)
logger.info(_("main.exit"))
return 0
def run_gui(config: Config):
try:
from autopoll.gui import AutoPollGUI
app = AutoPollGUI(config)
app.run()
return 0
except ImportError as e:
logger.error(_("main.gui_error", error=e))
logger.error(_("main.gui_tkinter"))
return 1
def main():
parser = argparse.ArgumentParser(
description=_("argparse.description"),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=_("argparse.epilog"),
)
parser.add_argument('--history', action='store_true', help=_("argparse.history"))
parser.add_argument('--auto', action='store_true', help=_("argparse.auto"))
parser.add_argument('--gui', action='store_true', help=_("argparse.gui"))
parser.add_argument('--config', type=str, default=None, help=_("argparse.config"))
args = parser.parse_args()
print_banner()
try:
config = Config(args.config)
except ConfigError as e:
logger.info(str(e))
return 0
if args.history:
history_logger = VoteHistoryLogger(config.log_dir)
print_history(history_logger)
return 0
if args.gui:
return run_gui(config)
return run_cli(config, auto_mode=args.auto)
if __name__ == '__main__':
sys.exit(main())