Esempio n. 1
0
 def start(self):
     if get_sonarr_info.is_legacy():
         logging.warning(
             'BAZARR can only sync from Sonarr v3 SignalR feed to get real-time update. You should '
             'consider upgrading your version({}).'.format(
                 get_sonarr_info.version()))
     else:
         logging.info('BAZARR trying to connect to Sonarr SignalR feed...')
         self.configure()
         while not self.connection.started:
             try:
                 self.connection.start()
             except ConnectionError:
                 time.sleep(5)
             except json.decoder.JSONDecodeError:
                 logging.error(
                     "BAZARR cannot parse JSON returned by SignalR feed. This is caused by a permissions "
                     "issue when Sonarr try to access its /config/.config directory."
                     "Typically permissions are too permissive - only the user and group Sonarr runs as should have Read/Write permissions (e.g. files 664 / folders 775)"
                     "You should fix permissions on that directory and restart Sonarr. Also, if you're a Docker image "
                     "user, you should make sure you properly defined PUID/PGID environment variables. "
                     "Otherwise, please contact Sonarr support.")
             else:
                 logging.info(
                     'BAZARR SignalR client for Sonarr is connected and waiting for events.'
                 )
             finally:
                 if not args.dev:
                     scheduler.add_job(update_series,
                                       kwargs={'send_event': True},
                                       max_instances=1)
                     scheduler.add_job(sync_episodes,
                                       kwargs={'send_event': True},
                                       max_instances=1)
Esempio n. 2
0
 def on_connect_handler():
     logging.info(
         'BAZARR SignalR client for Radarr is connected and waiting for events.'
     )
     if not args.dev:
         scheduler.add_job(update_movies,
                           kwargs={'send_event': True},
                           max_instances=1)
Esempio n. 3
0
def remember(m):
    spl = m.text.split(' ')
    if len(spl) < 2:
        return
    if spl[0] != 'напомни':
        return
    if spl[1] == 'через' and spl[2] not in ('час', 'минуту', 'секунду',
                                            'неделю', 'год'):
        return
    if spl[1] == 'завтра' or spl[1] == 'сегодня':
        dt = datetime.datetime.now().date()
        if spl[1] == 'завтра':
            dt = datetime.timedelta(days=1) + dt
        dt = datetime.timedelta(days=1) + dt
        # spl[2] = 'в'
        tm = datetime.datetime.strptime(
            spl[3], "%H:%M:%S").time()  # todo: пока с секундами
        date = datetime.datetime.combine(dt, tm)
        what = " ".join(spl[4:])
    elif spl[1] == 'через':
        if spl[2] == 'неделю':
            date = datetime.timedelta(weeks=1) + datetime.datetime.now()
        elif spl[2] == 'час':
            date = datetime.timedelta(hours=1) + datetime.datetime.now()
        elif spl[2] == 'минуту':
            date = datetime.timedelta(minutes=1) + datetime.datetime.now()
        elif spl[2] == 'секунду':
            date = datetime.timedelta(seconds=1) + datetime.datetime.now()
        elif spl[2] == 'год':
            date = datetime.timedelta(days=365) + datetime.datetime.now(
            )  # todo: Придумать нормальный год
        what = " ".join(spl[3:])
    elif re.match(
            r'^([1-2][0-9]|[1-9]|(0[1-9])|[1-9])-(0[1-9]|1[0-2]|[1-9])-(\d{4}) ([0-1][0-9]|[1-9]|2[0-3])(:([0-5]\d)){2}$',
            spl[1] + ' ' + spl[2]):
        date = datetime.datetime.strptime(spl[1] + ' ' + spl[2],
                                          "%d-%m-%Y %H:%M:%S")
        what = " ".join(spl[3:])
    elif re.match(
            r'^([1-2][0-9]|[1-9]|(0[1-9])|[1-9])-(0[1-9]|[1-9]|1[0-2])-(\d{4}) ([0-1][1-9]|[1-9]|2[0-3]):([0-5]\d)$',
            spl[1] + ' ' + spl[2]):
        date = datetime.datetime.strptime(spl[1] + ' ' + spl[2],
                                          "%d-%m-%Y %H:%M")
        what = " ".join(spl[3:])
    else:
        return
    logger.debug(f'remember {date} -- {what}')
    db.save_remind(date, what, m.chat.id)
    bot.send_message(m.chat.id, 'Ок')
    scheduler.add_job(print_msg,
                      'date',
                      run_date=date,
                      args=(
                          f'Напоминаю: {what}',
                          date,
                          m.chat.id,
                      ))
Esempio n. 4
0
def run_process(sender):
    init_sender(sender)
    update_timestamp(sender)

    def update():
        update_subscribers(sender)
        listen_and_deliver(sender)
        update_timestamp(sender)
        print("Waiting", datetime.datetime.now())
        print()

    scheduler.add_job(update, 'interval', minutes=1)
    scheduler.start()
Esempio n. 5
0
def collect_twitter_data():

    # Set the schedule interval in configuration file.
    t = config['schedule.param']['SCHEDULE_TIME']

    job = scheduler.add_job(collect_recent_tweets,
                            start_date=start_date,
                            trigger='interval',
                            minutes=int(t),
                            max_instances=4,
                            coalesce=True)

    sleep_time = datetime.timestamp(job.next_run_time) - int(time.time())
    print("Next Wakeup Call in {}. Next Run Time {} ".format(
        sleep_time, job.next_run_time))
    time.sleep(sleep_time)
Esempio n. 6
0
def main():
    updater = Updater(TELEGRAM_TOKEN, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
    conv_handler = conversation_handler()

    dp.add_handler(conv_handler)
    dp.add_error_handler(error)
    updater.start_polling()
    updater.idle()

    scheduler.add_job(ask_for_counters_data, 'cron', day=1, hour=7)
    scheduler.add_job(ask_for_counters_data, 'cron', day=3, hour=17)
    scheduler.add_job(ask_for_counters_data, 'cron', day=5, hour=7)
    scheduler.add_job(mark_as_paid, 'cron', day=15, hour=7)
Esempio n. 7
0
def schedule_msg(text, schedule, group_id, job=None):
    from resourcess.update import Update
    group = GroupModel.find_by_id(group_id).json()
    func = None
    args = None
    if group['channel']['channel_name'] == 'telegram':
        func = Update.telegram_send_message
        args = [text, int(group['channel']['group_chat_id'])]
    if group['channel']['channel_name'] == 'whatsapp':
        func = Update.whatsapp_send_message
        args = [group['channel']['group_name'], text]
    if job:
        job.modify(func=func, args=args)
        if schedule != job.next_run_time:
            job.reschedule(trigger='date', run_date=schedule)
        return job
    else:
        _id = Job(scheduler).id
        job = scheduler.add_job(id=_id,
                                func=func,
                                run_date=schedule,
                                trigger='date',
                                args=args)
        return job
Esempio n. 8
0
def check_and_submit_tracker(tracker_url):
    messages = []
    error = False

    r_tracker = requests.get(tracker_url)

    #skip unreachable trackers
    if not r_tracker.status_code == requests.codes.ok:
        messages.append("Tracker unreachable %s" % tracker_url)
        return messages, True

    if not error:
        tracker = r_tracker.json()

        if tracker_url != tracker["url"]:
            messages.append("Tracker url inconsistent: %s vs. %s" % (tracker_url, tracker["url"]))

        if not validator.is_valid(tracker):
            messages.append("Tracker invalid %s" % tracker["url"])
            error = True
            for msg in validator.iter_errors(tracker):
                messages.append("Tracker %s not conforming to spec: %s" % (tracker_url,msg.message))

    if not error:
        with tracker_idx.searcher() as searcher:
            if len(searcher.search(Term("url",tracker_url))) == 1:
                messages.append("Skipping known tracker %s" % tracker_url)

    scheduler.add_job(NowTrigger(),index_tracker,[tracker],{})
    scheduler.add_job(NowTrigger(),index_things,[tracker],{})

    if "trackers" in tracker:
        for subtracker in tracker["trackers"]:
            scheduler.add_job(NowTrigger(),crawl_trackers,[subtracker["url"]],{})

    return error,messages
Esempio n. 9
0
    def post(self):
        enabled_languages = request.form.getlist('languages-enabled')
        if len(enabled_languages) != 0:
            TableSettingsLanguages.update({
                TableSettingsLanguages.enabled: 0
            }).execute()
            for code in enabled_languages:
                TableSettingsLanguages.update({
                    TableSettingsLanguages.enabled: 1
                })\
                    .where(TableSettingsLanguages.code2 == code)\
                    .execute()
            event_stream("languages")

        languages_profiles = request.form.get('languages-profiles')
        if languages_profiles:
            existing_ids = TableLanguagesProfiles.select(TableLanguagesProfiles.profileId).dicts()
            existing_ids = list(existing_ids)
            existing = [x['profileId'] for x in existing_ids]
            for item in json.loads(languages_profiles):
                if item['profileId'] in existing:
                    # Update existing profiles
                    TableLanguagesProfiles.update({
                        TableLanguagesProfiles.name: item['name'],
                        TableLanguagesProfiles.cutoff: item['cutoff'] if item['cutoff'] != 'null' else None,
                        TableLanguagesProfiles.items: json.dumps(item['items']),
                        TableLanguagesProfiles.mustContain: item['mustContain'],
                        TableLanguagesProfiles.mustNotContain: item['mustNotContain'],
                    })\
                        .where(TableLanguagesProfiles.profileId == item['profileId'])\
                        .execute()
                    existing.remove(item['profileId'])
                else:
                    # Add new profiles
                    TableLanguagesProfiles.insert({
                        TableLanguagesProfiles.profileId: item['profileId'],
                        TableLanguagesProfiles.name: item['name'],
                        TableLanguagesProfiles.cutoff: item['cutoff'] if item['cutoff'] != 'null' else None,
                        TableLanguagesProfiles.items: json.dumps(item['items']),
                        TableLanguagesProfiles.mustContain: item['mustContain'],
                        TableLanguagesProfiles.mustNotContain: item['mustNotContain'],
                    }).execute()
            for profileId in existing:
                # Unassign this profileId from series and movies
                TableShows.update({
                    TableShows.profileId: None
                }).where(TableShows.profileId == profileId).execute()
                TableMovies.update({
                    TableMovies.profileId: None
                }).where(TableMovies.profileId == profileId).execute()
                # Remove deleted profiles
                TableLanguagesProfiles.delete().where(TableLanguagesProfiles.profileId == profileId).execute()

            update_profile_id_list()
            event_stream("languages")

            if settings.general.getboolean('use_sonarr'):
                scheduler.add_job(list_missing_subtitles, kwargs={'send_event': False})
            if settings.general.getboolean('use_radarr'):
                scheduler.add_job(list_missing_subtitles_movies, kwargs={'send_event': False})

        # Update Notification
        notifications = request.form.getlist('notifications-providers')
        for item in notifications:
            item = json.loads(item)
            TableSettingsNotifier.update({
                TableSettingsNotifier.enabled: item['enabled'],
                TableSettingsNotifier.url: item['url']
            }).where(TableSettingsNotifier.name == item['name']).execute()

        save_settings(zip(request.form.keys(), request.form.listvalues()))
        event_stream("settings")
        return '', 204
Esempio n. 10
0
    bot.send_chat_action(m.chat.id, 'typing')
    bot.send_sticker(m.chat.id, random.choice(andrew_stickers))


if __name__ == '__main__':
    bot.set_update_listener(listener)  # register listener
    db.init()
    logger = logging.getLogger('Wall•e')
    formatter = logging.Formatter(
        '%(asctime)s (%(filename)s:%(lineno)d %(threadName)s) %(levelname)s - %(name)s: "%(message)s"'
    )
    console_output_handler = logging.StreamHandler(sys.stderr)
    console_output_handler.setFormatter(formatter)
    logger.addHandler(console_output_handler)
    logger.setLevel(logging.DEBUG)
    scheduler.add_job(logger.debug, 'interval', seconds=10, args=(' ', ))
    rows = db.execute_read_query(
        f"SELECT datetime, text, from_id FROM reminder")
    if rows:
        for row in rows:
            logger.info(f'{row[0]} {row[1]} {row[2]}')
            scheduler.add_job(print_msg,
                              'date',
                              run_date=row[0],
                              args=(
                                  f'Напоминаю: {row[1]}',
                                  row[0],
                                  row[2],
                              ))

    scheduler.start()
Esempio n. 11
0
def insert_news_of_notice(news):
    job = scheduler.add_job(call_execute_news, 'date', run_date=news.send_date, args=[news])
    news_in_scheduler[news.id] = job
Esempio n. 12
0
def insert_2_scheduler(mailgroup):
    job = scheduler.add_job(call_execute_mails,
                            'date',
                            run_date=mailgroup.send_date,
                            args=[mailgroup])
    news_in_scheduler[mailgroup.id] = job
Esempio n. 13
0
import logging
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from configuration import config
from db import metadata
from tasks import archive, update
from scheduler import scheduler


engine = create_engine(config.DATABASE_URL, echo=True, poolclass=NullPool)
metadata.bind = engine
metadata.create_all()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    scheduler.add_job(archive, trigger='cron', **config.CRON_SETTINGS['ARCHIVE'])
    scheduler.add_job(update, trigger='cron', **config.CRON_SETTINGS['UPDATE'])
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass
Esempio n. 14
0
def insert_job_of_notice(notice):
    job = scheduler.add_job(call_execute_notice,
                            'date',
                            run_date=notice.send_date,
                            args=[notice])
    notice_in_scheduler[notice.id] = job