Esempio n. 1
0
def createItems(windows, spans=None):
    results = []
    # print('spans: ', spans)
    # [print(w.wm_name) for w in windows]
    # print(len(windows))
    for win in windows:
        if spans:
            text_subtext = highlightText(win, spans[win.wid])
        else:
            text_subtext = {
                'text':
                '%s: %s' %
                (win.desktop, win.wm_class.split('.')[-1].replace('-', ' ')),
                'subtext':
                '%s➜%s' % (win.wm_class.split('.')[-1], win.wm_name)
            }

        win_instance, win_class = win.wm_class.replace(' ', '-').split('.')
        iconPath = iconLookup(win_instance) or iconLookup(win_class.lower())
        results.append(
            Item(id="%s%s" % (__title__, win.wm_class),
                 **text_subtext,
                 icon=iconPath,
                 actions=[
                     ProcAction(text="Switch Window",
                                commandline=["wmctrl", '-i', '-a', win.wid]),
                     ProcAction(text="Move window to this desktop",
                                commandline=["wmctrl", '-i', '-R', win.wid]),
                     ProcAction(text="Close the window gracefully.",
                                commandline=["wmctrl", '-c', win.wid])
                 ]))

    return results
Esempio n. 2
0
def handleQuery(query):
    stripped = query.string.strip().lower()
    if stripped:
        results = []
        for line in subprocess.check_output(['wmctrl', '-lG',
                                             '-x']).splitlines():
            try:
                win = Window(*parseWindow(line))

                if win.desktop == "-1":
                    continue

                win_instance, win_class = win.wm_class.replace(' ',
                                                               '-').split('.')
                matches = [
                    win_instance.lower(),
                    win_class.lower(),
                    win.wm_name.lower()
                ]

                if any(stripped in match for match in matches):
                    iconPath = iconLookup(win_instance) or iconLookup(
                        win_class.lower())
                    results.append(
                        Item(id="%s%s" % (__title__, win.wm_class),
                             icon=iconPath,
                             text="%s  - <i>Display %s</i>" %
                             (win_class.replace('-', ' '), win.display),
                             subtext=win.wm_name,
                             actions=[
                                 ProcAction("Switch Window",
                                            ["wmctrl", '-i', '-a', win.wid]),
                                 ProcAction("Move window to this desktop",
                                            ["wmctrl", '-i', '-R', win.wid]),
                                 ProcAction("Close the window gracefully.",
                                            ["wmctrl", '-c', win.wid])
                             ]))
            except:
                continue

        return results
Esempio n. 3
0
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,
        )
Esempio n. 4
0
def handleAdd(query):
    actions = []
    onehour = datetime.datetime.now() + datetime.timedelta(hours=1)
    tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
    tomorrow.replace(hour=9, minute=0, second=0)  # always 9 AM
    nextweek = datetime.datetime.now() + datetime.timedelta(days=7)
    nextweek.replace(hour=9, minute=0, second=0)  # always 9 AM
    for name in connections.config.sections():
        actions.append(
            FuncAction(text=f"Create todo in {name}",
                       callable=lambda: connections.createTodo(
                           name, query.string))
        )
        actions.append(
            FuncAction(text=f"Create todo in {name} for in one hour",
                       callable=lambda: connections.createTodo(
                           name, query.string, onehour))
        )
        actions.append(
            FuncAction(text=f"Create todo in {name} for tomorrow",
                       callable=lambda: connections.createTodo(
                           name, query.string, tomorrow))
        )
        actions.append(
            FuncAction(text=f"Create todo in {name} for next week",
                       callable=lambda: connections.createTodo(
                           name, query.string, nextweek))
        )

    return Item(
        id=f"newtodo-{query.string}",
        text=query.string,
        subtext="Create a new todo",
        icon=iconLookup("add"),
        actions=actions
    )
Esempio n. 5
0
from pathlib import Path
from typing import Tuple

from fuzzywuzzy import process

import albert as v0

__title__ = "GMaps - Launch route planner"
__version__ = "0.4.0"
__triggers__ = "gmaps "
__authors__ = "Nikos Koukis"
__homepage__ = (
    "https://github.com/bergercookie/awesome-albert-plugins/blob/master/plugins//gmaps"
)

icon_path = v0.iconLookup("gmaps")
if not icon_path:
    icon_path = os.path.join(os.path.dirname(__file__), "gmaps")

cache_path = Path(v0.cacheLocation()) / "gmaps"
config_path = Path(v0.configLocation()) / "gmaps"
data_path = Path(v0.dataLocation()) / "gmaps"
gmaps_exe = Path(__file__).parent / "gmaps-cli" / "gmaps-cli.py"

available_means = ["walk", "drive", "bicycle", "fly", "transit"]
default_means = "transit"

# plugin main functions -----------------------------------------------------------------------


def initialize():
Esempio n. 6
0
    info,

    configLocation,

    ProcAction, ClipAction, FuncAction
)
import os
import configparser
import subprocess

import caldav
import vobject

import datetime

unresolved_todo = iconLookup("appointment-new")
resolved_todo = iconLookup("answer-correct")

__title__ = "TODOs"
__version__ = "0.4.0"
__triggers__ = ["t ", "ta "]
__authors__ = "Stijn Van Campenhout <*****@*****.**>"
__py_deps = ["vobject", "caldav"]
__exec_deps__ = ["xdg-open"]

helpText = """
# Please edit this file with your calendars you want to manage the todos for.
# With each calendar in a section.
#
# For example:
# [Work]
Synopsis: <trigger> [filter]"""

import re
import subprocess
import time

from albert import TermAction, iconLookup, Item, UrlAction

__title__ = "PacMan"
__version__ = "0.4.4"
__triggers__ = "pacman "
__authors__ = ["Manuel Schneider", "Benedict Dudel"]
__exec_deps__ = ["pacman", "expac"]

iconPath = iconLookup(["archlinux-logo", "system-software-install"])


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")
                ]
Esempio n. 8
0
import json
import os
import urllib.error
import urllib.parse
import urllib.request
from time import sleep

from albert import (ClipAction, Item, ProcAction, UrlAction, configLocation,
                    iconLookup)

__title__ = "MultiTranslate"
__version__ = "0.4.2"
__triggers__ = "mtr "
__authors__ = "David Britt"

iconPath = iconLookup('config-language')
if not iconPath:
    iconPath = ":python_module"

ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"
urltmpl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=%s&dt=t&q=%s"
urlbrowser = "https://translate.google.com/#auto/%s/%s"
configurationFileName = "language_config.json"
configuration_directory = os.path.join(configLocation(), __title__)
language_configuration_file = os.path.join(configuration_directory,
                                           configurationFileName)
languages = []


def initialize():
    if os.path.exists(language_configuration_file):
Esempio n. 9
0
where ' searches basenames and '' searches the full path  """

import os
import re
import subprocess

from albert import Item, TermAction, UrlAction, iconLookup

__title__ = "Locate"
__version__ = "0.4.1"
__triggers__ = ["''", "'"]  # Order matters since 2 is prefix of 1
__authors__ = "manuelschneid3r"
__exec_deps__ = ['locate']

iconPath = iconLookup(
    ["preferences-system-search", "system-search"
     "search", "text-x-generic"])


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()
Esempio n. 10
0
                                VBoxErrorHostError,
                                VBoxErrorInvalidObjectState,
                                VBoxErrorInvalidVmState, VBoxErrorIprtError,
                                VBoxErrorObjectNotFound)

from albert import FuncAction, Item, critical, iconLookup

__title__ = "Virtual Box"
__version__ = "0.4.2"
__triggers__ = "vbox "
__authors__ = "manuelschneid3r"
__py_deps__ = ['virtualbox']

vbox = None

iconPath = iconLookup(["virtualbox", "unknown"])


def initialize():
    global vbox
    vbox = VirtualBox()


def finalize():
    pass


def startVm(vm):
    try:
        with Session() as session:
            vm.launch_vm_process(session, 'gui', '')
Esempio n. 11
0
# -*- coding: utf-8 -*-
"""Fire up an external search in GoldenDict.

Synopsis: <trigger> <query>"""

from subprocess import run
from albert import Item, ProcAction, iconLookup

__title__ = "GoldenDict"
__version__ = "0.4.0"
__triggers__ = "gd "
__authors__ = "manuelschneid3r"
__exec_deps__ = ["goldendict"]

iconPath = iconLookup('goldendict')


def handleQuery(query):
    if query.isTriggered:
        return Item(id=__title__,
                    icon=iconPath,
                    text=__title__,
                    subtext="Look up '%s' using %s" %
                    (query.string, __title__),
                    actions=[
                        ProcAction("Start query in %s" % __title__,
                                   ["goldendict", query.string])
                    ])
Esempio n. 12
0
import os
import traceback
from pathlib import Path

import zoopla as z

import albert as v0

__title__ = "Zoopla - Search Properties"
__version__ = "0.4.0"
__triggers__ = "z "
__authors__ = "Nikos Koukis"
__homepage__ = "https://github.com/bergercookie/zoopla-albert-plugin"

iconPath = v0.iconLookup("zoopla")
if not iconPath:
    iconPath = os.path.join(os.path.dirname(__file__), "zoopla")
settings_path = Path(v0.cacheLocation()) / "zoopla"

api_key = "sn2dtcnvekktbjbv8ays8e33"
zoopla = z.Zoopla(api_key=api_key)

str_to_key = {"sale": "listing_status", "rent": "listing_status"}

str_to_actual_name = {"sale": "sale", "rent": "rent"}


def initialize():
    # Called when the extension is loaded (ticked in the settings) - blocking
Esempio n. 13
0
Unix 'kill' wrapper extension.

Synopsis: <trigger> <filter>"""

import os
from signal import SIGKILL, SIGTERM

from albert import FuncAction, Item, iconLookup

__title__ = "Kill Process"
__version__ = "0.4.4"
__triggers__ = "kill "
__authors__ = ["Benedict Dudel", "manuelschneid3r"]

iconPath = iconLookup('process-stop')


def handleQuery(query):
    if query.isTriggered:
        results = []
        uid = os.getuid()
        for dir_entry in os.scandir('/proc'):
            try:
                if dir_entry.name.isdigit() and dir_entry.stat().st_uid == uid:
                    proc_command = open(os.path.join(dir_entry.path, 'comm'),
                                        'r').read().strip()
                    if query.string in proc_command:
                        proc_cmdline = open(
                            os.path.join(dir_entry.path, 'cmdline'),
                            'r').read().strip().replace("\0", " ")
Esempio n. 14
0
Synopsis: <trigger> <query>"""

import json
import re
import time
from os import path
from urllib.parse import urlencode
from urllib.request import Request, urlopen

from albert import Item, UrlAction, iconLookup, critical, debug, info

__title__ = 'Youtube'
__version__ = '0.4.1'
__triggers__ = 'yt '
__authors__ = 'manuelschneid3r'
__icon__ = iconLookup(
    'youtube')  # path.dirname(__file__) + '/icons/YouTube.png'

DATA_REGEX = re.compile(
    r'^\s*(var\s|window\[")ytInitialData("\])?\s*=\s*(.*)\s*;\s*$',
    re.MULTILINE)

HEADERS = {
    'User-Agent':
    ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'
     ' Chrome/62.0.3202.62 Safari/537.36')
}


def handleQuery(query):
    if query.isTriggered and query.string.strip():
Esempio n. 15
0
Synopsis: <trigger>"""

import os
import subprocess
import tempfile
from shutil import which

from albert import FuncAction, Item, iconLookup

__title__ = "SCReenshOT utility"
__version__ = "0.4.0"
__triggers__ = "scrot "
__authors__ = "Benedict Dudel"
__exec_deps__ = ["scrot", "xclip"]

iconPath = iconLookup("camera-photo")


def handleQuery(query):
    if query.isTriggered:
        return [
            Item(id="%s-whole-screen" % __title__,
                 icon=iconPath,
                 text="Screen",
                 subtext="Take a screenshot of the whole screen",
                 actions=[
                     FuncAction("Take screenshot of whole screen",
                                lambda: doScreenshot([])),
                     FuncAction("Take screenshot of multiple displays",
                                lambda: doScreenshot(["--multidisp"])),
                 ]),
Esempio n. 16
0
# -*- coding: utf-8 -*-
"""Open virtual trash location.

This extension provides a single item which opens the systems virtual trash \
location in your default file manager.

Synopsis: <trigger>"""

import re

from albert import Item, UrlAction, iconLookup

__title__ = "Trash"
__version__ = "0.4.0"
__authors__ = "manuelschneid3r"
iconPath = iconLookup("user-trash-full")


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. 17
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. 18
0
"""Evaluate Mathematica expressions.

Synopsis: <trigger> [expr]"""

import subprocess
from tempfile import NamedTemporaryFile

from albert import ClipAction, Item, iconLookup

__title__ = 'Mathematica eval'
__version__ = '0.4.0'
__triggers__ = 'mma '
__authors__ = 'Asger Hautop Drewsen'
__exec_deps__ = ['wolframscript']

ICON_PATH = iconLookup('wolfram-mathematica')

def handleQuery(query):
    if not query.isTriggered:
        return

    item = Item(icon=ICON_PATH)
    stripped = query.string.strip()

    if stripped:
        with NamedTemporaryFile() as f:
            f.write(bytes(stripped, 'utf-8'))
            f.flush()
            output = subprocess.check_output(['wolframscript', '-print', '-f', f.name])
        result = str(output.strip(), 'utf-8')
        item.text = result
Esempio n. 19
0
# -*- coding: utf-8 -*-
"""Search the NASA ADS API

Synopsis: <trigger> <query>"""

import albert
import os
import re
import shlex

__title__ = "NASA ADS"
__version__ = "0.4.0"
__triggers__ = "ads "
__authors__ = ["Dan Foreman-Mackey"]

icon_path = albert.iconLookup("adsabs")
if not icon_path:
    icon_path = os.path.dirname(__file__) + "/adsabs.svg"


def parse_query_string(query):
    # Remove parentheses
    query = query.replace("(", " ").replace(")", " ")

    # Tokenize the query
    tokens = shlex.split(query)
    years = []
    authors = []
    for token in tokens:
        token = token.strip()
        numbers = re.findall("[0-9]+", token)