def test_now(self): DateTime.fake(2021, 1, 1, 8, 5, 0) br = Broadcast.now() self.assertTrue(br.is_now()) self.assertTrue(br.is_today()) self.assertIs(br, Broadcast(4, 0)) self.assertIs(br, Broadcast.get_closest())
def set(self): date_time = DateTime() now = date_time.get_now() HH = date_time.get_hour(now) if HH > SYSTEM["broadcast_time"]["FROM"] and HH < SYSTEM["broadcast_time"]["TO"]: self.create_snmp_at_broadcast_time() else: self.create_snmp_at_broadcast_timeout()
def update_data(self, video_status, source_status): date_time = DateTime() opdate = date_time.get_now() child_thread_list = [] profile = ProfileBLL() profile_data = { "video": video_status, "agent": self.agent, "ip": self.ip } self.logger.debug( "update profile data: video{0} - agent{1} - ip{2}".format( video_status, self.agent, self.ip)) child_thread = threading.Thread(target=profile.put, args=( self.id, profile_data, )) child_thread.start() child_thread_list.append(child_thread) human_readable_status = self.get_human_readable_status(source_status) message = """%s %s (ip:%s) %s in host: %s (%s)""" % ( self.name, self.type, self.source, human_readable_status, self.ip, self.agent) log_data = { "host": self.protocol + "://" + self.source, "tag": "status", "msg": message } rslog = { "sev": "Critical", "jname": self.name, "type": self.type, "res": self.source, "desc": human_readable_status, "cat": "Communication", "host": self.agent, "opdate": opdate, "cldate": opdate } self.logger.critical(json.dumps(rslog)) log = LogBLL() child_thread = threading.Thread(target=log.post, args=(log_data, )) child_thread.start() child_thread_list.append(child_thread) """Update local snmp IPTV""" local_snmp = LocalSnmp(profile=self.source + "-" + self.type, name=self.name, status=2) child_thread = threading.Thread(target=local_snmp.set) child_thread.start() child_thread_list.append(child_thread) """ Wait for update database complete """ for child_thread in child_thread_list: child_thread.join() return 0
def get_history_auto_return_main(thomson_host, jobid): query = { "from": 0, "size": 1000, "sort": [{ "@timestamp": { "order": "desc" } }], "_source": ["message"], "query": { "bool": { "must": [{ "match": { "host.keyword": "thomson" } }, { "match": { "message": "tool just" } }, { "match": { "message": "the main source" } }, { "match": { "message": "%s" % (thomson_host) } }, { "match": { "message": "%d" % (jobid) } }], "filter": { "range": { "@timestamp": { "gte": "now-5m", "lte": "now" } } } } } } d_time = DateTime() now = d_time.get_now_as_logtash_fortmat() yesterday = d_time.get_yesterday_as_logtash_fortmat() index = "logstash-%s,logstash-%s" % (now, yesterday) elast = Elasticsearch([{ 'host': host, 'port': port }]).search( index=index, body=query, ) return elast['hits']['hits']
def callback(ch, method, properties, body): date_time = DateTime() print "------------->\n" + str(date_time.get_now_as_human_creadeble( )) + " recieved: " + body + "\n<-------------" logger.info("received " + body) if not body: logger.warning("received " + body + "empty!") return 1 t = threading.Thread(target=return_main, args=(body, )) t.start()
async def admin_moderate(query: types.CallbackQuery, ether: Ether, status: kb.STATUS): user = utils.get_user_from_entity(query.message) moder = query.from_user admin_text = await _gen_order_caption(ether, user, status=status, moder=moder) track = PlaylistItem.from_tg(query.message.audio).add_track_info(user.id, user.first_name, query.message.message_id) try: await query.message.edit_caption(admin_text, reply_markup=kb.admin_unmoderate(ether, status)) except exceptions.MessageNotModified: return # если не отредачилось значит кнопка уже отработалась stats.add(query.message.message_id, moder.id, user.id, str(track), status, DateTime.now()) if status == kb.STATUS.REJECT: # кнопка отмена return communication.cache_add( await BOT.send_message(user.id, texts.ORDER_DENIED.format(track, ether.name)), query.message) await query.message.chat.do('record_audio') msg_to_user: Optional[str] try: if status != kb.STATUS.NOW: await _can_approve_order(ether, query.message.audio) ether_ = None if status == kb.STATUS.NOW else ether new_track = await Broadcast(ether_).add_track(track, audio=query.message.audio) except DuplicateException: when_playing = 'Такой же трек уже принят на этот эфир' msg_to_user = texts.ORDER_ACCEPTED.format(track, ether.name) except NotEnoughSpaceException: when_playing = 'не успел :(' msg_to_user = None communication.cache_add(await BOT.send_audio( user.id, query.message.audio.file_id, reply_markup=await kb.order_choose_day(), caption=texts.ORDER_ACCEPTED_TOOLATE.format(track, ether.name)), query.message ) else: if status == kb.STATUS.NOW: when_playing = 'прямо сейчас!' msg_to_user = texts.ORDER_ACCEPTED_UPNEXT.format(track, when_playing) elif ether.is_now(): minutes_left = round((new_track.start_time - DateTime.now()).seconds / 60) when_playing = f'через {minutes_left} ' + utils.case_by_num(minutes_left, 'минуту', 'минуты', 'минут') msg_to_user = texts.ORDER_ACCEPTED_UPNEXT.format(track, when_playing) else: when_playing = 'Заиграет когда надо' msg_to_user = texts.ORDER_ACCEPTED.format(track, ether.name) if msg_to_user: communication.cache_add(await BOT.send_message(user.id, msg_to_user), query.message) with suppress(exceptions.MessageNotModified): await query.message.edit_caption(admin_text + '\n🕑 ' + when_playing, reply_markup=kb.admin_unmoderate(ether, status))
def start(): on_startup = [lambda _: events.STARTUP_EVENT()] on_shutdown = [lambda _: events.SHUTDOWN_EVENT()] if config.IS_TEST_ENV: from utils import DateTime DateTime.fake(2021, 1, 6, 9, 15, 0) events.STARTUP_EVENT.register( lambda: events.ETHER_BEGIN_EVENT.notify(2, 0)) bot.start_longpoll(on_startup=on_startup, on_shutdown=on_shutdown) # start_server(on_startup=on_startup, on_shutdown=on_shutdown, port=8080) else: on_startup.append(lambda _: bot.set_webhook(config.WEBHOOK_URL)) start_server(on_startup=on_startup, on_shutdown=on_shutdown)
async def order_choose_day() -> InlineKeyboardMarkup: today = DateTime.day_num() btns = [] if (ether_now := Ether.now()) and await Broadcast(ether_now).get_free_time( ) > 3 * 60: # кнопка сейчас если эфир+влазит btns.append(_ikb(NEXT_DAYS[-1], cb.CBOrderTime(today, ether_now.num)))
def get_closest(cls) -> Ether: today = DateTime.day_num() for br in (cls(today, time) for time in others.ETHER_TIMES[today]): if br.is_now() or not br.is_already_play_today(): return br tomorrow = (today + 1) % 7 return cls(tomorrow, 0)
async def watch(self): now = DateTime.now().strftime('%H:%M') if (now != self.__class__.beginTime): return self.logger.info('started notify at %s.' % (now)) for guild in self.guilds: self.logger.debug('guild: %s.' % (guild.name)) channel_name = self.__class__.channel_name channel = self.find_channel(guild, channel_name) if (channel is None): self.logger.error('channel not found by name (%s)' % (channel_name)) break role_name = self.__class__.role_name role = self.find_role(guild, role_name) if (role is None): self.logger.error('role not found by name (%s)' % (role_name)) break await self.notify(channel, 'ワイが神絵師や!', role) self.logger.info('finished notify at %s.' % (now))
def __init__(self, j): self.summary = j['summary'] self.description = None self.start_at = None self.end_at = None if 'description' in j: self.description = j['description'] if 'start' in j and 'dateTime' in j['start']: # 2020-12-24T18:30:00-08:00 formatted = j['start']['dateTime'] self.start_at = DateTime.from_str(formatted) if 'end' in j and 'date' in j['end']: # '2021-01-02' formatted = j['end']['date'] self.end_at = DateTime.from_str(formatted)
async def _get_start_time(self): if not self.ether: return DateTime.now() if self.ether.is_now(): from player import Broadcast return await Broadcast.player.current_track_stop_time() return self.ether.start_time
def build_calendar_ui(self): ''' Builds the actual Calendar UI after making the RESTful request. ''' if not self.device_auth.authorized: self._error('Need to authorize first.') if not self.calendar: self.calendar = Calendar(self.device_auth) events = self.calendar.events() date_today = DateTime.today() sync_at = date_today.formatted() sync_at_message = 'Last updated at %s' % (sync_at) if len(events) <= 0: messages = [sync_at_message] self._notify('No events.', messages=messages) else: root = Column(layout_width=self.width, layout_height=self.height, padding=10) header = Row(parent=root, layout_height=40, wrap_content=False) f_date_today = date_today.formatted(include_day=True, include_time=False) header.add_text_content('Today - %s' % (f_date_today), text_size=4) header.add_image(CALENDAR_40_40, 40, 40, align=ALIGN_RIGHT) content_root = Row(parent=root, layout_height=480, wrap_content=False, outline=True) content = Column(parent=content_root, wrap_content=False) content.add_spacer(10, outline=True) content.add_spacer(20) for event in events: summary = event.summary duration_info = None if event.start_at: include_day = not event.start_at.is_today() duration_info = 'At %s' % (event.start_at.formatted( include_day=include_day)) elif event.end_at: duration_info = 'Ends at %s' % (event.end_at.formatted( include_day=True, include_time=False)) content.add_text_content(summary) if duration_info: content.add_text_content(duration_info) content.add_spacer(height=15) content_root.add_node(content) status = Row(parent=root, layout_height=40, wrap_content=False, outline=True) status.add_text_content(sync_at_message, align=ALIGN_RIGHT) root.add_node(header) root.add_node(content_root) root.add_node(status) self._draw(root)
def get_the_last_active_backup_log_by_jobid(thomson_host, jobid): query = { "from": 0, "size": 1, "_source": ["message"], "sort": [{ "@timestamp": { "order": "desc" } }], "query": { "bool": { "must": [{ "match": { "message": "%s" % (thomson_host) } }, { "match": { "message": "%d" % (jobid) } }, { "match": { "message": "input:backup" } }] } } } d_time = DateTime() now = d_time.get_now_as_logtash_fortmat() yesterday = d_time.get_yesterday_as_logtash_fortmat() index = "logstash-%s,logstash-%s" % (now, yesterday) elast = Elasticsearch([{ 'host': host, 'port': port }]).search( index=index, body=query, ) return elast['hits']['hits']
async def watch(self): now = DateTime.now() self.logger.debug('started execution disconnect at %s.' % (now)) await self.check_awake(self.guilds, now) for guild in self.guilds: self.logger.debug('guild: %s.' % (guild.name)) if (not await self.is_executable(guild, now)): continue for voice_channel in guild.voice_channels: self.logger.debug('voice_channel: %s.' % (voice_channel.name)) await self.disconnect(guild, voice_channel, now) self.logger.debug('finished execution disconnect at %s.' % (now))
async def do_sleep(self, minutes, guild, channel): if (minutes < 1): await channel.send('minutes must be greater than or equal 1.') return if (self.sleeping_list_per_guild.get(guild.id) is not None): del self.sleeping_list_per_guild[guild.id] if (minutes > 120): await channel.send('minutes must be less than 120.') return awake_time = DateTime.now().replace(microsecond=0) + timedelta( minutes=minutes) text = 'start sleeping %s minutes. until %s.' % ( minutes, awake_time.isoformat()) await channel.send(text) await self.change_presence(status=Status.idle) # fix me. self.sleeping_list_per_guild[guild.id] = awake_time
async def command(self, message): now = DateTime.now() commands = message.content.split(' ') guild = message.guild channel = message.channel if (commands is None or len(commands) < 2): return if (commands[1] == 'run'): for voice_channel in guild.voice_channels: await self.disconnect(guild, voice_channel, now) return if (commands[1] == 'add'): if (len(commands) < 3): await channel.send('time is required.') return await self.do_add(commands[2], guild, channel) return if (commands[1] == 'remove'): if (len(commands) < 3): await channel.send('time is required.') return await self.do_remove(commands[2], guild, channel) return if (commands[1] == 'exclude'): if (len(commands) < 3): await channel.send('weekday is required.') return if (len(commands) < 4): await channel.send('time is required.') return await self.do_exclude(commands[2], commands[3], guild, channel) return if (commands[1] == 'include'): if (len(commands) < 3): await channel.send('weekday is required.') return if (len(commands) < 4): await channel.send('time is required.') return await self.do_include(commands[2], commands[3], guild, channel) return if (commands[1] == 'list'): await self.do_list(guild, channel) return if (commands[1] == 'sleep'): if (len(commands) < 3): await channel.send('minutes is required.') return await self.do_sleep(int(commands[2]), guild, channel) return if (commands[1] == 'awake'): await self.do_awake(guild, channel) return if (commands[1] == 'status'): await self.do_status(guild, channel) return await self.do_help(channel)
def check_source(self, source, last_status, id, agent, name, type): """ Get status of profile, if stastus not change then update check equal 1. Ffmpeg: Use Ffprobe to check stastus profile (source) and return flag 0 is down 1 is up 2 is video error 3 is audio eror """ ffmpeg = Ffmpeg() check = ffmpeg.check_source(source) # print "%s : %s"%(check, last_status) self.logger.debug("Curent :%s <> Last: %s, %s %s %s"%(check, last_status, source, name, type)) if check != last_status: date_time = DateTime() opdate = date_time.get_now() time.sleep(SYSTEM["BREAK_TIME"]) self.logger.debug("Recheck : %s %s %s"%(source, name, type)) recheck = ffmpeg.check_source(source) if recheck == check: status = {0: "DOWN ", 1: "UP ", 2: "VIDEO ERROR", 3: "AUDIO ERROR"} [check] """ Update status and write log """ child_thread_list = [] profile = ProfileBLL() profile_data = {"status": check, "agent": agent, "ip": SYSTEM["HOST"]} child_thread = threading.Thread(target=profile.put, args=(id, profile_data,)) child_thread.start() child_thread_list.append(child_thread) """Append log""" channel = """%s %s"""%(name, type) while len(channel) < 22: channel += " " while len(source) < 27: source += " " ip_config = SYSTEM["HOST"] while len(ip_config) < 16: ip_config += " " message = """%s (ip:%s) %s in host: %s (%s)""" % (channel, source, status, ip_config, agent) cldate = date_time.get_now() rslog = { "sev" : "Critical", "jname" : name, "type" : type, "res" : source, "desc" : status, "cat" : "Communication", "host" : agent, "opdate" : opdate, "cldate" : cldate } self.logger.critical(json.dumps(rslog)) log_data = {"host": source, "tag": "status", "msg": message} log = LogBLL() child_thread = threading.Thread(target=log.post, args=(log_data,)) child_thread.start() child_thread_list.append(child_thread) """Update local snmp IPTV""" if "origin" or "4500" in agent: self.logger.debug("%s is core probe"%(agent)) time.sleep(2) snmp = Snmp() child_thread = threading.Thread(target=snmp.set) child_thread.start() child_thread_list.append(child_thread) """ Wait for update database complete """ for child_thread in child_thread_list: child_thread.join() return 1 return 0
def put(self, request, pk): data = request.body data = json.loads(data) self.logger.debug("message: %s" % (str(data))) #Status if ("status" in data): self.logger.debug("message: update status -->%s" % (str(data))) agent_name = data["agent"] profile_agent = self.get_object(pk) date_time = DateTime() if not profile_agent: self.logger.info("Not found profile_agent_id: %s" % (str(pk))) return HttpResponse(status=400) if profile_agent.status != data["status"]: profile_agent.status = data["status"] profile_agent.last_update = date_time.get_now() profile_agent.save() self.logger.debug("message: update status --> success") if "Origin" in agent_name or "4500" in agent_name or "ott" in agent_name: self.logger.info("%s is core probe" % (agent_name)) if PUSH_ALARM_CORE: self.logger.info("Push alarm to scc is active") time.sleep(0.5) snmp = Snmp(str(data["ip"]).replace(' ', '')) alarm_status, msg = snmp.check_agent() data = { "ishost": False, "queueServiceName": "Check_Agent_IPTV_Status", "queueHost": agent_name, "msg": str(msg), "AlertStatus": alarm_status, "agentId": int(pk) } self.logger.debug("alarm contain: %s" % (str(data))) scc = Scc() scc.post(data) return HttpResponse(status=202) else: self.logger.info("%s is not core probe" % (agent_name)) if PUSH_ALARM_PROBE: self.logger.info("Push alarm to scc is active") time.sleep(0.5) snmp = Snmp(str(data["ip"]).replace(' ', '')) alarm_status, msg = snmp.check_agent() data = { "ishost": False, "queueServiceName": "Check_Agent_IPTV_Status", "queueHost": agent_name, "msg": str(msg), "AlertStatus": alarm_status, "agentId": int(pk) } self.logger.debug("alarm contain: %s" % (str(data))) scc = Scc() scc.post(data) return HttpResponse(status=202) else: self.logger.warning("Value not change: %s" % (str(pk))) return HttpResponse(status=400) # querry = "update profile_agent set status=%s,last_update=unix_timestamp() where id=%s;"%(data['status'],pk) # RabbitMQQueue().push_query(querry) # return HttpResponse(status=202) #video elif ('video' in data): self.logger.debug("message: update video status -->%s" % (str(data))) agent_name = data["agent"] profile_agent = self.get_object(pk) date_time = DateTime() if not profile_agent: self.logger.warning("message: profile id %s not exist" % (str(pk))) return HttpResponse(status=400) if profile_agent.video != data["video"]: profile_agent.video = data["video"] profile_agent.last_update = date_time.get_now() profile_agent.save() self.logger.debug("message: update video status --> success") if "Origin" in agent_name or "4500" in agent_name or "ott" in agent_name: """ Push to SCC """ self.logger.info("%s is core probe" % (agent_name)) if PUSH_ALARM_CORE: self.logger.info("Push alarm to scc is active") time.sleep(0.5) snmp = Snmp(str(data["ip"]).replace(' ', '')) alarm_status, msg = snmp.check_agent() data = { "ishost": False, "queueServiceName": "Check_Agent_IPTV_Status", "queueHost": agent_name, "msg": str(msg), "AlertStatus": alarm_status, "agentId": int(pk) } self.logger.debug("alarm contain: %s" % (str(data))) scc = Scc() scc.post(data) return HttpResponse(status=202) else: self.logger.info("%s is not core probe" % (agent_name)) if PUSH_ALARM_PROBE: self.logger.info("Push alarm to scc is active") time.sleep(0.5) snmp = Snmp(str(data["ip"]).replace(' ', '')) alarm_status, msg = snmp.check_agent() data = { "ishost": False, "queueServiceName": "Check_Agent_IPTV_Status", "queueHost": agent_name, "msg": str(msg), "AlertStatus": alarm_status, "agentId": int(pk) } self.logger.debug("alarm contain: %s" % (str(data))) scc = Scc() scc.post(data) return HttpResponse(status=202) else: self.logger.warning("Value not change: %s" % (str(pk))) return HttpResponse(status=400) # querry="update profile_agent set video=%s,last_update=unix_timestamp() where id=%s;"%(data['video'],pk) # RabbitMQQueue().push_query(querry) # return HttpResponse(status=202) #dropframe elif ('dropframe' in data) and len(data) == 1: self.logger.debug("message: update dropframe -->%s" % (str(data))) querry = "update profile_agent set dropframe=%s,last_update=unix_timestamp() where id=%s;" % ( data['dropframe'], pk) RabbitMQQueue().push_query(querry) self.logger.info( "message: update dropframe added to RabbitMQQueue: %s" % (querry)) return HttpResponse(status=202) #discontinuity elif ('discontinuity' in data) and len(data) == 1: self.logger.debug("message: update discontinuity -->%s" % (str(data))) querry = "update profile_agent set discontinuity=%s,last_update=unix_timestamp() where id=%s;" % ( data['discontinuity'], pk) RabbitMQQueue().push_query(querry) self.logger.info( "message: update dropframe added to RabbitMQQueue: %s" % (querry)) return HttpResponse(status=202) #analyzer_status elif ('analyzer_status' in data) and len(data) == 1: self.logger.debug("message: update analyzer_status -->%s" % (str(data))) querry = "update profile_agent set analyzer_status=%s,last_update=unix_timestamp() where id=%s;" % ( data['analyzer_status'], pk) RabbitMQQueue().push_query(querry) self.logger.info( "message: update dropframe added to RabbitMQQueue: %s" % (querry)) return HttpResponse(status=202) return HttpResponse(status=400)
def duration(self, from_now: bool = False): s = DateTime.now() if from_now and self.is_now() else self.start_time return int((self.stop_time - s).total_seconds())
def is_already_play_today(self) -> bool: return self.is_today() and self.stop_time < DateTime.now()
def is_will_be_play_today(self) -> bool: return self.is_today() and self.start_time > DateTime.now()
def is_now(self) -> bool: return self.is_today( ) and self.start_time < DateTime.now() < self.stop_time
def is_today(self) -> bool: return self.day == DateTime.day_num()
def stop_time(self) -> datetime: return DateTime.strptoday(others.ETHER_TIMES[self.day][self.num][1], '%H:%M')
def _get_all_days_to_today(date_from: datetime) -> Iterator[datetime]: date_to = DateTime.today() day_delta = timedelta(days=1) while date_from < date_to: yield date_from date_from += day_delta
def return_main(body): if not is_json(body): logger.error("Recieve: %s not json fortmat --> break" % (str(body))) print "Not json %s" % (str(body)) return 1 data = json.loads(body) if data["status"] != 1: logger.warning( "Job(%s)single status is %s --> not ok --> not return main" % (str(data))) jid = int(data["jid"]) target_host = data["host"] account = None for i in THOMSON_HOST: if THOMSON_HOST[i]["host"] == target_host: account = THOMSON_HOST[i] break if not account: logger.error("Host %s not found on setting list: %s" % (target_host, str(THOMSON_HOST))) print "Host: %s not found!" % (target_host) return 1 jd = JobDetail(account["host"], account["user"], account["passwd"], jid) is_auto = is_auto_return_main(data) is_not_overwork = is_not_overworked(data) is_running_backup = is_running_backup_on_thomson(data) if not is_running_backup: time.sleep(10) is_running_backup = is_running_backup_on_thomson(data) if not is_running_backup: time.sleep(10) is_running_backup = is_running_backup_on_thomson(data) if not (is_auto and is_running_backup and is_not_overwork): logger.warning( "Job(%s) is not auto --> check your config: is_auto(%s), is_not_overwork(%s), is_running_backup(%s)" % (str(data), str(is_auto), str(is_not_overwork), str(is_running_backup))) date_time = DateTime() print "%s Job: %d from thomson %s not auto" % (str( date_time.get_now_as_human_creadeble()), jid, target_host) return 0 if not SYSTEM["auto"]["RETURN_MAIN"]: logger.warning("System auto return main not active check your config!") return 1 job_status = get_job_status(jd) logger.info("Job(%s) status --> |%s|" % (str(data), job_status)) if job_status.upper() == "OK": origin_source_backup, origin_udp_port = get_job_backup_info(jd) disable_backup = deactive_backup(jd) time.sleep(2) enable_backup = active_backup(jd) if enable_backup.upper() == "NOTOK": stop = stop_job(jd) #logger.warning("Job(%s) STOP --> %s"%(str(data), stop)) time.sleep(1) enable_backup = active_backup(jd) logger.warning("Job(%s) enable backup --> %s" % (str(data), enable_backup)) time.sleep(1) start = start_job(jd) #logger.warning("Job(%s) START --> %s"%(str(data), start)) logger.critical( "Tool just returned the main source by disable and enable Active backup: Job(%s)" % (str(data))) source_backup, udp_port = get_job_backup_info(jd) if origin_source_backup != source_backup: set_backup = set_backup_ip(jd, origin_source_backup) logger.warning( "Job(%s) thomson tool change value ip backup from %s to %s --> %s" % (str(data), source_backup, origin_source_backup, set_backup)) if origin_udp_port != udp_port: set_backup_port = set_backup_udp_port(jd, origin_udp_port) logger.warning( "Job(%s) thomson tool change value udp port backup from %s to %s --> %s" % (str(data), str(source_backup), str(origin_source_backup), set_backup_port)) elif job_status.upper() == "MAJOR": stop = stop_job(jd) time.sleep(2) start = start_job(jd) logger.critical( "Tool just returned the main source by stop and start job: Job(%s)" % (str(data))) return 0
def test_relative_time(self): DateTime.fake(2021, 1, 1, 8, 5, 0) br = Broadcast(4, 1) self.assertFalse(br.is_already_play_today()) self.assertTrue(br.is_will_be_play_today())