Esempio n. 1
0
def handleQuery(query):
    results = []
    if query.isTriggered:
        if len(query.string) > 2:
            pattern = re.compile(query.string, re.IGNORECASE)
            proc = subprocess.Popen([
                'locate', '-i' if query.trigger == "''" else "-bi",
                query.string
            ],
                                    stdout=subprocess.PIPE)
            for line in proc.stdout:
                path = line.decode().strip()
                basename = os.path.basename(path)
                results.append(
                    Item(id=path,
                         icon=iconPath,
                         text=pattern.sub(lambda m: "<u>%s</u>" % m.group(0),
                                          basename),
                         subtext=path,
                         completion="%s%s" % (__triggers__, basename),
                         actions=[UrlAction("Open", "file://%s" % path)]))
        else:
            results.append(
                Item(id=__title__,
                     icon=iconPath,
                     text="Update locate database",
                     subtext="Type at least three chars for a seach",
                     actions=[
                         TermAction("Update database", ["sudo", "updatedb"])
                     ]))

    return results
Esempio n. 2
0
def handleQuery(query):
    results = []
    if query.isTriggered:

        # avoid rate limiting
        sleep(0.2)
        if not query.isValid:
            return

        item = Item(id=__title__,
                    icon=iconPath,
                    text=__title__,
                    actions=[
                        ProcAction("Open the language configuration file.",
                                   commandline=[
                                       "xdg-open", language_configuration_file
                                   ])
                    ])
        if len(query.string) >= 2:
            for lang in languages:
                try:
                    url = urltmpl % (lang, urllib.parse.quote_plus(
                        query.string))
                    req = urllib.request.Request(url,
                                                 headers={'User-Agent': ua})
                    with urllib.request.urlopen(req) as response:
                        #print(type())
                        #try:
                        data = json.loads(response.read().decode())
                        #except TypeError as typerr:
                        #    print("Urgh this type.error. %s" % typerr)
                        translText = data[0][0][0]
                        sourceText = data[2]
                        if sourceText == lang:
                            continue
                        else:
                            results.append(
                                Item(id=__title__,
                                     icon=iconPath,
                                     text="%s" % (translText),
                                     subtext="%s" % lang.upper(),
                                     actions=[
                                         ClipAction(
                                             "Copy translation to clipboard",
                                             translText),
                                         UrlAction(
                                             "Open in your Browser",
                                             urlbrowser % (lang, query.string))
                                     ]))
                except urllib.error.URLError as urlerr:
                    print("Check your internet connection: %s" % urlerr)
                    item.subtext = "Check your internet connection."
                    return item
        else:
            item.subtext = "Enter a query: 'mtr &lt;text&gt;'. Languages {%s}" % ", ".join(
                languages)
            return item
    return results
Esempio n. 3
0
def handleQuery(query):
    if query.string.strip() and "trash".startswith(query.string.lower()):
        pattern = re.compile(query.string, re.IGNORECASE)
        return Item(id="trash-open",
                    icon=iconPath,
                    text=pattern.sub(lambda m: "<u>%s</u>" % m.group(0),
                                     "Trash"),
                    subtext="Show trash folder",
                    completion="trash",
                    actions=[UrlAction("Show", "trash:///")])
Esempio n. 4
0
def handleQuery(query):
    if query.isTriggered:
        fields = query.string.split()
        if len(fields) == 1:
            src = "de"
            dst = "en"
            txt = " ".join(fields)
        elif len(fields) >= 2:
            if fields[0] == ">":
                src = "de"
                dst = "en"
                txt = " ".join(fields[1:])
            elif fields[0] == "<":
                src = "en"
                dst = "de"
                txt = " ".join(fields[1:])
            else:
                src = fields[0]
                dst = fields[1]
                txt = " ".join(fields[2:])

                # If neither source nor destination are valid languages, assume that it is a standard case with
                # multiple words (cc kinder erziehen)
                if src not in AVAILABLE_LANGUAGES and dst not in AVAILABLE_LANGUAGES:
                    src = "de"
                    dst = "en"
                    txt = " ".join(fields)
                elif src not in ["de", "en"] and dst not in ["de", "en"]:
                    item = Item(id=__title__,
                                icon=iconPath,
                                completion=query.rawString)
                    item.text = "Unsupported language combination!"
                    item.subtext = "One language must be one of ['en', 'de']."
                    return item
                elif src not in AVAILABLE_LANGUAGES or dst not in AVAILABLE_LANGUAGES:
                    item = Item(id=__title__,
                                icon=iconPath,
                                completion=query.rawString)
                    item.text = "Unsupported language!"
                    item.subtext = "Source and destination language must be one of %s." % [
                        x for x in AVAILABLE_LANGUAGES.keys()
                    ]
                    return item
        else:
            item = Item(id=__title__,
                        icon=iconPath,
                        completion=query.rawString)
            item.text = __title__
            item.subtext = "Enter a query in the form of \"&lt;srclang&gt; &lt;dstlang&gt; &lt;text&gt;\""
            return item

        result = Dict.translate(txt, src, dst)
        items = []
        for input_word, output_word in result.translation_tuples:
            # critical(input_word + " | " + output_word)
            # Select correct value as translation
            # Dict.cc can only do <any language> <-> German or English
            # If src->dst are de->en or en->de, de is always the output
            # If src or dst is something else, it can vary, but we can detect that:
            #   * If src or dst is german, from or to is "Deutsch", the other one is the other language
            #   * If src or dst is english, form or to is "English", the other one is the other language
            if src == "de" and dst == "en":
                inp = output_word
                output = input_word
            elif src == "en" and dst == "de":
                inp = input_word
                output = output_word
            elif src == "de":
                inp, output = resolve(result.from_lang, result.to_lang,
                                      input_word, output_word, "Deutsch", True)
            elif dst == "de":
                inp, output = resolve(result.from_lang, result.to_lang,
                                      input_word, output_word, "Deutsch",
                                      False)
            elif src == "en":
                inp, output = resolve(result.from_lang, result.to_lang,
                                      input_word, output_word, "English", True)
            elif dst == "en":
                inp, output = resolve(result.from_lang, result.to_lang,
                                      input_word, output_word, "English",
                                      False)
            else:
                inp, output = error_text

            item = Item(id=__title__,
                        icon=iconPath,
                        completion=query.rawString)
            item.text = output
            item.subtext = "%s->%s translation of '%s'" % (src, dst, inp)
            item.addAction(ClipAction("Copy translation to clipboard", output))
            items.append(item)

        # If there where no results
        if len(items) == 0:
            item = Item(id=__title__,
                        icon=iconPath,
                        completion=query.rawString)
            item.text = "No results found!"
            items.append(item)
        else:
            # Add URL entry
            item = Item(id=__title__,
                        icon=iconPath,
                        completion=query.rawString)
            item.addAction(UrlAction("Open dict.cc", result.request_url))
            item.text = "Show all results (opens browser)"
            item.subtext = "Tip: You can scroll Alberts result list with your arrow keys to show more results."
            items.insert(0, item)

        return items
def handleQuery(query):
    if query.isTriggered:
        if not query.string.strip():
            return Item(
                id="%s-update" % __name__,
                icon=iconPath,
                text="Pacman package manager",
                subtext="Enter the package you are looking for or hit enter to update.",
                completion=__triggers__,
                actions=[
                    TermAction("Update the system (no confirm)", "sudo pacman -Syu --noconfirm"),
                    TermAction("Update the system", "sudo pacman -Syu")
                ]
            )

        time.sleep(0.1)
        if not query.isValid:
            return

        # Get data. Results are sorted so we can merge in O(n)
        proc_s = subprocess.Popen(["expac", "-Ss", "%n\t%v\t%r\t%d\t%u\t%E", query.string],
                                  stdout=subprocess.PIPE, universal_newlines=True)
        proc_q = subprocess.Popen(["expac", "-Qs", "%n", query.string], stdout=subprocess.PIPE, universal_newlines=True)
        proc_q.wait()

        items = []
        pattern = re.compile(query.string, re.IGNORECASE)
        local_pkgs = set(proc_q.stdout.read().split('\n'))
        remote_pkgs = [tuple(line.split('\t')) for line in proc_s.stdout.read().split('\n')[:-1]]  # newline at end

        for pkg_name, pkg_vers, pkg_repo, pkg_desc, pkg_purl, pkg_deps in remote_pkgs:
            if not pattern.search(pkg_name):
                continue

            pkg_installed = True if pkg_name in local_pkgs else False

            item = Item(
                id="%s:%s:%s" % (__name__, pkg_repo, pkg_name),
                icon=iconPath,
                text="%s <i>%s</i> [%s]"
                     % (pattern.sub(lambda m: "<u>%s</u>" % m.group(0), pkg_name), pkg_vers, pkg_repo),
                subtext=("<b>[Installed]</b> %s%s" if pkg_installed else "%s%s")
                        % (pkg_desc, (" <i>(%s)</i>" % pkg_deps) if pkg_deps else ""),
                completion="%s%s" % (query.trigger, pkg_name)
            )
            items.append(item)

            if pkg_installed:
                item.addAction(TermAction("Remove", "sudo pacman -Rs %s" % pkg_name))
                item.addAction(TermAction("Reinstall", "sudo pacman -S %s" % pkg_name))
            else:
                item.addAction(TermAction("Install", "sudo pacman -S %s" % pkg_name))
            item.addAction(UrlAction("Show on packages.archlinux.org", "https://www.archlinux.org/packages/%s/x86_64/%s/" % (pkg_repo, pkg_name)))
            if pkg_purl:
                item.addAction(UrlAction("Show project website", pkg_purl))

        if items:
            return items
        else:
            return Item(
                id="%s-empty" % __name__,
                icon=iconPath,
                text="Search on archlinux.org",
                subtext="No results found in the local database",
                actions=[
                    UrlAction("Search on archlinux.org",
                              "https://www.archlinux.org/packages/?q=%s" % query.string.strip())
                ]
            )

    elif len(query.string.strip()) > 0 and ("pacman".startswith(query.string.lower()) or "update".startswith(query.string.lower())):
        return Item(
            id="%s-update" % __name__,
            icon=iconPath,
            text="Update all packages on the system",
            subtext="Synchronizes the repository databases and updates the system's packages",
            actions=[
                TermAction("Update the system (no confirm)", "sudo pacman -Syu --noconfirm"),
                TermAction("Update the system", "sudo pacman -Syu")
            ]
        )
Esempio n. 6
0
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))
Esempio n. 7
0
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