예제 #1
0
def valid_duration(representation):
    try:
        Duration(representation)
    except ScaleFormatError:
        return False

    return True
예제 #2
0
def create_entries(
    settings: Settings,
    config: Config,
    spec_row: CollectionRowBlock,
) -> Generator[Dict[str, Any], None, None]:
    r = RecurringEvent(now_date=spec_row.start_date.start)
    times = r.parse(spec_row.recurrence)
    rr = rrule.rrulestr(r.get_RFC_rrule(), dtstart=spec_row.start_date.start)

    if get_row_prop(spec_row, 'not_on'):
        not_r = RecurringEvent(now_date=spec_row.start_date.start)
        not_times = not_r.parse(spec_row.not_on)
        not_dates = {
            d.date()
            for d in rrule.rrulestr(
                not_r.get_RFC_rrule(),
                dtstart=spec_row.start_date.start,
            )
        }

    for dt in rr:
        if get_row_prop(spec_row, 'not_on') and dt.date() in not_dates:
            continue

        to_insert = {
            key: spec_row.get_property(key)
            for key in config.properties_to_sync
        }
        to_insert['title'] = spec_row.title
        if config.tags_property in to_insert:
            to_insert[config.tags_property].append(config.scheduled_tag)
        if config.status_property:
            to_insert[
                config.status_property] = config.status_after_today if dt.date(
                ) >= datetime.date.today() else config.status_before_today

        reminder = None
        if get_row_prop(spec_row, 'reminder'):
            reminder = parse_reminder(spec_row.reminder)

        if get_row_prop(spec_row, 'include_time'):
            if get_row_prop(spec_row, 'duration'):
                duration = datetime.timedelta(
                    minutes=Duration(spec_row.duration).to_minutes())
                to_insert[spec_row.date_field] = NotionDate(dt,
                                                            dt + duration,
                                                            reminder=reminder)
            else:
                to_insert[spec_row.date_field] = NotionDate(dt,
                                                            reminder=reminder)
        else:
            to_insert[spec_row.date_field] = NotionDate(dt.date(),
                                                        reminder=reminder)

        if not settings.dry_run:
            yield to_insert
        logging.info(
            f"Added row '{to_insert.get('title', 'Untitled')}' for {dt:%Y-%m-%d}"
        )
예제 #3
0
class TestDuration(unittest.TestCase):
    def setUp(self):
        self.test_duration = Duration('1d')

    def tearDown(self):
        pass

    def test_repr_has_valid_representation(self):
        self.assertEqual(self.test_duration.__repr__(), '<Duration 1d>')

    def test_parse_simple_valid_scale(self):
        duration_representation = self.test_duration.parse('1d')
        self.assertTrue(isinstance(duration_representation, list))

        duration_representation = duration_representation[0]
        self.assertEqual(duration_representation.value, 1.0)
        self.assertTrue(isinstance(duration_representation.scale, Scale))
        self.assertEqual(duration_representation.scale.representation.short,
                         'd')

    def test_parse_composed_valid_scale(self):
        duration_representation = self.test_duration.parse(
            '1d, 24h and 36 minutes')

        self.assertTrue(isinstance(duration_representation, list))
        self.assertEqual(len(duration_representation), 3)

        first, second, third = duration_representation

        self.assertEqual(first.value, 1.0)
        self.assertTrue(isinstance(first.scale, Scale))
        self.assertEqual(first.scale.representation.short, 'd')

        self.assertEqual(second.value, 24.0)
        self.assertTrue(isinstance(second.scale, Scale))
        self.assertEqual(second.scale.representation.short, 'h')

        self.assertEqual(third.value, 36.0)
        self.assertTrue(isinstance(third.scale, Scale))
        self.assertEqual(third.scale.representation.short, 'm')

    def test_parse_simple_malformed_scale_raises(self):
        self.assertRaises(ScaleFormatError, Duration, 'd1')

    def test_parse_composed_malformed_scale_raises(self):
        self.assertRaises(ScaleFormatError, Duration, '1d h23')
예제 #4
0
def parse_duration(value: Union[None, str, int]) -> int:
    if value:
        if type(value) == int:
            return value
        else:
            return int(Duration(value).to_seconds())
    else:
        return 0
예제 #5
0
 def __init__(self, account: str, start_time: Optional[datetime]):
     end_time = datetime.now().astimezone(pytz.UTC)
     window = Duration(
         "{}s".format((end_time - start_time).total_seconds() + 1))
     super(MetricNamesExporter, self).__init__(account, start_time,
                                               end_time, window)
     self.hosts = []
     self.metrics = []
예제 #6
0
def force_video():
    video_id = app.current_request.query_params.get('videoId')
    channel = app.current_request.query_params.get('channel')
    ttl = app.current_request.query_params.get('ttl')
    try:
        duration = Duration(ttl).to_seconds()
    except (InvalidTokenError, ScaleFormatError, ValueError):
        return Response(body=json.dumps({}), status_code=400)
    if channel not in CHANNELS:
        return Response(body=json.dumps({}), status_code=400)
    if video_id:
        return force_video_id(video_id, channel, duration)
    else:
        return Response(body=json.dumps({}), status_code=400)
예제 #7
0
def main():
    data = yaml.load(open("data/data.yaml"), Loader=yaml.BaseLoader)

    scheduler = AsyncIOScheduler()

    for item in data["distraktor"]:
        interval = Duration(item["interval"]).to_seconds()
        scheduler.add_job(
            reminder,
            trigger="interval",
            args=[item["name"], item["messages"], item["icons"]],
            seconds=interval,
        )

    scheduler.start()

    print("Press Ctrl+{0} to exit".format("Break" if os.name == "nt" else "C"))
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
        pass
예제 #8
0
 async def mute(self,
                ctx,
                target: discord.Member = None,
                duration=None,
                *,
                reason=None):
     if target is None:
         return await ctx.send("Specify a user to mute")
     if duration is None:
         return await ctx.send("Specify a duration")
     allowed = await self.check_hierarchy(ctx, ctx.message.author, target)
     if not allowed:
         return await self.ctx.send(
             "You don't have permission to mute that user")
     if target not in ctx.guild.members:
         return await ctx.send("User is not in guild")
     duration_pre_parse = duration
     try:
         duration = Duration(duration)
         duration = duration.to_seconds()
     except:
         return await ctx.send("Invalid duration")
     infraction_id = await self.generate_infraction_id()
     notified = await self.notify_target(ctx,
                                         target=target,
                                         infraction_type="mute",
                                         reason=reason,
                                         infraction_id=infraction_id,
                                         duration=duration_pre_parse)
     try:
         mute_role = discord.utils.get(ctx.guild.roles,
                                       id=self.config.mute_role)
     except:
         return await ctx.send("Invalid mute role, yell at waffles")
     try:
         await target.add_roles(
             mute_role,
             reason=f"Action by {ctx.message.author} for {reason}")
     except:
         await ctx.send("Error muting user")
     await self.log_infraction(ctx,
                               verb="muted",
                               target=target,
                               mod=ctx.message.author,
                               reason=reason,
                               infraction_type="mute",
                               notified=notified,
                               infraction_id=infraction_id,
                               duration=duration_pre_parse)
     await self.store_infraction(ctx,
                                 infraction_id=infraction_id,
                                 infraction_type="mute",
                                 target=target,
                                 mod=ctx.message.author,
                                 reason=reason,
                                 duration=duration_pre_parse)
     await self.confirm_infraction(ctx,
                                   verb="muted",
                                   target=target,
                                   infraction_id=infraction_id)
     await asyncio.sleep(duration)
     await target.remove_roles(
         mute_role, reason=f"Temporary mute {infraction_id} expired")
     notified = await self.notify_target(
         ctx,
         target=target,
         infraction_type="unmute",
         reason=f"Temporary mute {infraction_id} expired")
     await self.log_infraction(
         ctx,
         verb="unmuted",
         target=target,
         mod=ctx.message.author,
         reason=f"Temporary mute {infraction_id} expired",
         infraction_type="unmute",
         notified=notified)
예제 #9
0
 def duration(self):
     if duration := self.movie.get('duration'):
         duration = duration[2:].lower()
         return Duration(duration).to_minutes()
예제 #10
0
 def setUp(self):
     self.test_duration = Duration('1d')
예제 #11
0
    def set_daily_alarm(for_date=None):
        # Close the blinds a user-specified amount of time before sunrise.
        # Open the blinds at a user specified absolute time.

        # Coordinates for the City of Santa Clara, California
        sun = suntime.Sun(37.354444, -121.969167)

        if for_date is None:
            # If the date to get the sunrise for isn't speficied,
            # schedule the blinds to open for the next future sunrise.
            datetime_now = datetime.now().astimezone()
            date_today = datetime_now.date()
            is_pm = datetime_now.hour > 11
            if is_pm:
                # Sunrise is always in the AM. If the current time is PM,
                # schedule the blinds to open for tomorrow's sunrise.
                date_tomorrow = date_today + timedelta(days=1)
                datetime_sunrise = sun.get_sunrise_time(
                    date_tomorrow).astimezone()

            else:
                # Check if sunrise already happened
                datetime_sunrise_today = sun.get_sunrise_time(
                    date_today).astimezone()

                if datetime_sunrise_today <= datetime_now:
                    # Sunrise already happened today. Schedule the blinds
                    # to open for tomorrow's sunrise.
                    date_tomorrow = date_today + timedelta(days=1)
                    datetime_sunrise = sun.get_sunrise_time(
                        date_tomorrow).astimezone()
                else:
                    # sunrise is in the future today
                    datetime_sunrise = datetime_sunrise_today

        else:
            # Use the date given in the keywork argument.
            datetime_sunrise = sun.get_sunrise_time(for_date).astimezone()

        nonlocal datetime_daily_alarm_close

        seconds_before_sunrise = Duration(
            textbox_duration_before_sunrise.value).to_seconds()
        datetime_daily_alarm_close = (datetime_sunrise -
                                      timedelta(seconds=seconds_before_sunrise)).astimezone()

        # When to open the blinds - get an absolute time from user.
        datetime_parsed_open_at = dateparser.parse(
            textbox_open_blinds_time.value).astimezone()

        nonlocal datetime_daily_alarm_open

        if datetime_parsed_open_at is None:
            text_daily_alarm_status.text_color = "red"
            text_daily_alarm_status.value = "Couldn't parse date from string"
            datetime_daily_alarm_open = None
            return

        datetime_daily_alarm_open = datetime.combine(datetime_sunrise.date(),
                                                     datetime_parsed_open_at.time()).astimezone()

        if datetime_daily_alarm_open <= datetime_daily_alarm_close:
            text_daily_alarm_status.text_color = "red"
            text_daily_alarm_status.value = \
                "Trying to set blinds to open before they close:" + \
                "\ndatetime_daily_alarm_open = " + \
                datetime_daily_alarm_open.strftime(DATETIME_FORMAT_STRING) + \
                "\ndatetime_daily_alarm_close = " + \
                datetime_daily_alarm_close.strftime(DATETIME_FORMAT_STRING)
            datetime_daily_alarm_open = None
            return

        neopixel_ring_clock.put_alarm_region("daily",
                                             datetime_daily_alarm_close, datetime_daily_alarm_open)

        text_daily_alarm_status.text_color = "black"
        text_daily_alarm_status.value = \
            "\nSunrise is:\n" + \
            datetime_sunrise.strftime(DATETIME_FORMAT_STRING) + \
            "\n\nClose blinds at:\n" + \
            datetime_daily_alarm_close.strftime(DATETIME_FORMAT_STRING) + \
            "\n\nThen open blinds at:\n" + \
            datetime_daily_alarm_open.strftime(DATETIME_FORMAT_STRING)
예제 #12
0
def find_incidents_job():
	for domain in config['domains']:
		incidents = [i for i in pd.fetch_incidents(api_key=domain['token']) if i['service']['id'] in domain['services']]
		for incident in incidents:
			created = parse(incident['created_at'])
			service = incident['service']['id']

			if not incident['id'] in current_incidents:
				current_incidents[incident['id']] = {
					"id": incident['id'],
					"status": incident['status'],
					"summary": incident['summary'],
					"domain": domain
				}

			if incident['status'] == "triggered":
				if 'should_resolve' in current_incidents[incident['id']]:
					del current_incidents[incident['id']]['should_resolve']
				if not 'should_ack' in current_incidents[incident['id']]:
					print(f"Found triggered incident {incident['summary']} ({incident['id']}), created at {created}")
					min_ack_duration = Duration(domain['services'][service]['ack']['min'])
					max_ack_duration = Duration(domain['services'][service]['ack']['max'])
					ack_seconds = randint(min_ack_duration.to_seconds(), max_ack_duration.to_seconds())
					current_incidents[incident['id']]['should_ack'] = created + timedelta(seconds=ack_seconds)
					print(f"  Will acknowledge incident {incident['id']} at {current_incidents[incident['id']]['should_ack']}")
			elif incident['status'] == "acknowledged":
				if 'should_ack' in current_incidents[incident['id']]:
					del current_incidents[incident['id']]['should_ack']
				if not 'should_resolve' in current_incidents[incident['id']]:
					print(f"Found acknowledged incident {incident['summary']} ({incident['id']}), created at {created}")
					min_res_duration = Duration(domain['services'][service]['resolve']['min'])
					max_res_duration = Duration(domain['services'][service]['resolve']['max'])
					res_seconds = randint(min_res_duration.to_seconds(), max_res_duration.to_seconds())
					current_incidents[incident['id']]['should_resolve'] = created + timedelta(seconds=res_seconds)
					print(f"  Will resolve incident {incident['id']} at {current_incidents[incident['id']]['should_resolve']}")

		for k, v in dict(current_incidents).items():
			if 'should_ack' in v and v['should_ack'] < datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()):
				print(f"Should ack incident {v['summary']} ({k})")
				acknowledge(v)
			elif 'should_resolve' in v and v['should_resolve'] < datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()):
				print(f"Should resolve incident {v['summary']} ({k})")
				resolve(v)
예제 #13
0
def parse_reminder(reminder_str: str) -> Dict[str, Any]:
    reminder = Duration(reminder_str).parsed_durations[0]
    return {
        'value': int(reminder.value),
        'unit': reminder.scale.representation.long_singular
    }
예제 #14
0
    "--start-time",
    required=True,
    type=click_argument_types.DateTime(),
    help="of the export. either a duration, date or timestamp",
)
@click.option(
    "--end-time",
    required=False,
    default=datetime.now().astimezone(pytz.UTC).replace(second=0, microsecond=0),
    type=click_argument_types.DateTime(),
    help="of the export. either a duration, date or timestamp. default now.",
)
@click.option(
    "--window",
    required=False,
    default=Duration("24h"),
    type=click_argument_types.Duration(),
    help="size of an export window, default 24h",
)
@click.option(
    "--iso-datetime/--no-iso-datetime",
    required=False,
    default=False,
    help="output timestamps in iso format",
)
@click.option(
    "--pretty-print/--no-pretty-print",
    required=False,
    default=False,
    help="output json in pretty print",
)
예제 #15
0
async def timed_restriction(m: types.Message,
                            user: dict,
                            chat: dict,
                            action='ban'):
    try:
        user_request = await bot.get_chat_member(chat['id'], m.from_user.id)
    except:
        await m.reply('Не могу получить информацию о юзере.')
        return
    if not (user_request.can_restrict_members
            or user_request.status == 'creator' or user.get('status', 0) >= 3):
        return await m.reply('Ты куда лезишь?')

    chat_id = chat['id']
    target_user_id = m.reply_to_message.from_user.id
    ban_user = m.reply_to_message.from_user.to_python()
    log_event = LogEvents.TEMPBAN if action == 'ban' else LogEvents.UNMEDIA

    until_date = None

    command, _, msg_args = m.text.partition(' ')
    if msg_args:
        time_tokens, other_tokens = get_time_args(msg_args)
        time_string = ''.join(time_tokens)
        if not time_tokens:
            now = datetime.utcnow().replace()
            until_date = get_next_day_msk().astimezone(
                pytz.utc)  # 21:00 UTC, 00:00 MSK
            time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"
    else:
        other_tokens = None
        now = datetime.utcnow()
        until_date = get_next_day_msk().astimezone(
            pytz.utc)  # 21:00 UTC, 00:00 MSK
        time_string = f"{(until_date.replace(tzinfo=None) - now).total_seconds()}s"

    if valid_duration(time_string):
        duration = Duration(time_string)

        ban_seconds = duration.to_seconds()
        # Чтобы без пермачей
        if ban_seconds <= 30:
            ban_seconds = 31
        if ban_seconds > 31_536_000:
            ban_seconds = 31_536_000 - 1
        human_time = format_seconds(ban_seconds)
        try:
            await bot.restrict_chat_member(
                chat_id,
                target_user_id,
                until_date=until_date if until_date else timedelta(
                    seconds=ban_seconds),
                can_send_messages=action != 'ban',
                can_send_media_messages=False,
                can_send_other_messages=False,
                can_add_web_page_previews=False)
        except Exception as e:
            return await m.reply('штото пошло не так :((')
        kb = types.InlineKeyboardMarkup()
        kb.add(
            types.InlineKeyboardButton('Unban',
                                       callback_data=unban_cb.new(
                                           chat_id=str(chat['id']),
                                           user_id=str(ban_user['id']))))
        await add_log(chat_id, target_user_id, log_event, by=m.from_user.id)

        text_kwargs = {'duration': human_time}
        if other_tokens:
            text_kwargs['reason'] = ' '.join(other_tokens)

        await log(event=log_event,
                  chat=chat,
                  user=ban_user,
                  message_id=m.message_id,
                  admin=user,
                  text_kwargs=text_kwargs,
                  log_kwargs={'reply_markup': kb})
        await mp.track(m.from_user.id, StatsEvents.TEMPBAN, m)

        await m.reply(
            get_restrict_text(chat, action,
                              till_next_day=bool(until_date)).format(
                                  human_time=hbold(human_time)))
    else:
        return await m.reply('Я такие даты не понимаю')
예제 #16
0
from flask_restful import reqparse

from gcp_hashicorp_packer_reaper.gcp import GlobalOptions
from gcp_hashicorp_packer_reaper.logger import log
from gcp_hashicorp_packer_reaper.reaper import (
    delete_expired_instances,
    list_packer_instances,
    stop_expired_instances,
)

options = None

app = Flask(__name__)

parser = reqparse.RequestParser()
parser.add_argument("older_than", type=Duration, default=Duration("2h"))
parser.add_argument("dry_run", type=bool, default=True)


@app.route("/")
def index():
    return jsonify({
        "list": url_for("do_list", _external=True),
        "stop": url_for("do_stop", _external=True),
        "delete": url_for("do_delete", _external=True),
    })


@app.route("/list")
def do_list():
    return do("list")