def create(): pattern = request.form['pattern'] command = request.form['command'] if not command or prettify_cron(pattern) == pattern: return json.dumps({ 'status': 'fail', 'message': 'Some arguments are invalid.' }) cron = CronTab(user=os.getenv('USER')) job_id = len(cron) job = cron.new(command=command) job.setall(pattern) cron.write() return json.dumps({ 'status': 'ok', 'message': 'Job successfully created.', 'job': { 'id': job_id, 'pattern': pattern, 'command': command, 'description': prettify_cron(pattern) } })
def add(self, path=None, recurrence=None, params=None, debug=False): if self.manager.is_production(): print("No add done you are in production\n") return if not recurrence: print("No recurrence provided\n") return if not self.__check_cron(recurrence): print(f"WARNING : Recurrence wrong format {recurrence}") return current_file = self.manager.get_path(path) self.manager.add_prod( { "type": self.role, "path": current_file, "params": {}, "value": recurrence, }, debug, ) cron_string = pretty_cron.prettify_cron(recurrence) print("👌 Well done! Your Notebook has been sent to production. \n") print( f'⏰ It will be scheduled "{cron_string}" (more on the syntax on https://crontab.guru/).\n' ) print('Ps: to remove the "Scheduler", just replace .add by .delete')
def add(self, path=None, reccurence=None, params=None, silent=False): if not self.manager.notebook_path(): print("No add done you are in already in naas folder\n") return if not reccurence: print("No reccurence provided\n") return cron_string = pretty_cron.prettify_cron(reccurence) current_file = self.manager.get_path(path) prod_path = self.manager.get_prod_path(current_file) if silent is False: print( f"[Naas from Jupyter] => i have copied this {current_file} here: {prod_path} \n" ) print(f"it will refresh it {cron_string}\n") print( f'If you want to remove the refresh capability, just call .delete({path if path is not None else "" })) in this file' ) return self.manager.add_prod( { "type": self.role, "path": current_file, "params": {}, "value": reccurence, }, silent, )
def send_scheduler(self, uid, status, email, file_path, cron_str): cron_string = pretty_cron.prettify_cron(cron_str) content = f"Your {file_path} who run {cron_string} is {status}, check the Logs on your manager below :" status_url = f"{encode_proxy_url('assets')}/{status}.png" message_bytes = file_path.encode("ascii") base64_bytes = base64.b64encode(message_bytes) file_path_base64 = base64_bytes.decode("ascii") link_url = f"{encode_proxy_url('manager')}/?filter={file_path_base64}" try: data = { "subject": f"Sheduler {status}", "email": email, "content": content, "image": status_url, "link": link_url, } req = requests.post(url=f"{self.base_notif_url}/send", json=data) req.raise_for_status() jsn = req.json() return jsn except Exception as err: self.logger.error( json.dumps({ "id": uid, "type": "notification error", "error": str(err) }))
def description(self): rfield = lambda f: f and str(f).replace(' ', '') or '*' string = '{0} {1} {2} {3} {4}'.format( rfield(self.minute), rfield(self.hour), rfield(self.day_of_week), rfield(self.day_of_month), rfield(self.month_of_year), ) return pretty_cron.prettify_cron(string)
def currents(self): json_data = self.manager.get_naas() for item in json_data: kind = None if item["type"] == self.role: cron_string = pretty_cron.prettify_cron(item["value"]) kind = f"refresh {cron_string}" print(f"File ==> {item['path']} is {kind}")
def retrieve(job_id): jobs = [] cron = CronTab(user=os.getenv('USER')) if job_id < 0: for i, job in enumerate(cron): pattern = job.slices.render() command = job.command description = prettify_cron(pattern) jobs.append({ 'id': i, 'pattern': pattern, 'command': command, 'description': description }) return json.dumps({ 'status': 'ok', 'message': 'Jobs retrieved successfully', 'jobs': jobs }) elif job_id < len(cron): job = cron[job_id] pattern = job.slices.render() command = job.command description = prettify_cron(pattern) return json.dumps({ 'status': 'ok', 'message': 'Job retrieved successfully', 'jobs': [{ 'id': job_id, 'pattern': pattern, 'command': command, 'description': description }] }) return json.dumps({'status': 'fail', 'message': 'Job ID is invalid.'})
def currents(self, raw=False): json_data = self.manager.get_naas() if raw: for item in json_data: if item["type"] == self.role: print(item) else: for item in json_data: kind = None if item["type"] == self.role: cron_string = pretty_cron.prettify_cron(item["value"]) kind = f"scheduler {cron_string}" print(f"File ==> {item['path']} is {kind}")
def timer(ctx, vac: miio.Vacuum): """List and modify existing timers.""" if ctx.invoked_subcommand is not None: return timers = vac.timer() click.echo("Timezone: %s\n" % vac.timezone()) for idx, timer in enumerate(timers): color = "green" if timer.enabled else "yellow" click.echo(click.style("Timer #%s, id %s (ts: %s)" % ( idx, timer.id, timer.ts), bold=True, fg=color)) click.echo(" %s" % timer.cron) min, hr, x, y, days = timer.cron.split(' ') cron = "%s %s %s %s %s" % (min, hr, x, y, days) click.echo(" %s" % pretty_cron.prettify_cron(cron))
def update(job_id): pattern = request.form['pattern'] if 'pattern' in request.form else None command = request.form['command'] if 'command' in request.form else None description = '' if not command and prettify_cron(pattern) == pattern: return json.dumps({ 'status': 'fail', 'message': 'Some argument must be provided.' }) cron = CronTab(user=os.getenv('USER')) if job_id >= len(cron) or job_id < 0: return json.dumps({'status': 'fail', 'message': 'Job ID is invalid.'}) if not command: command = cron[job_id].command cron[job_id].set_command(command) if pattern and prettify_cron(pattern) != pattern: cron[job_id].setall(pattern) description = prettify_cron(pattern) else: pattern = cron[job_id].slices.render() cron.write() return json.dumps({ 'status': 'ok', 'message': 'Job updated successfully.', 'job': { 'id': job_id, 'pattern': pattern, 'command': command, 'description': description } })
def timer(vac: mirobo.Vacuum, timer): """Schedule vacuuming, times in GMT.""" if timer: raise NotImplementedError() # vac.set_timer(x) pass else: timers = vac.timer() for idx, timer in enumerate(timers): color = "green" if timer.enabled else "yellow" # Note ts == ID for changes click.echo(click.style("Timer #%s, id %s (ts: %s)" % ( idx, timer.id, timer.ts), bold=True, fg=color)) print(" %s" % timer.cron) min, hr, x, y, days = timer.cron.split(' ') # hr is in gmt+8 (chinese time), TODO convert to local hr = (int(hr) - 8) % 24 cron = "%s %s %s %s %s" % (min, hr, x, y, days) click.echo(" %s" % pretty_cron.prettify_cron(cron))
def handle_command(user, command, channel): """ Executes bot command if the command is known Args: user: Slack user ID command: Command string channel: Originating Slack channel """ # Default response is help text for the user default_response = "Sorry, I am not sure what you mean. Try _*@Xarvis help*_ to see what I can help you with\n" # Finds and executes the given command, filling in response response = None # This is where you start to implement more commands! if command.lower().startswith("schedule "): command_split = command.split("schedule ") if command_split[1].lower().startswith("list"): response = "*Scheduled jobs*\n" for key in JOBS: response += "- " + JOBS[key]["title"] + "\n" else: partial_reponse = "" for key in JOBS: description = pretty_cron.prettify_cron(JOBS[key]["sequence"]) if description == JOBS[key]["sequence"]: description = get_description(description) description = description[0].lower() + description[1:] if command_split[1].lower() in JOBS[key]["title"].lower( ) or JOBS[key]["title"].lower() in command_split[1].lower(): partial_reponse += "*" + JOBS[key]["title"] + "*\n" \ "- Runs " + description + " (ET)\n" if len(partial_reponse) > 0: response = "Job scheduled time(s)\n" + partial_reponse elif command.lower().startswith("help"): response = "Hey there, following are the queries that I am trained to help you with as of now,\n" \ "- *schedule list* - _Get a list of cron pattern based scheduled jobs stored_\n" \ "- *schedule <job_name>* - _Get the scheduled time of a specific job_\n" \ "- *holidays* - _Get the list of US holidays for the year_\n" \ "- *calc <expression>* - _Do a calculation_\n" \ "- *execute <job_name> <optional parameters>* - _Execute a predifined job_\n" \ "Use *@Xarvis _command_* to ask me something" elif command.lower().startswith("holidays"): now = datetime.datetime.now() response = "US public holidays\n" for date, name in sorted(holidays.US(years=now.year).items()): response += "- " + "*" + date.strftime( "%A") + "*, " + date.strftime("%B %d ") + date.strftime( ", %Y") + ": " + name + "\n" elif "thank" in command.lower() or "thanks" in command.lower(): response = "You are welcome <@" + user + ">" elif command.lower().startswith("calc "): command_split = command.split("calc ") try: result = eval(command_split[1]) if isinstance(result, numbers.Real): response = "<@" + user + ">, result: " + str(result) else: response = "<@" + user + ">, invalid mathematical expression" except: response = "<@" + user + ">, invalid mathematical expression" elif "hi" in command.lower() or "hey" in command.lower(): response = "Hey <@" + user + ">, Try _*@Xarvis help*_ to see what I can help you with" elif command.lower().startswith("execute"): response = handlers.tasks.execute_task( command.lower().strip()[8:].split(" "), TASKS) # Sends the response back to the channel SLACK_CLIENT.api_call("chat.postMessage", channel=channel, text=response or default_response)
def format_schedule(self, schedule): cron_schedule = "%s %s %s %s %s" % ( schedule['minute'], schedule['hour'], schedule['day_of_month'], schedule['month_of_year'], schedule['day_of_week']) return prettify_cron(cron_schedule)
def send_status( self, uid, status, email_to, file_path, current_type, current_value, files=[], email_from=None, ): if self.base_notif_url is None: jsn = { "id": uid, "type": "notification error", "error": "not configured" } if self.logger is not None: self.logger.error(json.dumps(jsn)) else: print(jsn) return jsn base_url = os.environ.get("JUPYTERHUB_URL", None) base_user = os.environ.get("JUPYTERHUB_USER", None) content = "" file_link = f"{base_url}/user/{base_user}/tree/{file_path}" if current_type == t_asset or current_type == t_notebook: content = f'The file <a href="{file_link}">{file_path}</a> <br/>' content += f"Accesible at this url:<br/> {encode_proxy_url(current_type)}/{current_value}<br/>" elif current_type == t_scheduler: cron_string = pretty_cron.prettify_cron(current_value) content = f'The file <a href="{file_link}">{file_path}</a><br/>' content += f"who run {cron_string}<br/>" content += f"Is {status}.<br/><br/>" content += "Check the Logs on your manager below :<br/>" status_url = f"{encode_proxy_url(t_asset)}/naas_{status}.png" message_bytes = file_path.encode("ascii") base64_bytes = base64.b64encode(message_bytes) file_path_base64 = base64_bytes.decode("ascii") link_url = f"{base_url}/user/{base_user}/naas/?filter={file_path_base64}" logo_url = f"{encode_proxy_url(t_asset)}/naas_logo.png" try: data = { "title": "Naas manager notification", "subject": f"{current_type.capitalize()} {status}", "from": email_from, "email": ",".join(email_to) if isinstance(email_to, list) else email_to, "content": content, "custom_vars": { "URL_HOME": encode_proxy_url(), "URL_LOGO": logo_url, "ALT_LOGO": "Naas Manager LOGO", "URL_IMAGE": status_url, "ALT_IMAGE": status, "URL_LINK": link_url, }, } req = None if len(files) > 0: files = {} for file in files: abs_path = os.path.abspath(os.path.join(os.getcwd(), file)) try: files[file] = open(abs_path, "rb") except Exception as err: print(err) req = requests.post( url=f"{self.base_notif_url}/send_status", headers=self.headers, files=files, json=data, ) else: req = requests.post( url=f"{self.base_notif_url}/send_status", headers=self.headers, json=data, ) req.raise_for_status() jsn = req.json() return jsn except Exception as err: if self.logger is not None: self.logger.error( json.dumps({ "id": uid, "type": "notification error", "error": str(err) })) else: print(err)