def totp_show(name: str) -> str: try: return subprocess.check_output(["totp", "show", name]).decode("utf-8") except Exception: exc = f"Exception:\n\n{traceback.format_exc()}" v0.critical(exc) do_notify(f"Couldn't fetch the OTP code. {exc}") return ""
def handleQuery(query): pattern = query.string.strip().lower() results = [] try: for vm in vbox.machines: albert.critical(vm.name) if (pattern and pattern in vm.name.lower() or not pattern and query.isTriggered): results.append(buildVmItem(vm)) except Exception as e: critical(str(e)) return results
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string if len(query_str) < 2: results.extend([s.get_as_albert_item() for s in subcommands]) else: subcommand_query = get_subcommand_query(query_str) if subcommand_query: results.extend( subcommand_query.command.get_as_albert_items_full( subcommand_query.query)) except Exception: # user to report error if dev_mode: # let exceptions fly! v0.critical(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title_short__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def searchMovies(query): query_url = "http://www.omdbapi.com/?s={}&apikey=e389610c".format( query.string.strip()) try: res = http.request("GET", query_url) data = json.loads(res.data) except: critical("No Internet!") return [ Item( id=__prettyname__, icon=iconLookup("dialog-warning"), text="Is internet working?", subtext="We could not query, check your internet connection", completion=query.rawString, ) ] itemArr = [] if data["Response"] == "True": return [ Item( id=__prettyname__, icon=_get_icon("movie"), text="{}".format(mediaItem["Title"]), subtext= f"Type: {mediaItem['Type'].capitalize()}. Press tab for more info!", completion=__triggers__ + "id: " + mediaItem["imdbID"], ) for mediaItem in data["Search"] ] else: return Item( id=__prettyname__, icon=iconLookup("dialog-warning"), text="Too many results", subtext="Too many results returned, Please be specifics", completion=query.rawString, )
def logHtml(html): logTime = time.strftime("%Y%m%d-%H%M%S") logName = 'albert.plugins.youtube_dump' logPath = '/tmp/{}-{}.html'.format(logName, logTime) f = open(logPath, 'wb') f.write(html) f.close() critical("The HTML output has been dumped to {}.".format(logPath)) critical( "If the page looks ok in a browser, please include the dump in a new issue:" ) critical(" https://www.github.com/albertlauncher/albert/issues/new")
def handleQuery(query): results = [] # we're into the new day, create and assign a fresh instance last_used = last_used_date.get() current_date = datetime.datetime.today().date() global tw_side, subcommands if last_used < current_date: tw_side = TaskWarriorSideWLock() subcommands = create_subcommands() last_used_date.set(current_date) elif last_used > current_date: # maybe due to NTP? v0.critical( f"Current date {current_date} < last_used date {last_used} ?! Overriding current date, please report this if it persists" ) tw_side = TaskWarriorSideWLock() subcommands = create_subcommands() last_used_date.set(current_date) if not query.isTriggered: if show_items_wo_trigger and len(query.string) < 2: results = [ ActiveTasks().get_as_albert_item(), TodayTasks().get_as_albert_item(), *results, ] else: # join any previously launched threads for i in range(len(workers)): workers.pop(i).join(2) try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup tasks = tw_side.get_all_items(include_completed=False) query_str = query.string if len(query_str) < 2: results.extend([s.get_as_albert_item() for s in subcommands]) results.append( get_as_item( text="Reload list of tasks", actions=[v0.FuncAction("Reload", async_reload_items)], )) tasks.sort(key=lambda t: t["urgency"], reverse=True) results.extend([get_tw_item(task) for task in tasks]) else: subcommand_query = get_subcommand_query(query_str) if subcommand_query: results.extend( subcommand_query.command.get_as_albert_items_full( subcommand_query.query)) if not results: results.append(get_as_item(text="No results")) else: # find relevant results desc_to_task = { task["description"]: task for task in tasks } matched = process.extract(query_str, list(desc_to_task.keys()), limit=30) for m in [elem[0] for elem in matched]: task = desc_to_task[m] results.append(get_tw_item(task)) except Exception: # user to report error if dev_mode: v0.critical(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def movieInfo(mid): query_url = "http://www.omdbapi.com/?i={}&apikey=e389610c".format(mid) try: res = http.request("GET", query_url) data = json.loads(res.data) except: critical("No Internet!") return [ Item( id=__prettyname__, icon=iconLookup("dialog-warning"), text="Is internet working?", subtext="We could not query, check your internet connection", ) ] itemArr = [] if data["Response"] == "True": # Append movie name itemArr.append( Item( id=__prettyname__, icon=_get_icon("movie"), text=data["Title"], subtext="Title", )) # Append movie genre itemArr.append( Item( id=__prettyname__, icon=_get_icon("genre"), text=data["Genre"], subtext="Genre", )) # Append director itemArr.append( Item( id=__prettyname__, icon=_get_icon("director"), text=data["Director"], subtext="Director", )) # Append Actors itemArr.append( Item( id=__prettyname__, icon=_get_icon("actors"), text=data["Actors"], subtext="Actors", )) # Append Plot itemArr.append( Item( id=__prettyname__, icon=_get_icon("plot"), text=data["Plot"], subtext="Plot", )) # Append Awards itemArr.append( Item( id=__prettyname__, icon=_get_icon("awards"), text=data["Awards"], subtext="Awards", )) # Append Metascore itemArr.append( Item( id=__prettyname__, icon=_get_icon("metacritic"), text=data["Metascore"], subtext="Metascore", )) # Append imdbRating imdb_url = "https://www.imdb.com/title/" + mid itemArr.append( Item( id=__prettyname__, icon=_get_icon("imdb"), text=data["imdbRating"], subtext="IMDB Rating, Click to open on IMDB", actions=[UrlAction("Open article on Wikipedia", imdb_url)], )) # TODO : Append Rotten tomatoes rating # Open on IMDB return itemArr else: critical("No Internet!") return [ Item( id=__prettyname__, icon=iconLookup("dialog-warning"), text="Movie Not found", subtext="Movie does not exist in database", ) ] return Item(id=__prettyname__, icon=iconLookup("dialog-warning"), text=str(mid))
def handleQuery(query) -> list: """Hook that is called by albert with *every new keypress*.""" # noqa results = [] if query.isTriggered: try: query.disableSort() results_setup = setup(query) if results_setup: return results_setup query_str = query.string query_parts = query_str.split() if not query_parts: for template in all_templates: results.append(template.get_as_item()) return results meme_id = query_parts[0] if meme_id in id_to_template: captions = [ c.strip() for c in " ".join(query_parts[1:]).split("|") ] c1 = captions[0] c2 = captions[1] if len(captions) > 1 else "" results.insert( 0, id_to_template[meme_id].get_as_item_custom(caption1=c1, caption2=c2), ) else: title_to_templ = { template.title(): template for template in all_templates } # do fuzzy search - show relevant issues matched = process.extract(query.string.strip(), list(title_to_templ.keys()), limit=5) for m in [elem[0] for elem in matched]: results.append(title_to_templ[m].get_as_item()) except Exception: # user to report error if dev_mode: # let exceptions fly! v0.critical(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text= "Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ), ) return results
def handleQuery(query): if query.isTriggered and query.string.strip(): # avoid rate limiting time.sleep(0.2) if not query.isValid: return info("Searching YouTube for '{}'".format(query.string)) req = Request(headers=HEADERS, url='https://www.youtube.com/results?{}'.format( urlencode({'search_query': query.string.strip()}))) with urlopen(req) as response: responseBytes = response.read() match = re.search(DATA_REGEX, responseBytes.decode()) if match is None: critical( "Failed to receive expected data from YouTube. This likely means API changes, but could just be a failed request." ) logHtml(responseBytes) return results = json.loads(match.group(3)) results = results['contents']['twoColumnSearchResultsRenderer'][ 'primaryContents']['sectionListRenderer']['contents'][0][ 'itemSectionRenderer']['contents'] items = [] for result in results: for type, data in result.items(): try: if type == 'videoRenderer': subtext = ['Video'] action = 'Watch on Youtube' link = 'watch?v={}'.format(data['videoId']) if 'lengthText' in data: subtext.append(textFrom(data['lengthText'])) if 'shortViewCountText' in data: subtext.append( textFrom(data['shortViewCountText'])) if 'publishedTimeText' in data: subtext.append( textFrom(data['publishedTimeText'])) elif type == 'channelRenderer': subtext = ['Channel'] action = 'Show on Youtube' link = 'channel/{}'.format(data['channelId']) if 'videoCountText' in data: subtext.append(textFrom( data['videoCountText'])) if 'subscriberCountText' in data: subtext.append( textFrom(data['subscriberCountText'])) else: continue except Exception as e: critical(e) critical(json.dumps(result, indent=4)) item = Item( id=__title__, icon=data['thumbnail']['thumbnails'][0]['url'].split( '?', 1)[0] if data['thumbnail']['thumbnails'] else __icon__, text=textFrom(data['title']), subtext=' | '.join(subtext), actions=[ UrlAction(action, 'https://www.youtube.com/' + link) ]) items.append(item) return items
if len(query_str) < 2: keys_monitor.reset() return results keys_monitor.report() if keys_monitor.triggered(): # modify this... results.append(get_as_item()) {%- else %} # modify this... results.append(get_as_item()) {%- endif %} except Exception: # user to report error if dev_mode: # let exceptions fly! v0.critical(traceback.format_exc()) raise results.insert( 0, v0.Item( id=__title__, icon=icon_path, text="Something went wrong! Press [ENTER] to copy error and report it", actions=[ v0.ClipAction( f"Copy error - report it to {__homepage__[8:]}", f"{traceback.format_exc()}", ) ], ),