def write(context): """Starts a new article""" config = context.obj title = click.prompt('Title') author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR')) slug = slugify(title) creation_date = datetime.now() basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug) meta = ( ('Title', title), ('Date', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)), ('Modified', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)), ('Author', author), ) file_content = '' for key, value in meta: file_content += '{}: {}\n'.format(key, value) file_content += '\n\n' file_content += 'Text...\n\n' file_content += '![image description]({filename}/images/my-photo.jpg)\n\n' file_content += 'Text...\n\n' os.makedirs(config['CONTENT_DIR'], exist_ok=True) path = os.path.join(config['CONTENT_DIR'], basename) with click.open_file(path, 'w') as f: f.write(file_content) click.echo(path) click.launch(path)
def browse(lancet, issue): """ Open the issue tracker page for the given issue in your default browser. If no issue is provided, the one linked to the current branch is assumed. """ click.launch(get_issue(lancet, issue).permalink())
def search(query): """ Search through notes. """ results = [] for idx, (note, highlights) in enumerate(nomadic.index.search(query)): path = note.path.rel results.append(path) # Show all the results. header = ('['+Fore.GREEN+'{0}'+Fore.RESET+'] ').format(idx) echo('\n' + header + Fore.BLUE + path + Fore.RESET) echo(highlights) echo('\n---') if len(results) > 0: # Ask for an id and open the # file in the default editor. id = click.prompt('Select a note', type=int) path = results[id] if os.path.splitext(path)[1] == '.pdf': click.launch(path) else: click.edit(filename=os.path.join(conf.ROOT, path)) else: echo('\nNo results for ' + Fore.RED + query + Fore.RESET + '\n')
def dropbox_token_flow(): click.echo(click.style('The application will load an URL into your browser.', fg='blue')) click.echo(click.style('You have to authorize the application to access to your account.', fg='blue')) click.echo(click.style('When the access is granted, dropbox will return you a key.', fg='blue')) click.pause() click.launch( 'https://www.dropbox.com/1/oauth2/authorize?client_id=%s&response_type=code' % settings.DROPBOX_APP_KEY) key = click.prompt(click.style('Please enter the dropbox returned key', bold=True)) click.echo(click.style('Processing...', fg='blue')) query = requests.post( url='https://api.dropbox.com/1/oauth2/token', params={ 'grant_type': 'authorization_code', 'code': key, 'client_id': settings.DROPBOX_APP_KEY, 'client_secret': settings.DROPBOX_APP_SECRET, }) data = query.json() if 'error' in data: click.echo(click.style('Dropbox returned an error: %s' % data['error_description'], fg='red')) elif 'access_token' not in data: click.echo(click.style('An unknow error has occured, please retry later.', fg='red')) else: click.echo(click.style('Here is your token: %s' % click.style(data['access_token'], fg='green'), fg='blue')) click.echo(click.style('Please save it in your uBackup settings.', fg='blue'))
def select(questions, num): print_full_question(questions[num - 1]) working = True while working: user_input = click.prompt("Enter b to launch browser, x to return to search, or q to quit") if user_input == 'b': click.launch(questions[num - 1].json['link']) elif user_input == 'q': sys.exit() elif user_input == 'x': click.echo("\n" * 12) # Ranging over the 5 questions including the user's choice origin = 0 if not num % NUM_RESULTS: origin = num - NUM_RESULTS else: origin = num - num % NUM_RESULTS for j in range(origin, origin + NUM_RESULTS): print_question(questions[j], j + 1) working = False else: click.echo(click.style( "The input entered was not recognized as a valid choice.", fg="red", err=True))
def create_api_key(): """ Interactively create a new API key via Zotero's OAuth API. Requires the user to enter a verification key displayed in the browser. :returns: API key and the user's library ID """ auth = OAuth1Service( name='zotero', consumer_key=CLIENT_KEY, consumer_secret=CLIENT_SECRET, request_token_url=REQUEST_TOKEN_URL, access_token_url=ACCESS_TOKEN_URL, authorize_url=AUTH_URL, base_url=BASE_URL) token, secret = auth.get_request_token( params={'oauth_callback': 'oob'}) auth_url = auth.get_authorize_url(token) auth_url += '&' + urlencode({ 'name': 'zotero-cli', 'library_access': 1, 'notes_access': 1, 'write_access': 1, 'all_groups': 'read'}) click.echo("Opening {} in browser, please confirm.".format(auth_url)) click.launch(auth_url) verification = click.prompt("Enter verification code") token_resp = auth.get_raw_access_token( token, secret, method='POST', data={'oauth_verifier': verification}) if not token_resp: logging.debug(token_resp.content) click.fail("Error during API key generation.") access = urlparse.parse_qs(token_resp.text) return access['oauth_token'][0], access['userID'][0]
def search(query, browser, include_pdf): """search through notes""" results = [] for idx, (note, highlights) in enumerate(nomadic.search(query, delimiters=(Fore.RED, Fore.RESET), include_pdf=include_pdf)): path = note.path.rel results.append(path) # Show all the results. header = ('['+Fore.GREEN+'{0}'+Fore.RESET+'] ').format(idx) echo('\n' + header + Fore.BLUE + path + Fore.RESET) for highlight in highlights: echo(highlight) echo('\n---') if len(results) > 0: # Ask for an id and open the # file in the default editor. id = click.prompt('Select a note', type=int) path = results[id] abs_path = os.path.join(conf.ROOT, path) if os.path.splitext(path)[1] == '.pdf': click.launch(abs_path) else: if not browser: click.edit(filename=abs_path) else: click.launch('http://localhost:{0}/{1}'.format(conf.PORT, path)) else: echo('\nNo results for ' + Fore.RED + query + Fore.RESET + '\n')
def clip(save, edit, browser, overwrite): """convert html in the clipboard to markdown""" html = clipboard.get_clipboard_html() if html is None: click.echo('No html in the clipboard') return if save is None: content = html2md.html_to_markdown(html).strip() click.echo(content) return if not save.endswith('.md'): click.echo('Note must have extension ".md"') return note = Note(save) if os.path.exists(note.path.abs) and not overwrite: click.echo('Note already exists at "{}" (specify `--overwrite` to overwrite)'.format(note.path.abs)) return html = parsers.rewrite_external_images(html, note) content = html2md.html_to_markdown(html).strip() note.write(content) if browser: click.launch('http://localhost:{0}/{1}'.format(conf.PORT, note.path.rel)) if edit: click.edit(filename=note.path.abs)
def login_token_helper(ctx, value): if not value: url = ctx.obj.client.get_access_token_url() click.secho("Your browser has been opened to visit: {}".format(url)) click.launch(url) value = click.prompt("Please copy the access token and paste it here") return value
def preview(context): """Opens local preview of your blog website""" config = context.obj pelican(config, '--verbose', '--ignore-cache') server_proc = None os.chdir(config['OUTPUT_DIR']) try: try: command = 'python -m http.server ' + str(PORT) server_proc = run(command, bg=True) time.sleep(3) click.launch('http://localhost:8000') time.sleep(5) pelican(config, '--autoreload') except Exception: if server_proc is not None: server_proc.kill() raise except KeyboardInterrupt: abort(context)
def show(globs: AttrDict, full: bool, patch: bool, patch_only: bool, browse: bool, bugs: List[int]): """Displaying bugs.""" results = [] tmpl = template.get_template('view', '/issue.txt') for bug_no in bugs: if browse: click.launch('https://github.com/{}/issues/{:d}'.format( globs.project, bug_no)) continue r, bug = globs.req_get(bug_no, model='Issue') if full and bug.comments: r, comments = globs.req_get('{}/comments'.format(bug_no), model='Comment') else: comments = [] if (patch or patch_only) and bug.pull_request: url = '{}/repos/{}/pulls/{}'.format(globs.host_url, globs.project, bug_no) headers = {'Accept': 'application/vnd.github.patch'} r, c = globs.req_get(url, headers=headers, is_json=False) patch = c.decode('utf-8') else: patch = None results.append(tmpl.render(bug=bug, comments=comments, full=True, patch=patch, patch_only=patch_only, project=globs.repo_obj())) if results: utils.pager('\n'.join(results), pager=globs.pager)
def cli(box, endpoint, ip): """ Open an endpoint in your default browser """ url = box.browse(endpoint, ip) click.secho('Opening %s in your browser...' % (url), fg='green') click.launch(url)
def publish(context): """Publishes the project""" commit_version_change(context) if context.github: # github token project_settings = project_config(context.module_name) if not project_settings['gh_token']: click.echo('You need a GitHub token for changes to create a release.') click.pause('Press [enter] to launch the GitHub "New personal access ' 'token" page, to create a token for changes.') click.launch('https://github.com/settings/tokens/new') project_settings['gh_token'] = click.prompt('Enter your changes token') store_settings(context.module_name, project_settings) description = click.prompt('Describe this release') upload_url = create_github_release(context, project_settings['gh_token'], description) upload_release_distributions( context, project_settings['gh_token'], build_distributions(context), upload_url, ) click.pause('Press [enter] to review and update your new release') click.launch('{0}/releases/tag/{1}'.format(context.repo_url, context.new_version)) else: tag_and_push(context)
def open_project_cloud_site(client, project_id, stage): assert stage in ("test", "live") project_data = client.get_project(project_id) url = project_data["{}_status".format(stage)]["site_url"] if url: click.launch(url) else: click.secho("No {} server deployed yet.".format(stage), fg="yellow")
def main(root=None, port=None, launch=False): """Serve a single-page application from a directory.""" path, httpd = server.init(root, port) click.echo("Serving {d}/ on {p}".format(d=path, p=httpd.server_port)) if launch: click.launch("http://localhost:{p}".format(p=httpd.server_port)) httpd.serve_forever()
def src(ident, date, note): check_if_loaded(cur_notebook) note_files = note_from_ident(ident, date, note) if len(note_files) == 0: click.echo('No matches found.') sys.exit(1) for n in note_files: click.launch(os.path.join(cur_notebook.location, n.src_path))
def explore(debug, launch): '''A web interface to explore data''' if not debug: # Avoid dual title title('Running the exploration Web interface') import explore if launch: click.launch('http://localhost:5000/') explore.run(debug)
def docs(): index = os.path.join('.', 'docs', '_build', 'html', 'index.html') if os.path.isfile(index): index = os.path.abspath(index) click.launch(index) else: click.echo( 'Could not find docs path. Have you generated the docs yet? ' 'If not try "python -m walkoff dev generate docs"')
def starred(username, token, sort, repository, message): """GitHub starred creating your own Awesome List used GitHub stars! example: starred --username maguowei --sort > README.md """ if repository: if not token: click.secho('Error: create repository need set --token', fg='red') return file = BytesIO() sys.stdout = file else: file = None gh = GitHub(token=token) stars = gh.starred_by(username) click.echo(desc) repo_dict = {} for s in stars: language = s.language or 'Others' description = html_escape(s.description).replace('\n', '') if s.description else '' if language not in repo_dict: repo_dict[language] = [] repo_dict[language].append([s.full_name, s.name, s.html_url, description.strip(), s.homepage or '']) if sort: repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0])) for language in repo_dict: repo_dict[language] = sorted(repo_dict[language], key=lambda l: l[1]) for language in repo_dict.keys(): data = u' - [{}](#{})'.format(language, '-'.join(language.lower().split())) click.echo(data) click.echo('') for language in repo_dict: click.echo('## {} \n'.format(language.replace('#', '# #'))) for repo in repo_dict[language]: data = u'* [{0}]({2}) - {3} [{4}]({4})'.format(*repo) click.echo(data) click.echo('') click.echo(license_.format(username=username)) if file: rep = gh.repository(username, repository) if rep: readme = rep.readme() readme.update(message, file.getvalue()) else: rep = gh.create_repository(repository, 'A curated list of my GitHub stars!') rep.create_file('README.md', 'starred initial commit', file.getvalue()) click.launch(rep.html_url)
def hackpad(): url = 'https://hackpad.com/ep/account/settings/' if click.confirm( 'Hackpad creds can be found at {}. Launch?'.format(url) ): click.launch(url) prompt_for_keychain('HackPad client id', AuthKeys.HACKPAD_CLIENT_ID) prompt_for_keychain('HackPad secret', AuthKeys.HACKPAD_SECRET)
def explore(debug, launch): """A web interface to explore data""" if not debug: # Avoid dual title title("Running the exploration Web interface") import explore if launch: click.launch("http://localhost:5000/") explore.run(debug)
def browse(index): """Opens the tweet in web browser.""" details = get_tweet_id(index) link = 'http://twitter.com/%s/status/%d' %(details['author'], details['id']) try: click.launch(link) click.echo('Opening link %s' %link) except Exception as e: click.secho('Error - %s' %e, fg="red")
def view(note): """view a note in the browser, recompiling when changed""" # convert to abs path; don't assume we're in the notes folder outdir = '/tmp' note = os.path.join(os.getcwd(), note) n = Note(note) compile.compile_note(n, outdir=outdir, templ='default') click.launch('/tmp/{title}/{title}.html'.format(title=n.title)) f = partial(compile.compile_note, outdir=outdir, templ='default') watch_note(n, f)
def open_project_cloud_site(client, stage): from .localdev.utils import get_aldryn_project_settings assert stage in ('test', 'live') project_settings = get_aldryn_project_settings() project_data = client.get_project(project_settings['id']) url = project_data['{}_status'.format(stage)]['site_url'] if url: click.launch(url) else: click.secho('No {} server deployed yet.'.format(stage), fg='yellow')
def new(date, title, markup, note): check_if_loaded(cur_notebook) try: if note: path = cur_notebook.newnote(date,title,markup) else: path = cur_notebook.newpage(title, markup) except ScribblerError as e: click.echo(ERROR + str(e)) sys.exit(1) scribbler.save(cur_notebook) click.launch(path)
def show(ctx, image_id=None): image_dir = ctx.obj['image_dir'] if not image_id: click.launch(image_dir, locate=True) return try: images = sorted(os.listdir(image_dir)) image = images[image_id -1] secho('Showing image {}'.format(image)) click.launch(os.path.join(image_dir, image)) except IndexError: secho(u'{} Image id not found'.format(BAD)) sys.exit(1)
def browsefs(): alt = request.values.get('alt') or PRIMARY_ALT record = g.admin_context.pad.get(request.values['path'], alt=alt) okay = False if record is not None: if record.is_attachment: fn = record.attachment_filename else: fn = record.source_filename if os.path.exists(fn): click.launch(fn, locate=True) okay = True return jsonify(okay=okay)
def browse(package, homepage): """Browse to a package's PyPI or project homepage.""" p = Package(package) try: if homepage: echof('Opening homepage for "{0}"...'.format(package), bold=True) url = p.home_page else: echof('Opening PyPI page for "{0}"...'.format(package), bold=True) url = p.package_url except NotFoundError: abort_not_found(package) click.launch(url)
def fun_open(): """Trying out click.launch.""" sites = { 'Google': 'https://google.com', 'The Verge': 'https://theverge.com', 'Liliputing': 'https://liliputing.com' } sites_keys = sites.keys() for index, site in enumerate(sites_keys): click.echo('%i %s' % (index, site)) choice = click.prompt('Which site to open?', default=0, type=int) click.launch(sites[sites_keys[choice]])
def html_viewer(html, block=False): import uuid filename = u'/tmp/%s.html' % uuid.uuid4() with open(filename, 'w') as f: f.write(html) import click click.launch(filename) if block: raw_input() return
def launch(config): """ Launch the dashboard in your default browser. """ url = f"http://localhost:{config.server.port}" click.launch(url)
def on_website_clicked(self): """Open the Dropbox website.""" click.launch("https://www.dropbox.com/")
def on_folder_clicked(self): """Open the Dropbox folder.""" click.launch(self.mdbx.dropbox_path)
def view(visualization_path, index_extension): # Guard headless envs from having to import anything large import sys from q2cli.core.config import CONFIG if not os.getenv("DISPLAY") and sys.platform != "darwin": raise click.UsageError( 'Visualization viewing is currently not supported in headless ' 'environments. You can view Visualizations (and Artifacts) at ' 'https://view.qiime2.org, or move the Visualization to an ' 'environment with a display and view it with `qiime tools view`.') import zipfile import qiime2.sdk if index_extension.startswith('.'): index_extension = index_extension[1:] try: visualization = qiime2.sdk.Visualization.load(visualization_path) # TODO: currently a KeyError is raised if a zipped file that is not a # QIIME 2 result is passed. This should be handled better by the framework. except (zipfile.BadZipFile, KeyError, TypeError): raise click.BadParameter( '%s is not a QIIME 2 Visualization. Only QIIME 2 Visualizations ' 'can be viewed.' % visualization_path) index_paths = visualization.get_index_paths(relative=False) if index_extension not in index_paths: raise click.BadParameter( 'No index %s file is present in the archive. Available index ' 'extensions are: %s' % (index_extension, ', '.join(index_paths.keys()))) else: index_path = index_paths[index_extension] launch_status = click.launch(index_path) if launch_status != 0: click.echo(CONFIG.cfg_style( 'error', 'Viewing visualization ' 'failed while attempting to open ' f'{index_path}'), err=True) else: while True: click.echo( "Press the 'q' key, Control-C, or Control-D to quit. This " "view may no longer be accessible or work correctly after " "quitting.", nl=False) # There is currently a bug in click.getchar where translation # of Control-C and Control-D into KeyboardInterrupt and # EOFError (respectively) does not work on Python 3. The code # here should continue to work as expected when the bug is # fixed in Click. # # https://github.com/pallets/click/issues/583 try: char = click.getchar() click.echo() if char in {'q', '\x03', '\x04'}: break except (KeyboardInterrupt, EOFError): break
def edit_settings(context: YeahYeahContext): """Open context file for editing""" click.launch(str(context.settings_path / default_settings_file_name))
def github(nobrowser: bool): """Links to the github project""" if nobrowser: click.secho(f"{SPARKLES_EMOJI} {GITHUB_REPO_URL}", fg=SUCCESS_COLOR) else: click.launch(GITHUB_REPO_URL)
def bad_launch(x: str) -> None: click.launch(x)
def docs(ctx, opts): """Launch the help website in your browser.""" # pylint: disable=unused-argument click.launch(get_help_website())
def login(token, username, password): """Login to Polyaxon.""" polyaxon_client = PolyaxonClient() if username: # Use user or email / password login if not password: password = click.prompt("Please enter your password", type=str, hide_input=True) password = password.strip() if not password: logger.info( "You entered an empty string. " "Please make sure you enter your password correctly.") sys.exit(1) try: body = polyaxon_sdk.models.V1CredsBodyRequest(username=username, password=password) access_auth = polyaxon_client.auth_v1.login(body=body) except (ApiException, HTTPError) as e: AuthConfigManager.purge() CliConfigManager.purge() handle_cli_error(e, message="Could not login.") sys.exit(1) if not access_auth.token: Printer.print_error("Failed to login") return else: if not token: token_url = "{}/app/token".format(polyaxon_client.config.host) click.confirm( "Authentication token page will now open in your browser. Continue?", abort=True, default=True, ) click.launch(token_url) logger.info("Please copy and paste the authentication token.") token = click.prompt( "This is an invisible field. Paste token and press ENTER", type=str, hide_input=True, ) if not token: logger.info( "Empty token received. " "Make sure your shell is handling the token appropriately.") logger.info( "See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth" ) return access_auth = polyaxon_sdk.models.V1Auth(token=token.strip(" ")) # Set user try: AuthConfigManager.purge() polyaxon_client = PolyaxonClient(token=access_auth.token) user = polyaxon_client.users_v1.get_user() except (ApiException, HTTPError) as e: handle_cli_error(e, message="Could not load user info.") sys.exit(1) access_token = AccessTokenConfig(username=user.username, token=access_auth.token) AuthConfigManager.set_config(access_token) polyaxon_client.config.token = access_auth.token Printer.print_success("Login successful") # Reset current cli server_versions = get_server_versions(polyaxon_client=polyaxon_client) current_version = get_current_version() log_handler = get_log_handler(polyaxon_client=polyaxon_client) CliConfigManager.reset( check_count=0, current_version=current_version, server_versions=server_versions.to_dict(), log_handler=log_handler, )
def wait_gitlab_esphomeyaml(): with open('data/gitlab_url', 'r') as f: gitlab_url = f.read() click.launch(gitlab_url) if not click.confirm("Please wait for Gitlab CI to complete at {}".format(gitlab_url)): raise EsphomeReleaseError
def pull_request( ctx, repo_dir, force_push, merge_after_pipeline, open_url, github_token, gitlab_token, reviewers, ): """ A command to simplify pull request creation. 1. Fetch remote changes 2. Push to a remote branch 3. Create pull request with Github or Gitlab """ repo = Repo(repo_dir, search_parent_directories=True) ctx.obj = repo click.clear() remote_url = get_remote_url(ctx.obj) giturl = giturlparse.parse(remote_url) if not giturl.github and not giturl.gitlab: raise click.UsageError( f"This command only supports Github & Gitlab - remote: {remote_url}" ) repo.remote().fetch() with Halo(text="Rebasing on master") as h: repo.git.rebase("origin/master") h.succeed() with Halo(text="Pushing changes", spinner="dots4") as h: try: repo.git.push(repo.remote().name, repo.active_branch.name, force=force_push) except GitCommandError as ex: if "your current branch is behind" in ex.stderr: h.stop() click.confirm( ("Your branch is behind the remote. You can either " "abort or force push. Do you want to force push?"), abort=True, ) repo.git.push(repo.remote().name, repo.active_branch.name, force=True) h.start() else: raise ex h.succeed() with Halo(text="Creating pull-request", spinner="dots5") as h: if giturl.github: pull_request_url = create_github_pull_request() elif giturl.gitlab: pull_request_url = create_gitlab_pull_request() h.succeed() click.echo(click.style(pull_request_url, fg="green", bold=True)) if open_url: click.launch(pull_request_url)
def open_folder(self): click.launch(environ.get_app_dir())
def open_url(url): click.launch(url)
def explore(): """Open the config location in your file manager.""" click.launch(CONFIG_FILE, locate=True)
def service(ctx, project, uid, yes, external, url): """Open the operation service in browser. N.B. The operation must have a run kind service, otherwise it will raise an error. You can open the service embedded in Polyaxon UI or using the real service URL, please use the `--external` flag. """ owner, project_name, run_uuid = get_project_run_or_local( project or ctx.obj.get("project"), uid or ctx.obj.get("run_uuid"), is_cli=True, ) client = RunClient(owner=owner, project=project_name, run_uuid=run_uuid) client.refresh_data() if client.run_data.kind != V1RunKind.SERVICE: Printer.print_warning("Command expected an operation of " "kind `service` received kind: `{}`!".format( client.run_data.kind)) sys.exit(1) Printer.print_header("Waiting for running condition ...") client.wait_for_condition(statuses={V1Statuses.RUNNING} | LifeCycle.DONE_VALUES, print_status=True) client.refresh_data() if LifeCycle.is_done(client.run_data.status): Printer.print_header("The operations reached a done statuses.") latest_status = Printer.add_status_color( {"status": client.run_data.status}, status_key="status") click.echo("{}\n".format(latest_status["status"])) run_url = get_dashboard_url( subpath="{}/{}/runs/{}/service".format(owner, project_name, run_uuid)) namespace = client.run_data.settings.namespace service_endpoint = SERVICES_V1 if client.run_data.meta_info.get(META_REWRITE_PATH, False): service_endpoint = REWRITE_SERVICES_V1 external_run_url = get_dashboard_url( base=service_endpoint, subpath="{}/{}/{}/runs/{}/".format(namespace, owner, project_name, run_uuid), ) if url: Printer.print_header( "The service will be available at: {}".format(run_url)) Printer.print_header( "You can also view it in an external link at: {}".format( external_run_url)) sys.exit(0) if not yes: click.confirm( "Dashboard page will now open in your browser. Continue?", abort=True, default=True, ) if external: click.launch(external_run_url) sys.exit(0) click.launch(run_url)
def on_recent_file_clicked(self): sender = self.sender() local_path = sender.data() click.launch(local_path, locate=True)
def bypass(url, judul): cc = 1 req = ses.get(url) bs = Bs(req.text, 'html.parser') link = bs.find('a', {'class': 'btn btn-success'})['href'] # print(link) req2 = ses.get(link) rg = re.findall(r'<frame src="(.*)">', req2.text)[0] # print(rg) blin = link.split('/')[2] req3 = ses.get(f"http://{blin}{rg}") bs2 = Bs(req3.text, 'html.parser') link2 = bs2.find('a', {'target': '_parent'})['href'] # print(link2) req4 = ses.get(f"http://{blin}{link2}") rg2 = re.findall(r'post\("(.*?)", {', req4.text)[0] # print(rg2) blin2 = req4.url.split('/')[2] # print(blin2) head = { 'Host': blin2, 'accept': '*/*', 'origin': f'http://{blin2}', 'x-requested-with': 'XMLHttpRequest', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded;charser=UTF-8', 'referer': link2, 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', } req5 = ses.post(f"http://{blin2}{rg2}", headers=head) # print(req5.text) try: rg3 = re.findall(r'https://layarkacaxxi.icu/f/(.*?)"', req5.text)[0] except: print("\n !Failed to bypass") tan = input( "[?] Anda ingin melanjutkannya ke website layarkaca21 (y/n) ") if tan.lower() == 'y': click.launch(info['title'][pil - 1][1]) else: sys.exit("okay bye bye:*") # print(rg3) req6 = ses.get(f'https://layarkacaxxi.icu/f/{rg3}') try: rg4 = re.findall(r"post\('(.*?)', ", req6.text)[0] except: raise Exception("\nDCMATakedown: Video tidak tersedia") # print(rg4) req7 = ses.post(f'https://layarkacaxxi.icu{rg4}') js = json.loads(req7.text) print("\n\t[ Resulution ]") for x in js['data']: print(f"{cc}. {x['label']}") cc += 1 lih = int(input("_> pilih: ")) if lih <= 0: print("index out of ranges") return True downld2(js['data'][lih - 1]['file'], f"{judul} {js['data'][lih-1]['label']}")
def on_help_clicked(self): """Open the Dropbox help website.""" click.launch("https://dropbox.com/help")
def reveal_on_filesystem(self): medias = self.lst_media.selectedItems() logger.info("Opening file location for {} files".format(medias)) for item in medias: media = self.lst_media.itemWidget(item) click.launch(win_short_path(media.path), locate=True)
def project_dashboard(obj, remote_id): """Open project dashboard""" click.launch(get_cp_url(client=obj.client, project_id=remote_id))
def cli(ctx, path, **kwds): """Open latest Planemo test results in a web browser.""" click.launch(path)
def fn(book_id): """Open web page for book.""" book = self.get_book(book_id) if book: click.echo(f'Opening {book.url}') click.launch(book.url)
def on_help_clicked(self): """Open the Dropbox help website.""" click.launch(f"{__url__}/docs")
def setup_ui_linked(self): if not self.mdbx: return self.autostart = None self.settings_window = SettingsWindow(self, self.mdbx) self.setToolTip(IDLE) # ------------- populate context menu ------------------- self.menu.clear() openDropboxFolderAction = self.menu.addAction("Open Dropbox Folder") openDropboxFolderAction.triggered.connect( lambda: click.launch(self.mdbx.dropbox_path)) openWebsiteAction = self.menu.addAction("Launch Dropbox Website") openWebsiteAction.triggered.connect(self.on_website_clicked) self.menu.addSeparator() self.accountEmailAction = self.menu.addAction( self.mdbx.get_conf("account", "email")) self.accountEmailAction.setEnabled(False) self.accountUsageAction = self.menu.addAction( self.mdbx.get_conf("account", "usage")) self.accountUsageAction.setEnabled(False) self.menu.addSeparator() self.statusAction = self.menu.addAction(IDLE) self.statusAction.setEnabled(False) self.pauseAction = self.menu.addAction( self.PAUSE_TEXT if self.mdbx.syncing else self.RESUME_TEXT) self.pauseAction.triggered.connect(self.on_start_stop_clicked) self.recentFilesMenu = self.menu.addMenu("Recently Changed Files") if platform.system() == "Linux": # on linux, submenu.aboutToShow may not be emitted # (see https://bugreports.qt.io/browse/QTBUG-55911) # therefore, we update the recent files list when the main menu is about to show self.menu.aboutToShow.connect(self.update_recent_files) else: self.recentFilesMenu.aboutToShow.connect(self.update_recent_files) self.menu.addSeparator() preferencesAction = self.menu.addAction("Preferences...") preferencesAction.triggered.connect(self.on_settings_clicked) updatesAction = self.menu.addAction("Check for Updates...") updatesAction.triggered.connect(self.on_check_for_updates_clicked) helpAction = self.menu.addAction("Help Center") helpAction.triggered.connect(self.on_help_clicked) self.menu.addSeparator() self.syncIssuesAction = self.menu.addAction("Show Sync Issues...") self.syncIssuesAction.triggered.connect(self.on_sync_issues_clicked) rebuildAction = self.menu.addAction("Rebuild index...") rebuildAction.triggered.connect(self.on_rebuild_clicked) self.menu.addSeparator() if self._started: quitAction = self.menu.addAction("Quit Maestral") else: quitAction = self.menu.addAction("Quit Maestral GUI") quitAction.triggered.connect(self.quit) # --------------- switch to idle icon ------------------- self.setIcon(IDLE)
def project_cheatsheet(obj, remote_id): """Show useful commands for your project""" click.launch( get_cp_url(obj.client, project_id=remote_id, section='local-development/'), )
def user() -> dict: """ Get the active user """ global data if data: return data else: click.echo( 'Hi! Thank you for using ' + click.style('Asyncy', fg='magenta') + '.' ) click.echo('Please login with GitHub to get started.') state = uuid4() query = { 'state': state } url = f'https://stories.asyncyapp.com/github?{urlencode(query)}' click.launch(url) click.echo() click.echo('Visit this link if your browser ' 'doesn\'t open automatically:') click.echo(url) click.echo() with click_spinner.spinner(): while True: try: url = 'https://stories.asyncyapp.com/github/oauth_callback' res = requests.get(f'{url}?state={state}') if res.text == 'null': raise IOError() res.raise_for_status() write(res.text, f'{home}/.config') init() break except IOError: time.sleep(0.5) # just try again pass except KeyboardInterrupt: click.echo('Login failed. Please try again.') sys.exit(1) click.echo( emoji.emojize(':waving_hand:') + f' Welcome {data["name"]}!' ) click.echo() click.echo('Create a new app with:') print_command('asyncy apps create') click.echo() click.echo('To list all your apps:') print_command('asyncy apps') click.echo() track('Login Completed') try: if enable_reporting: requests.post( 'https://stories.asyncyapp.com/track/profile', json={ 'id': str(data['id']), 'profile': { 'Name': data['name'], 'Email': data.get('email'), 'GitHub Username': data.get('username'), 'Timezone': time.tzname[time.daylight] } }) except: # Ignore tracking errors pass return data
def play_stream(self, track_data): """ Given track data, generate the stream url and pass it to ffplay to handle. While stream is playing allow user input to control playback :param track_data: dict :return: """ stream_url = self.create_url('download') song_id = track_data.get('id') if self.notify: self.notifications.get_cover_art(track_data) if not song_id: return False click.secho('{} by {}'.format(track_data.get('title', ''), track_data.get('artist', '')), fg='green') self.scrobble(song_id) params = [ 'ffplay', '-i', '{}&id={}&format={}'.format(stream_url, song_id, self.format), '-showmode', '{}'.format(self.show_mode), '-window_title', '{} by {}'.format(track_data.get('title', ''), track_data.get('artist', '')), '-autoexit', '-hide_banner', '-x', '500', '-y', '500', '-loglevel', 'fatal', '-infbuf', ] params = self.pre_exe + params if len(self.pre_exe) > 0 else params if not self.display: params += ['-nodisp'] try: if self.notify: self.notifications.show_notification(track_data) ffplay = Popen(params) has_finished = None open(os.path.join(click.get_app_dir('pSub'), 'play.lock'), 'w+').close() while has_finished is None: has_finished = ffplay.poll() if self.input_queue.empty(): time.sleep(1) continue command = self.input_queue.get_nowait() self.input_queue.queue.clear() if 'x' in command.lower(): click.secho('Exiting!', fg='blue') os.remove( os.path.join(click.get_app_dir('pSub'), 'play.lock')) ffplay.terminate() return False if 'b' in command.lower(): click.secho('Restarting Track....', fg='blue') os.remove( os.path.join(click.get_app_dir('pSub'), 'play.lock')) ffplay.terminate() return self.play_stream(track_data) if 'n' in command.lower(): click.secho('Skipping...', fg='blue') os.remove( os.path.join(click.get_app_dir('pSub'), 'play.lock')) ffplay.terminate() return True os.remove(os.path.join(click.get_app_dir('pSub'), 'play.lock')) return True except OSError as err: click.secho( f'Could not run ffplay. Please make sure it is installed, {str(err)}', fg='red') click.launch('https://ffmpeg.org/download.html') return False except CalledProcessError as e: click.secho( 'ffplay existed unexpectedly with the following error: {}'. format(e), fg='red') return False
def cli(ctx, **kwds): """Open the Planemo documentation in a web browser.""" click.launch(SYNTAX_URL)
def readability_exporter(api_key, api_secret, login_user, login_pw, format, bookmarks, export_directory, export_filename, not_show_file, http_error_threshold): """Readability Exporter This little script takes credentials for a Readability account and the API key and secret to create the standard Readability export file in JSON format that can be used to import your links into Instapaper. We think about adding support for the del.icio.us flavour of bookmarks.html to allow direct import into Pocket. You can find more information about this script on GitHub at https://github.com/goetzb/readability-exporter """ click.echo(click.style('Readability Exporter', bold=True)) # Create string for export filename if '{timestamp}' not in export_filename: export_filename += '_{timestamp}' if '{format}' not in export_filename: export_filename += '_{format}' if '{filetype}' not in export_filename: export_filename += '.{filetype}' # Prepare json export dictionary export_dict = OrderedDict() export_dict['bookmarks'] = [] # Add empty recommendations list - in my example this was just empty. export_dict["recommendations"] = [] # Prepare jsonraw export dictionary export_dict_raw = OrderedDict() # Prepare html export string export_html = """<!DOCTYPE NETSCAPE-Bookmark-file-1> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> <!-- This is an automatically generated file. It will be read and overwritten. Do Not Edit! --> <TITLE>Bookmarks</TITLE> <H1>Bookmarks</H1> <DL><p> """ auth_tokens = get_auth_tokens(api_key=api_key, api_secret=api_secret, login_user=login_user, login_pw=login_pw) if len(auth_tokens) != 2: click.ClickException( """An error occurred and you could not be authenticated successfully. Please check your Readability API keys and login details.""") client = ReaderClient(token_key=auth_tokens[0], token_secret=auth_tokens[1], consumer_key=api_key, consumer_secret=api_secret) meta_infos = get_readability_meta_infos(readability_reader_client=client) click.echo("* You have saved " + click.style("{link_count}".format( link_count=meta_infos['bookmarks_total']), bold=True) + " links on Readability") if bookmarks == 0: bookmarks = meta_infos['bookmarks_total'] click.echo("* We are now going to export the latest " + click.style("{export_count}".format(export_count=bookmarks), bold=True) + " of your links") if bookmarks < 50: bookmarks_per_page = bookmarks + 1 else: bookmarks_per_page = 50 bookmarks_get_pages = int(ceil(bookmarks / bookmarks_per_page)) data_export = export_bookmarks_via_api( readability_reader_client=client, export_formats=format, bookmarks_number=bookmarks, bookmarks_per_page=bookmarks_per_page, bookmarks_get_pages=bookmarks_get_pages, export_json=export_dict, export_html=export_html, export_jsonraw=export_dict_raw, error_threshold=http_error_threshold) click.echo( "Bear with us, we are almost there. In the next step we bring the data into the right formats." ) exported_files = [] files_export_count = 0 timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S") with click.progressbar(label='Writing export files...', length=len(format), show_percent=True) as files_bar: for export_format in format: output_data = data_export[export_format] if export_format == 'json' or export_format == 'jsonraw': filetype = 'json' elif export_format == 'html': filetype = 'html' output_data += "</DL><p>" format_export_filename = export_filename.format( timestamp=timestamp, format=export_format, filetype=filetype) export_file = write_export_data(filetype=filetype, directory=export_directory, filename=format_export_filename, data=output_data) exported_files.append(export_file) files_export_count += 1 files_bar.update(files_export_count) # TODO: Improve bookmark count to verify if actually the correct number of bookmarks has been exported # Get length of 'bookmarks' in json export dictionary click.echo( click.style( "Good news! We have successfully exported {number_of_bookmarks} bookmarks for you." .format(number_of_bookmarks=bookmarks), fg='green')) for exported_file in exported_files: if exported_file['file_size'] / 1024 > 1024: file_size_string = '{size:d} MiB'.format( size=int(round(exported_file['file_size'] / 1024 / 1024))) elif exported_file['file_size'] > 1024: file_size_string = '{size:d} KiB'.format( size=int(round(exported_file['file_size'] / 1024))) else: file_size_string = '{size:d} B'.format( size=exported_file['file_size']) click.echo("You can find your exported data in ") click.echo( click.style(" {path}".format(path=exported_file['file_path']), bold=True)) click.echo(" (~{size})".format(size=file_size_string)) click.echo( click.style("Thank you for using this little tool!", reverse=True)) if not not_show_file: click.echo( click.style( "We will now try to open your file manager with the exported file selected.", reverse=True)) click.launch(export_directory, locate=True)
def cli(port, host, no_open, shutdown_timeout): # pylint: disable=import-error, import-outside-toplevel # import contrib modules inject_contrib_pysite() try: from autobahn.twisted.resource import WebSocketResource except: # pylint: disable=bare-except build_contrib_pysite_deps(get_core_package_dir("contrib-pysite")) from autobahn.twisted.resource import WebSocketResource from twisted.internet import reactor from twisted.web import server from platformio.commands.home.rpc.handlers.app import AppRPC from platformio.commands.home.rpc.handlers.ide import IDERPC from platformio.commands.home.rpc.handlers.misc import MiscRPC from platformio.commands.home.rpc.handlers.os import OSRPC from platformio.commands.home.rpc.handlers.piocore import PIOCoreRPC from platformio.commands.home.rpc.handlers.project import ProjectRPC from platformio.commands.home.rpc.server import JSONRPCServerFactory from platformio.commands.home.web import WebRoot factory = JSONRPCServerFactory(shutdown_timeout) factory.addHandler(AppRPC(), namespace="app") factory.addHandler(IDERPC(), namespace="ide") factory.addHandler(MiscRPC(), namespace="misc") factory.addHandler(OSRPC(), namespace="os") factory.addHandler(PIOCoreRPC(), namespace="core") factory.addHandler(ProjectRPC(), namespace="project") contrib_dir = get_core_package_dir("contrib-piohome") if not isdir(contrib_dir): raise exception.PlatformioException("Invalid path to PIO Home Contrib") # Ensure PIO Home mimetypes are known mimetypes.add_type("text/html", ".html") mimetypes.add_type("text/css", ".css") mimetypes.add_type("application/javascript", ".js") root = WebRoot(contrib_dir) root.putChild(b"wsrpc", WebSocketResource(factory)) site = server.Site(root) # hook for `platformio-node-helpers` if host == "__do_not_start__": return already_started = is_port_used(host, port) home_url = "http://%s:%d" % (host, port) if not no_open: if already_started: click.launch(home_url) else: reactor.callLater(1, lambda: click.launch(home_url)) click.echo( "\n".join( [ "", " ___I_", " /\\-_--\\ PlatformIO Home", "/ \\_-__\\", "|[]| [] | %s" % home_url, "|__|____|______________%s" % ("_" * len(host)), ] ) ) click.echo("") click.echo("Open PlatformIO Home in your browser by this URL => %s" % home_url) if already_started: click.secho( "PlatformIO Home server is already started in another process.", fg="yellow" ) return click.echo("PIO Home has been started. Press Ctrl+C to shutdown.") reactor.listenTCP(port, site, interface=host) reactor.run()