def save_settings(self): try: chromepath = self.lineEdit_chromepath.text() timeout = self.spinBox_timeout.value() timeout_confirm = self.spinBox_timeout_confirm.value() sheduled = self.checkBox_sheduled.isChecked() stop_datetime = self.dateTime_stop.dateTime().toPyDateTime() start_datetime = self.dateTime_start.dateTime().toPyDateTime() refresh_count = self.spinBox_refresh_count.value() config = Config.select().get() config.chrome_path = chromepath config.timeout = timeout config.timeout_confirm = timeout_confirm config.sheduled = sheduled config.start_data_time = start_datetime config.stop_data_time = stop_datetime config.refresh_count = refresh_count config.save() except peewee.DoesNotExist: config = Config(chrome_path=chromepath, timeout=timeout, sheduled=sheduled, start_data_time=start_datetime, stop_data_time=stop_datetime, timeout_confirm=timeout_confirm, refresh_count=refresh_count) config.save()
def restore_configs(json): for config in json: Config(key=config["key"], value=config["value"], config_type=config["type"]) arr = Config.select()[:] print("===RESTORED {0} {1}===".format(len(arr), "Configs"))
def load_stored_data(self): try: config = Config.select().get() self.lineEdit_chromepath.setText(config.chrome_path) self.spinBox_timeout.setValue(config.timeout) self.spinBox_timeout_confirm.setValue(config.timeout_confirm) if config.refresh_count: self.spinBox_refresh_count.setValue(config.refresh_count) if config.sheduled: self.checkBox_sheduled.setChecked(config.sheduled) else: self.checkBox_sheduled.setChecked(False) if config.stop_data_time: self.dateTime_stop.setDateTime(config.stop_data_time) if config.start_data_time: self.dateTime_start.setDateTime(config.start_data_time) except peewee.DoesNotExist: # загружаем значения по умолчанию self.lineEdit_chromepath.setText('') self.spinBox_timeout.setValue(30) self.spinBox_timeout_confirm.setValue(5) self.spinBox_refresh_count.setValue(5) self.checkBox_autostart.setChecked(False) self.dateTime_stop.setDateTime(datetime.datetime.now() + datetime.timedelta(days=1))
def __init__(self): # Это здесь нужно для доступа к переменным, методам # и т.д. в файле design.py super().__init__() if not os.path.exists(REPORTS_DIRECTORY_NAME): os.makedirs(REPORTS_DIRECTORY_NAME) self.setupUi(self) self.setWindowTitle('Instagram auto follow confirm v.1.5') self.pushButton_start.clicked.connect(self.btn_start) self.pushButton_stop.clicked.connect(self.btn_stop) self.pushButton_config.clicked.connect(self.btn_settings) self.pushButton_pause.clicked.connect(self.btn_pause) finish = QAction("Quit", self) finish.triggered.connect(self.closeEvent) # таймер для вывода времени работы self.timer = QTimer() self.timer.timeout.connect(self.handleTimer) self.timer.setInterval(1000) # таймер для старта планировщика self.timer_start = QTimer() self.timer_start.timeout.connect(self.handleTimerstart) self.is_startet_sheduler = False self.lg = logging.getLogger('insta') self.threadpool = QThreadPool() self.stop_thread = False self.pause_thread = False self.is_sheduled = False # программа запустилась по расписанию try: config = Config.select().get() if config.start_data_time: # если врямя запуска уже прошло - устанавливаем насильно ручной режим if datetime.datetime.now() > config.start_data_time: config.sheduled = False config.save() # настраиваем внешний вид в зависимости от config.sheduled if config.sheduled: # запуск по планировщику self.set_shedule_mode(config) else: # запуск в ручном режиме self.set_manual_mode(config) except peewee.DoesNotExist: self.log.append('Внимание! необходимо настроить путь к браузеру') config = Config(chrome_path='', timeout=10, timeout_confirm=3, refresh_count=5, auto_start=False) config.save() self.update_ui()
def get_state(name): # if not auth.username() != name: # print(auth.username(), name) # return '', 401 cl = get_cluster(name) it = Config.select().join(Cluster).where(Cluster.name == name).order_by( Config.date_create.desc()) r = [i for i in it] if not r: return '' return jsonify(json.loads(r[0].data))
def get_configs(): arr = [] configs = Config.select() for config in configs: arr.append({ "key": config.key, "value": config.value, "type": config.config_type.type }) print("===SAVING {0} {1}===".format(len(arr), "Configs")) return arr
def btn_stop(self): self.log.append('Нажали Стоп, ждем закрытя браузера') self.stop_thread = True self.timer.stop() if self.is_sheduled: # сбрасываем настроку автозапуска self.is_sheduled = False config = Config.select().get() config.sheduled = self.is_sheduled config.save() self.timer_start.stop() self.set_manual_mode(config)
def do_c_get(self, line): parser = self.parser_c_get() options, args = parser.parse_args(line) line = u" ".join(args) if not line: line="%" k=Config.select(AND(LIKE(Config.q.name, line), Config.q.system==options.system)) fields=[(x.name, "%s (%s)" % (x.value, x.desc)) for x in k] if fields: tui.renderFields(fields) else: raise YokadiException("Configuration key %s does not exist" % line)
def btn_settings(self): dialog = QDialogClass() dialog.exec_() # тут проверяем каждый раз установлен ли запуск по времени config = Config.select().get() # если врямя запуска уже прошло - устанавливаем насильно ручной режим if datetime.datetime.now() > config.start_data_time: config.sheduled = False config.save() if config.sheduled: self.set_shedule_mode(config) else: self.set_manual_mode(config)
def update_ui(self): history_all = Historys.select().count() self.label_countAll.setText(str(history_all)) curr_datetime = datetime.datetime.now() td = datetime.timedelta(days=1) last_24 = curr_datetime - td history_24 = Historys.select().where( Historys.date_time > last_24).count() self.label_count24hour.setText(str(history_24)) config = Config.select().get() history_last_start = Historys.select().where( Historys.date_time > config.last_start_dt).count() self.label_countLaststart.setText(str(history_last_start))
def dump(): # if not auth.username() in ['egeneralov']: # return '{}', 401 r = {} for i in Cluster.select(): try: data = Config.select().join(Cluster).where( Cluster.name == i.name).order_by( Config.date_create.desc()).limit(1).get().data r[i.name] = json.loads(data) except: if i.name != 'favicon.ico': r[i.name] = '' return jsonify(r)
def btn_start(self): # обрабатываем паузу if self.pause_thread: self.pause_thread = False self.pushButton_start.setDisabled(True) self.pushButton_pause.setDisabled(False) return else: #запускам таймер если нажимаем страт вне паузы self.curren_time = datetime.datetime.now() self.timer.start() # загружаем настройки config = Config.select().get() chromepath = config.chrome_path if chromepath == '': QMessageBox.warning(self, 'Внимание', 'Путь к браузеру не указан в настройках!', QMessageBox.Ok) return timeout = config.timeout timeout_confirm = config.timeout_confirm refresh_count = config.refresh_count #self.stop_data_time = config.stop_data_time # сохраняем дату время страта config.last_start_dt = datetime.datetime.now() config.save() self.pushButton_start.setDisabled(True) if self.is_sheduled: self.pushButton_pause.setDisabled(True) else: self.pushButton_pause.setDisabled(False) self.pushButton_stop.setDisabled(False) self.pushButton_config.setDisabled(True) print('Start') worker = Worker(self.insat_monitor, kwargs={ 'chromepath': chromepath, 'timeout': timeout, 'timeout_confirm': timeout_confirm, 'refresh_count': refresh_count }) worker.signals.result.connect(self.print_output) worker.signals.finished.connect(self.thread_complete) worker.signals.progress.connect(self.loging_thread) # Execute self.threadpool.start(worker)
def do_c_set(self, line): """Set a configuration key to value : c_set <key> <value>""" line=line.split() if len(line)<2: raise YokadiException("You should provide two arguments : the parameter key and the value") name=line[0] value=" ".join(line[1:]) p=Config.select(AND(Config.q.name==name, Config.q.system==False)) if p.count()==0: tui.error("Sorry, no parameter match") else: if self.checkParameterValue(name, value): p[0].value=value tui.info("Parameter updated") else: tui.error("Parameter value is incorrect")
def save_report(self): try: curr_datetime = datetime.datetime.now() td = datetime.timedelta(days=1) last_24 = curr_datetime - td history_24 = Historys.select().where( Historys.date_time > last_24).count() config = Config.select().get() history_last_start = Historys.select().where( Historys.date_time > config.last_start_dt).count() file_name = f'{REPORTS_DIRECTORY_NAME}/report_{datetime.datetime.now().strftime("%H%M%S_%m%d%Y")}.txt' with open(file_name, 'w') as file: file.write( f'Окончание работы: {datetime.datetime.now().strftime("%H:%M:%S %m.%d.%Y")}' + '\n') file.write(f'За сутки было принято: {history_24}' + '\n') file.write( f'За время работы было принято: {history_last_start}' + '\n') except: self.lg.exception('save_report')
def handleTimerstart(self): if datetime.datetime.now() > self.start_data_time: # запускаем скрипт if not self.is_sheduled: self.is_sheduled = True self.log.append('Запускаем по расписанию') self.pushButton_stop.setDisabled(False) self.btn_start() # меняем надписи self.label_timer_text.setText('Время работы:') else: #выводим время работы time = datetime.datetime.now() - self.start_data_time self.label_timer.setText(str(time).split('.', 2)[0]) self.label_timer_text_2.setText('Работать осталось:') time = self.stop_data_time - datetime.datetime.now() self.label_timer_2.setText(str(time).split('.', 2)[0]) else: # выводим время до старта time = self.start_data_time - datetime.datetime.now() self.label_timer.setText(str(time).split('.', 2)[0]) self.label_timer_2.setText('0:00:00') if datetime.datetime.now() > self.stop_data_time: # останавливаем скрипт self.log.append('Останавливаем по расписанию') if self.is_sheduled: # останавливаем таймер self.timer_start.stop() # останавливаем процесс self.btn_stop() # сбрасываем настроку автозапуска self.is_sheduled = False config = Config.select().get() config.sheduled = self.is_sheduled config.save() self.set_manual_mode(config)