def on_event(self, event, extension): """ On user input """ self.extension = extension gopass_cmd = self.extension.preferences['gopass-cmd'] # Get keyword and arguments from event query_keyword = event.get_keyword() query_args = event.get_argument() # Initialize variables path = '' files = [] dirs = [] misc = [] no_filename = False path_not_exists = False search_otp = (extension.preferences['pass-otp-search'] != "") and ( query_keyword == extension.preferences['pass-otp-search']) otp_filter = extension.preferences['otp-filter'] if search_otp else "" if not query_args: # No arguments specified, list folders and passwords in the password-store root files, dirs = self.extension.search(depth=1, search_filter=otp_filter) else: # Splitting arguments into path and pattern path = os_path.split(query_args)[0] pattern = os_path.split(query_args)[1] # If the path begins with a slash we remove it if path.startswith('/'): path = path[1:] # store_location = os_path.expanduser(self.extension.preferences['store-location']) files_and_folders = get_files_and_folders( self.extension.preferences, otp_filter) depth = None if not re.findall(r"^{path}(.+)$".format(path=path), files_and_folders, flags=re.MULTILINE): path_not_exists = True if query_keyword == extension.preferences['pass-search']: # If specified folder does not exist and we are in searching mode, # show the user an error misc.append(WRONG_PATH_ITEM) if not pattern: # If the path exists and there is no pattern, only show files # and dirs in the current location depth = 1 if query_keyword == extension.preferences['pass-generate']: # If we are in generation mode and no pattern is given, # show the user an error no_filename = True misc.append(NO_FILENAME_ITEM) if not no_filename and query_keyword == extension.preferences[ 'pass-generate']: # If the user specified a pattern and we are in generation mode # give him the possibility to generate the password action = RunScriptAction( "{} generate --symbols={} --force=true --strict=false -c {} {}" .format(gopass_cmd, self.extension.preferences['special-characters'], os_path.join(path, pattern), self.extension.preferences['password-length']), None) misc.append( ExtensionResultItem( icon=PASSWORD_ICON, name='Generate /{}'.format(os_path.join(path, pattern)), description='Enter to generate and save password', on_enter=action)) # If the specified path doesn't exist it makes no sense to search for a password if not path_not_exists: files, dirs = self.extension.search(path=path, pattern=pattern, depth=depth, search_filter=otp_filter) if query_keyword == extension.preferences['pass-generate']: # If we are in generation mode we can remove the files files = [] return RenderResultListAction( misc + self.render_results(path, files, dirs, query_keyword, search_otp))
def on_event(self, event, extension): items = [] text = event.get_argument() or "" return RenderResultListAction(extension.search_package(text))
def _spotify_not_launched(): return RenderResultListAction([ ExtensionResultItem(icon=cs.IconPaths.ICON, name='Run Spotify desktop app first', on_enter=LaunchAppAction(cs.SPOTIFY_PATH)), ])
def on_event(self, event, extension): query = event.get_argument() if (len(query) < 3): return RenderResultListAction([]) regex = r".{3}-\d{1,5}" pattern = re.compile(regex) jqlQuery = "" if (pattern.match(query)): jqlQuery = "key=\"" + query + "\"" else: jqlQuery = "summary~\"" + query + "\" OR description~\"" + query + "\"" results = [] workspace_url = extension.preferences.get('url') user = extension.preferences.get('username') password = extension.preferences.get('password') maxResults = extension.preferences.get('maxResults') token = base64.b64encode(str('%s:%s' % (user, password)).encode()).decode() url = urllib.parse.urljoin(workspace_url, 'rest/api/latest/search') get_url = "%s?%s" % (url, urllib.parse.urlencode({ 'jql': jqlQuery, 'maxResults': maxResults })) req = urllib.request.Request(get_url, headers={ 'Authorization': 'Basic %s' % token, 'Content-Type': 'application/json' }, method="GET") result_types = [] try: response = urllib.request.urlopen(req) result_types = json.loads(response.read()) except urllib.error.HTTPError as e: if e.code == 401: results.append( ExtensionResultItem( name='Authentication failed.', description= 'Please check your username/e-mail and password.', icon=self.icon_file, on_enter=DoNothingAction())) return RenderResultListAction(results) except urllib.error.URLError as e: results.append( ExtensionResultItem( name='Could not connect to Jira.', description= 'Please check your workspace url and make sure you are connected to the internet.', icon=self.icon_file, on_enter=DoNothingAction())) return RenderResultListAction(results) issues = result_types.get('issues') for issue in issues: key = issue.get('key') title = issue.get('fields').get('summary') url1 = urllib.parse.urljoin(workspace_url, 'browse/%s' % key) results.append( ExtensionResultItem(name=title if not key else '%s - %s' % (key, title), description=key, icon=self.icon_file, on_enter=OpenUrlAction(url=url1))) if not results: results.append( ExtensionResultItem( name="Search '%s'" % query, description='No results. Try searching something else :)', icon=self.icon_file, on_enter=DoNothingAction())) return RenderResultListAction(results)
def action(self, result_list): return RenderResultListAction(result_list)
def execute(self, container_id): """ Show container details """ try: container = self.extension.docker_client.containers.get( container_id) except docker.errors.NotFound: return RenderResultListAction([ExtensionResultItem( icon='images/icon.png', name="No container found with id %s" % container_id, highlightable=False, on_enter=HideWindowAction() )]) items = [] attrs = container.attrs ports = container.attrs['NetworkSettings']['Ports'] ports_list = [] for container_port, host_mapping in ports.iteritems(): if host_mapping is not None: ports_str = "%s -> %s" % (container_port, "%s:%s" % ( host_mapping[0]['HostIp'], host_mapping[0]['HostPort'])) ports_list.append(ports_str) ip_address = container.attrs['NetworkSettings']['IPAddress'] if not ip_address: ip_address = attrs['NetworkSettings']['Networks'].values()[ 0]['IPAddress'] items.append(ExtensionResultItem( icon='images/icon.png', name=container.name, description=attrs['Config']['Image'], highlightable=False, on_enter=HideWindowAction() )) if container.status != 'running': items.append(ExtensionResultItem( icon='images/icon_start.png', name="Start", description="Start the specified container", highlightable=False, on_enter=ExtensionCustomAction( {'action': ACTION_START_CONTAINER, 'id': container.short_id}) )) if container.status == 'running': items.append(ExtensionResultItem( icon='images/icon_ip.png', name="IP Address", description=ip_address, highlightable=False, on_enter=OpenUrlAction(ip_address), on_alt_enter=CopyToClipboardAction(ip_address) )) items.append(ExtensionResultItem( icon='images/icon_ip.png', name="Ports", description='\n'.join(ports_list), highlightable=False, on_enter=HideWindowAction(), )) items.append(ExtensionResultItem( icon='images/icon_terminal.png', name="Open container shell", description="Opens a new sh shell in the container", highlightable=False, on_enter=RunScriptAction( "x-terminal-emulator -e docker exec -it %s sh" % container.short_id, []) )) items.append(ExtensionResultItem( icon='images/icon_stop.png', name="Stop", description="Stops The container", highlightable=False, on_enter=ExtensionCustomAction( {'action': ACTION_STOP_CONTAINER, 'id': container.short_id}) )) items.append(ExtensionResultItem( icon='images/icon_restart.png', name="Restart", description="Restarts the container", highlightable=False, on_enter=ExtensionCustomAction( {'action': ACTION_RESTART_CONTAINER, 'id': container.short_id}) )) items.append(ExtensionResultItem( icon='images/icon_logs.png', name="Logs", description="Show logs of the container", highlightable=False, on_enter=RunScriptAction( "x-terminal-emulator -e docker logs -f %s" % container.short_id, []) )) return RenderResultListAction(items)
def on_event(self, event, extension): keyword = event.get_keyword() argument = event.get_argument() if argument and '/' in argument: # there's an argument and has a "/", we must interpret it like this: # "f /foo/bar/baz else" == "search 'baz else' inside /foo/bar/" bits = argument.split('/') current_path = Path('/'.join(bits[:-1])) current_filter = bits[-1] else: # there's no argument, or the argument has no "/". Search inside the default path current_path = Path(extension.preferences.get('fb_default_path')) current_filter = argument current_path = current_path.expanduser() items = [] # if we aren't filtering stuff inside the current dir, show an option to open the current # dir in the OS's file browser if not current_filter: item = ExtensionSmallResultItem( icon=get_icon_for_file(current_path), name="[ Open folder in external file browser ]", on_enter=OpenAction(str(current_path)), ) items.append(item) # children items, filtered, and folders first sorted_children = list( sorted( current_path.iterdir(), key=lambda child_path: (not child_path.is_dir(), child_path.name), )) items_limit = extension.preferences.get('fb_items_limit') if items_limit is not None: try: items_limit = int(items_limit) except ValueError: pass show_hidden = extension.preferences.get('fb_show_hidden') == 'Yes' # show each one of them items_count = 0 for child_path in sorted_children: if show_hidden or not child_path.name.startswith('.'): if matches_filter(child_path.name, current_filter): if child_path.is_dir(): item_action = SetUserQueryAction("{} {}/".format( keyword, str(child_path))) else: item_action = OpenAction(str(child_path)) item = ExtensionSmallResultItem( icon=get_icon_for_file(child_path), name=child_path.name, on_enter=item_action, ) items.append(item) items_count += 1 if items_limit is not None and items_count == items_limit: break return RenderResultListAction(items)
def on_event(self, event, extension): data = event.get_data() or "" subprocess.Popen(data, shell=True) return RenderResultListAction([])
def on_event(self, event, extension): items = [] options = [ 'logout', 'restart', 'reboot', 'shutdown', 'halt', 'suspend', 'sleep', 'hibernate' ] reboot_command = extension.preferences['reboot_command'] shutdown_command = extension.preferences['shutdown_command'] logout_command = extension.preferences['logout_command'] suspend_command = extension.preferences['suspend_command'] hibernate_command = extension.preferences['hibernate_command'] myList = event.query.split(" ") if len(myList) == 1: items.append( ExtensionResultItem(icon='images/reboot.png', name='Reboot', description='Restart computer', on_enter=RunScriptAction( reboot_command, None))) items.append( ExtensionResultItem(icon='images/shutdown.png', name='Shutdown', description='Power off computer', on_enter=RunScriptAction( shutdown_command, None))) items.append( ExtensionResultItem(icon='images/logout.png', name='Logout', description='Logout from session', on_enter=RunScriptAction( logout_command, None))) items.append( ExtensionResultItem(icon='images/suspend.png', name='Suspend', description='Trigger sleep mode', on_enter=RunScriptAction( suspend_command, None))) items.append( ExtensionResultItem(icon='images/hibernate.png', name='Hibernate', description='Suspend to disk', on_enter=RunScriptAction( hibernate_command, None))) return RenderResultListAction(items) else: myQuery = myList[1] included = [] for option in options: if myQuery in option: if option in ['shutdown', 'halt' ] and 'shutdown' not in included: items.append( ExtensionResultItem( icon='images/shutdown.png', name='Shutdown', description='Power off computer', on_enter=RunScriptAction( shutdown_command, None))) included.append('shutdown') elif option in ['restart', 'reboot' ] and 'reboot' not in included: items.append( ExtensionResultItem(icon='images/reboot.png', name='Reboot', description='Restart computer', on_enter=RunScriptAction( reboot_command, None))) included.append('reboot') elif option in ['suspend', 'sleep' ] and 'suspend' not in included: items.append( ExtensionResultItem( icon='images/suspend.png', name='Suspend', description='Trigger sleep mode', on_enter=RunScriptAction( suspend_command, None))) included.append('suspend') elif option in ['logout']: items.append( ExtensionResultItem( icon='images/logout.png', name='Logout', description='Logout from session', on_enter=RunScriptAction(logout_command, None))) elif option in ['hibernate']: items.append( ExtensionResultItem(icon='images/hibernate.png', name='Hibernate', description='Suspend to disk', on_enter=RunScriptAction( hibernate_command, None))) return RenderResultListAction(items)
def on_event(self, event, extension): return RenderResultListAction( [ExtensionResultItem( icon=_icon_, name=_name_, description="Enter a query in the form of \"[set] <key> <value> | [get] <key>; [unset]\"")])
def return_error(self, msg): item = ExtensionResultItem(name=msg) return RenderResultListAction([item])
def get_stops(self, ev: KeywordQueryEvent, arg: str) -> BaseAction: items = [] for stop in self.drt.stops(ev.get_argument())[:5]: items.append(self.make_stop(stop, ev.get_query())) return RenderResultListAction(items)
def get_favorites(self, ev: KeywordQueryEvent) -> BaseAction: return RenderResultListAction([ self.make_favourite(stop, self.drt.departures(str(stop.id)), ev.get_query()) for stop in self.fav_get() ])
def list_commands(command_suggestions=None): if command_suggestions is not None: items = [COMMANDS[action] for action in command_suggestions] else: items = [value for (key, value) in COMMANDS.items()] return RenderResultListAction(items)
def _render(self, i: Union[list, ExtensionResultItem]) -> RenderResultListAction: if isinstance(i, list): return RenderResultListAction(i) elif isinstance(i, ExtensionResultItem): return RenderResultListAction([i])
def on_event(self, event, extension): items = extension.get_items(event.get_argument()) return RenderResultListAction(items)
def on_event(self, event, extension): return RenderResultListAction(list(islice(self.generate_results(event), 10)))
def on_event(self, event, extension): """ On user input """ self.extension = extension # Get keyword and arguments from event query_keyword = event.get_keyword() query_args = event.get_argument() # Initialize variables path = '' files = [] dirs = [] misc = [] no_filename = False path_not_exists = False if not query_args: # No arguments specified, list folders and passwords in the password-store root files, dirs = self.extension.search(depth=1) else: # Splitting arguments into path and pattern path = os_path.split(query_args)[0] pattern = os_path.split(query_args)[1] # If the path begins with a slash we remove it if path.startswith('/'): path = path[1:] store_location = os_path.expanduser( self.extension.preferences['store-location']) depth = None if not os_path.exists(os_path.join(store_location, path)): path_not_exists = True if query_keyword == extension.preferences['pass-search']: # If specified folder does not exist and we are in searching mode, # show the user an error misc.append(WRONG_PATH_ITEM) if not pattern: # If the path exists and there is no pattern, only show files # and dirs in the current location depth = 1 if query_keyword == extension.preferences['pass-generate']: # If we are in generation mode and no pattern is given, # show the user an error no_filename = True misc.append(NO_FILENAME_ITEM) if not no_filename and query_keyword == extension.preferences[ 'pass-generate']: # If the user specified a pattern and we are in generation mode # give him the possibility to generate the password action = RunScriptAction( "pass generate -c {}".format(os_path.join(path, pattern)), None) misc.append( ExtensionResultItem( icon=PASSWORD_ICON, name='Generate /{}'.format(os_path.join(path, pattern)), description='Enter to generate and save password', on_enter=action)) # If the specified path doesn't exist it makes no sense to search for a password if not path_not_exists: files, dirs = self.extension.search(path=path, pattern=pattern, depth=depth) if query_keyword == extension.preferences['pass-generate']: # If we are in generation mode we can remove the files files = [] return RenderResultListAction( misc + self.render_results(path, files, dirs, query_keyword))
def on_event(self, event, extension): data = event.get_data() or "" command = 'emacsclient -n -c ' + data subprocess.Popen(command, shell=True) return RenderResultListAction([])
def on_event(self, event, extension): query = event.get_argument() or str() if len(query.strip()) == 0: #<--------- in case the extension is called but there is nothing in input global string_list string_list.clear() #clear the list so it won't repeat the items in case of retyping read_database() print (string_list) #============================= # Copy #============================= if len(string_list) == 0: return RenderResultListAction([ # this is from Ulauncher ExtensionResultItem(icon='images/icon.png', #image name='Your list is empty. Type "add" to add a new item', # text that appears when you type "delete" description="Or click here to access our GitHub page for help", on_enter=OpenUrlAction("https://github.com/LyimeS/Get-it-Fast-a-Ulauncher-extension")) ]) #return RenderResultListAction(items) else: items = [] #list thst goes to render for string_list_item in string_list: if len(string_list_item[1]) < 40: items.append(ExtensionResultItem(icon='images/icon.png', name=string_list_item[1], description='Copy this to your clipboard', on_enter=CopyToClipboardAction(string_list_item[1]))) else: items.append(ExtensionResultItem(icon='images/icon.png', name=string_list_item[1][0:40] + "...", description=f'Copy this to your clipboard. ({len(string_list_item[1])} characters)', on_enter=CopyToClipboardAction(string_list_item[1]))) return RenderResultListAction(items) #============================= # input #============================= elif query.strip()[0:3] == "add": # items = [] #this list goes to render data = {"action": "add", "id": query[4:]} items.append(ExtensionResultItem(icon='images/icon.png', name="I'm done!", description="New item: " + query[4:], on_enter=ExtensionCustomAction(data))) return RenderResultListAction(items) #============================= # Delete #============================= elif query.strip()[0:6] == "delete": string_list.clear() #clear the list so it won't repeat the items in case of retyping read_database() print (string_list) items = [] #this list goes to render for string_list_item in string_list: data = {"action": "delete", "id": string_list_item[0]} items.append(ExtensionResultItem(icon='images/icon.png', name=string_list_item[1], description='Delete this item from your list', on_enter=ExtensionCustomAction(data, keep_app_open=True))) return RenderResultListAction(items) #============================= # anything else #============================= else: return RenderResultListAction([ # this is from Ulauncher ExtensionResultItem(icon='images/icon.png', #image name='Are you lost?', # text that appears when you type "delete" description="Open our help section on GitHub", on_enter=OpenUrlAction("https://github.com/LyimeS/Get-it-Fast-a-Ulauncher-extension")) ])
def on_event(self, event, extension): icon_style = extension.preferences['emoji_style'] fallback_icon_style = extension.preferences['fallback_emoji_style'] search_term = event.get_argument().replace( '%', '') if event.get_argument() else None search_with_shortcodes = search_term and search_term.startswith(':') # Add %'s to search term (since LIKE %?% doesn't work) skin_tone = normalize_skin_tone(extension.preferences['skin_tone']) if skin_tone not in extension.allowed_skin_tones: logger.warning('Unknown skin tone "%s"' % skin_tone) skin_tone = '' search_term_orig = search_term if search_term and search_with_shortcodes: search_term = ''.join([search_term, '%']) elif search_term: search_term = ''.join(['%', search_term, '%']) if search_with_shortcodes: query = ''' SELECT em.name, em.code, em.keywords, em.icon_apple, em.icon_twemoji, em.icon_noto, em.icon_blobmoji, skt.icon_apple AS skt_icon_apple, skt.icon_twemoji AS skt_icon_twemoji, skt.icon_noto AS skt_icon_noto, skt.icon_blobmoji AS skt_icon_blobmoji, skt.code AS skt_code, sc.code as "shortcode" FROM emoji AS em LEFT JOIN skin_tone AS skt ON skt.name = em.name AND tone = ? LEFT JOIN shortcode AS sc ON sc.name = em.name WHERE sc.code LIKE ? GROUP BY em.name ORDER BY length(replace(sc.code, ?, '')) LIMIT 40 ''' sql_args = [skin_tone, search_term, search_term_orig] else: query = ''' SELECT em.name, em.code, em.keywords, em.icon_apple, em.icon_twemoji, em.icon_noto, em.icon_blobmoji, skt.icon_apple AS skt_icon_apple, skt.icon_twemoji AS skt_icon_twemoji, skt.icon_noto AS skt_icon_noto, skt.icon_blobmoji AS skt_icon_blobmoji, skt.code AS skt_code FROM emoji AS em LEFT JOIN skin_tone AS skt ON skt.name = em.name AND tone = ? WHERE em.name LIKE ? LIMIT 40 ''' sql_args = [skin_tone, search_term] # Display blank prompt if user hasn't typed anything if not search_term: search_icon = 'images/%s/icon.png' % icon_style return RenderResultListAction([ ExtensionResultItem(icon=search_icon, name='Type in emoji name...', on_enter=DoNothingAction()) ]) # Get list of results from sqlite DB items = [] display_char = extension.preferences['display_char'] != 'no' for row in conn.execute(query, sql_args): if row['skt_code']: icon = row['skt_icon_%s' % icon_style] icon = row['skt_icon_%s' % fallback_icon_style] if not icon else icon code = row['skt_code'] else: icon = row['icon_%s' % icon_style] icon = row['icon_%s' % fallback_icon_style] if not icon else icon code = row['code'] name = row['shortcode'] if search_with_shortcodes else row[ 'name'].capitalize() if display_char: name += ' | %s' % code items.append( ExtensionResultItem(icon=icon, name=name, on_enter=CopyToClipboardAction(code))) return RenderResultListAction(items)
def do_nothing_result(self, text, icon=extension_icon): return RenderResultListAction([ ExtensionResultItem(icon=extension_icon, name=text, on_enter=DoNothingAction()) ])
def _render_loading(self, icon): loading_item = ResultItem(name='Loading...', icon=icon, highlightable=False) RenderResultListAction([loading_item]).run()
def on_event(self, event, extension): term = (event.get_argument() or '').lower() items = [i for name, i in items_cache if name.startswith(term)] return RenderResultListAction(items)
def on_event(self, event, extension): query = event.get_argument() or str() script = extension.preferences["script"] getir = os.popen("lsof -i").read() boluk = getir.split("\n") baslk = boluk.pop(0).split() liste = {} for j, i in enumerate(boluk): col = i.split() if len(col) < 3: continue col[-2] += col[-1] col.remove(col[-1]) liste[str(j)] = {} for t, k in enumerate(col): liste[str(j)][baslk[t]] = k # Seçili Stil'i bulur. Sorgu satırına yazılan kod, ayarlardaki koddan üstündür. selected = extension.preferences["tips"] for i in ["t0", "t1", "t2", "t3", "t4", "t5", "t6"]: if i in query: selected = i query = query.replace(i, "").strip() items = [] if selected == "t0": # Aynı dosya isimleri başlıkta birleştirilmiş, bahlantı adresleri açıklamada o = {} for i in liste.keys(): if liste[i]["COMMAND"] in o: o[liste[i]["COMMAND"]].append(liste[i]["NAME"]) elif "NAME" in liste[i]: # I couldn't manage to make a merge. Sorry # fixed: https://github.com/jasonsyoung/ulauncher-nettekim/ o[liste[i]["COMMAND"]] = [liste[i]["NAME"]] query = query.replace("t0", "").strip() for i in o.keys(): if len(query) > 0 and query not in i: continue items.append( ExtensionResultItem(icon='images/icon.png', name=i, description="\n".join(o[i]), on_enter=RunScriptAction(script))) else: desc_list = ["NAME", "USER", "PID", "TYPE", "NODE", "DEVICE"] for i in liste.keys(): if len(query) > 0 and query not in liste[i]["COMMAND"]: continue items.append( ExtensionResultItem(icon='images/icon.png', name=liste[i]["COMMAND"], description="\n".join([ desc_list[u] + " : " + liste[i][desc_list[u]] for u in range(int(selected[1])) ]), on_enter=RunScriptAction(script))) return RenderResultListAction(items)
def on_alt_enter(self, query): menu_items = self._get_dir_alt_menu() if self.path.is_dir( ) else self._get_file_alt_menu() return RenderResultListAction(menu_items)
def on_event(self, event, extension): items = [] options = [ 'ec2', 'ecs', 'rds', 's3', 'elasticbeanstalk', 'elasticache', 'cloudwatch', 'cloudformation', 'vpc', 'iam', 'ecr', 'eks', 'lambda', 'dynamodb', 'managementconsole', 'management', 'console', 'support', 'ticket', 'helpdesk', 'help', 'billing', 'budget', 'costs', 'pricingcalculator', 'pricing', 'price', 'prices', 'calculate', 'calculator', 'compare', 'instancecomparison', 'comparison', 'route53', 'dns', 'sqs', 'sns', 'ses', 'elasticsearch', 'kms', 'cloudfront', 'api', 'gateway', 'cloudtrail', 'secret', 'airflow', 'mwaa' ] my_list = event.query.split(" ") if len(my_list) == 1: items.append(get_ec2_item()) items.append(get_ecs_item()) items.append(get_rds_item()) items.append(get_s3_item()) items.append(get_elasticbeanstalk_item()) items.append(get_elasticache_item()) items.append(get_cloudwatch_item()) items.append(get_cloudformation_item()) items.append(get_vpc_item()) items.append(get_iam_item()) items.append(get_ecr_item()) items.append(get_eks_item()) items.append(get_lambda_item()) items.append(get_dynamodb_item()) items.append(get_managementconsole_item()) items.append(get_support_item()) items.append(get_billing_item()) items.append(get_pricingcalculator()) items.append(get_compare()) items.append(get_route53_item()) items.append(get_sqs_item()) items.append(get_sns_item()) items.append(get_ses_item()) items.append(get_cloudfront_item()) items.append(get_kms_item()) items.append(get_elasticsearch_item()) items.append(get_api_gateway_item()) items.append(get_secret_item()) items.append(get_cloudtrail_item()) items.append(get_mwaa_item()) return RenderResultListAction(items) else: my_query = my_list[1] included = [] for option in options: if my_query in option: if option in ['ec2']: items.append(get_ec2_item()) elif option in ['ecs']: items.append(get_ecs_item()) elif option in ['rds']: items.append(get_rds_item()) elif option in ['s3']: items.append(get_s3_item()) elif option in ['elasticbeanstalk']: items.append(get_elasticbeanstalk_item()) elif option in ['elasticache']: items.append(get_elasticache_item()) elif option in ['cloudwatch']: items.append(get_cloudwatch_item()) elif option in ['cloudformation']: items.append(get_cloudformation_item()) elif option in ['vpc']: items.append(get_vpc_item()) elif option in ['iam']: items.append(get_iam_item()) elif option in ['ecr']: items.append(get_ecr_item()) elif option in ['eks']: items.append(get_eks_item()) elif option in ['lambda']: items.append(get_lambda_item()) elif option in ['dynamodb']: items.append(get_dynamodb_item()) elif option in ['managementconsole', 'management', 'console'] and 'managementconsole' not in included: items.append(get_managementconsole_item()) included.append('managementconsole') elif option in ['support', 'ticket', 'helpdesk', 'help'] and 'support' not in included: items.append(get_support_item()) included.append('support') elif option in ['billing', 'budget', 'costs'] and 'billing' not in included: items.append(get_billing_item()) included.append('billing') elif option in ['pricingcalculator', 'pricing', 'price', 'prices', 'calculate', 'calculator'] and 'pricingcalculator' not in included: items.append(get_pricingcalculator()) included.append('pricingcalculator') elif option in ['compare', 'instancecomparison', 'comparison'] and 'compare' not in included: items.append(get_compare()) included.append('compare') elif option in ['route53', 'dns'] and 'route53' not in included: items.append(get_route53_item()) included.append('route53') elif option in ['sqs']: items.append(get_sqs_item()) elif option in ['sns']: items.append(get_sns_item()) elif option in ['ses']: items.append(get_ses_item()) elif option in ['cloudfront']: items.append(get_cloudfront_item()) elif option in ['kms']: items.append(get_kms_item()) elif option in ['elasticsearch']: items.append(get_elasticsearch_item()) elif option in ['api', 'gateway']: items.append(get_api_gateway_item()) elif option in ['secret']: items.append(get_secret_item()) elif option in ['cloudtrail']: items.append(get_cloudtrail_item()) elif option in ['airflow', 'mwaa']: items.append(get_mwaa_item()) return RenderResultListAction(items)
def on_event(self, event, extension): keyword = event.get_keyword() preferences = extension.preferences query_words = event.get_argument() if query_words == None: query_words = "" if preferences["cb_lib_path"] == 'default': try: with open(home + '/.config/calibre/global.py') as f: text = f.readlines() for i in text: if 'library_path' in i: calibre_lib_path = i.strip()[17:-1] except FileNotFoundError: pass if keyword == preferences["cb_kw"]: import sqlite3 if not preferences["cb_lib_path"] == 'default': calibre_lib_path = preferences["cb_lib_path"] if preferences["cb_lib_path"][-1] == '/': conn = sqlite3.connect(preferences["cb_lib_path"] + "metadata.db") else: conn = sqlite3.connect(preferences["cb_lib_path"] + "/metadata.db") else: print(calibre_lib_path + "/metadata.db") conn = sqlite3.connect(calibre_lib_path + "/metadata.db") c = conn.cursor() queries = query_words.split() if len(queries) == 1: results = c.execute( 'select title, author_sort, path from books where (title like "%{}%" or author_sort like "%{}%") limit 10' .format(queries[0], queries[0])) elif len(queries) == 2: results = c.execute( 'select title, author_sort, path from books where (title like "%{}%" or author_sort like "%{}%") and id in (select id from books where title like "%{}%" or author_sort like "%{}%")' .format(queries[1], queries[1], queries[0], queries[0])) items = [] for i in results: cover = 'images/gnome.png', pad = calibre_lib_path + '/{}'.format(i[2]) for f in os.listdir(pad): if f.split('.')[-1] in ['pdf', 'djvu', 'epub']: filepath = os.path.join(pad, f) print('FILE =', filepath) if f.endswith(".jpg"): cover = os.path.join(pad, f) print("cover = ", cover) data = '%s' % filepath items.append( ExtensionResultItem(icon='%s' % cover, name='%s' % i[0], description="%s" % i[1], on_enter=ExtensionCustomAction( data, keep_app_open=True))) elif keyword == preferences["rc_kw"]: from recoll import recoll db = recoll.connect() query = db.query() query_words_list = query_words.split() if not 'g' in query_words_list[:-1]: res = query.execute(query_words) if res < 200: result_list = query.fetchmany(res) results = [[ doc.filename, query.makedocabstract(doc)[:80], doc.url ] for doc in result_list[:15]] else: result_list = query.fetchmany(200) results = [[ doc.filename, query.makedocabstract(doc)[:80], doc.url ] for doc in result_list[:15]] else: query.execute(' '.join( query_words_list[:query_words_list.index('g')])) if res < 200: result_list = query.fetchmany(res) results = [[ doc.filename, query.makedocabstract(doc)[:80], doc.url ] for doc in result_list if query_words_list[-1].lower() in doc.filename.lower()] else: result_list = query.fetchmany(200) results = [[ doc.filename, query.makedocabstract(doc)[:80], doc.url ] for doc in result_list if query_words_list[-1].lower() in doc.filename.lower()] #results = sorted(output, key=lambda entry: entry[2])[::-1] items = [] for i in results: data = '%s' % i[2] items.append( ExtensionResultItem(icon='images/recoll.png', name='%s' % i[0], description="%s" % i[1], on_enter=ExtensionCustomAction( data, keep_app_open=True))) elif keyword == preferences["df_kw"]: from search import search out = search(query_words, 28834) output = [[ doc.getFilename(), doc.getPathStr(), doc.getLastModifiedStr() ] for doc in out] results = sorted(output, key=lambda entry: entry[2])[::-1] items = [] for i in results: data = '%s' % i[1] items.append( ExtensionResultItem(icon='images/docfetcher.png', name='%s' % i[0], description="%s" % i[1], on_enter=ExtensionCustomAction( data, keep_app_open=True))) else: if keyword == preferences["gt_kw"]: query_words_list = query_words.split() if preferences["autowildcardsearch"] == 'Yes': if " " in query_words: query_words = "*".join(query_words.split(' ')) + "*" else: if not 'g' in query_words_list[:-1]: query_words = query_words else: query_words = ' '.join( query_words_list[:query_words_list.index('g')]) command = [ 'tracker', 'sparql', '-q', "SELECT nfo:fileName(?f) nie:url(?f) WHERE { ?f nie:url ?url FILTER(fn:starts-with(?url, \'file://" + home + "/\')) . ?f fts:match '" + query_words + "' } ORDER BY nfo:fileLastAccessed(?f)" ] # command = ['tracker', 'sparql', '-q', "SELECT nfo:fileName(?f) nie:url(?f) WHERE { ?f nie:url ?url FILTER(fn:starts-with(?url, \'file://" + home + "/\')) . ?f nie:plainTextContent ?w FILTER regex(?w, '"+query_words+"', 'i') }"] output = subprocess.check_output(command, encoding='UTF-8') print('HALLO', output + '\n') if not 'g' in query_words_list[:-1]: pre_results = [i.split(', ') for i in output.splitlines() ][::-1][1:-1][:20] else: pre_results = [ i.split(', ') for i in output.splitlines()[1:-1] if query_words_list[-1].lower() in i ][::-1][:20] print("RES", pre_results) results = [[pre_results[i][0][2:], pre_results[i][1][7:]] for i in range(len(pre_results))] elif keyword == preferences["ts_kw"]: import re out1 = subprocess.check_output( ['tracker', 'search', query_words], encoding='UTF-8') out2 = [i for i in out1.splitlines()] out3 = [re.sub('\x1b[^m]*m', '', i).strip() for i in out2[1:]] pre_results = list(chunks(out3, 3))[:-1] print(pre_results) results = [[pre_results[i][1], pre_results[i][0][7:]] for i in range(len(pre_results))] elif keyword == preferences["lc_kw"]: words = query_words.split(' ') if len(words) == 1: output = subprocess.check_output( ['locate', '-l', '11', query_words], encoding='UTF-8') pre_results = output.splitlines() results = [[os.path.basename(i), i] for i in pre_results] elif preferences["autowildcardsearch"] == 'No': if len(words) == 3 and words[1] == 'g': loc = subprocess.Popen( ['locate', '-l', '100000', words[0]], stdout=subprocess.PIPE) #output = subprocess.run(['grep','-i', '-m','11', 'rey'], input=loc.stdout, capture_output=True) output = subprocess.check_output( ['grep', '-i', '-m', '11', words[2]], stdin=loc.stdout, encoding='UTF-8') pre_results = output.splitlines() results = [[os.path.basename(i), i] for i in pre_results] elif len(words ) == 5 and words[1] == 'g' and words[3] == 'g': loc = subprocess.Popen( ['locate', '-l', '100000', words[0]], stdout=subprocess.PIPE) #output = subprocess.run(['grep','-i', '-m','11', 'rey'], input=loc.stdout, capture_output=True) grep1 = subprocess.Popen(['grep', '-i', words[2]], stdin=loc.stdout, stdout=subprocess.PIPE) output = subprocess.check_output( ['grep', '-i', '-m', '11', words[4]], stdin=grep1.stdout, encoding='UTF-8') pre_results = output.splitlines() results = [[os.path.basename(i), i] for i in pre_results] # Do auto wildcard search if enabled in preferences else: output = subprocess.check_output([ 'locate', '-i', '-l', '11', "*" + "*".join(words) + "*" ], encoding='UTF-8') pre_results = output.splitlines() results = [[os.path.basename(i), i] for i in pre_results] items = [] for i in results: data = '%s' % i[1] print(data) items.append( ExtensionResultItem(icon='images/gnome.png', name='%s' % i[0], description="%s" % i[1], on_enter=ExtensionCustomAction( data, keep_app_open=True))) return RenderResultListAction(items)
def on_event(self, event, extension): subprocess.Popen("flameshot gui --delay 200", shell=True) return RenderResultListAction([])
def show_open_confirmation(self, number_of_links): confirmation = self._screens.render_open_confirmation(number_of_links) return RenderResultListAction(confirmation)