コード例 #1
0
def read_history_file(hist_file='/home/jack/.dotfiles/clipster/history'):
    try:
        with open(hist_file) as hist_f:
            data = (json.load(hist_f))
        return data
    except FileNotFoundError as exc:
        Rofi.error("[!] Missing History File [!]")
        raise SystemExit(1)
コード例 #2
0
ファイル: rofi-skyss.py プロジェクト: torrottum/rofi-skyss
class RofiSkyss:
    def __init__(self):
        self.rofi = Rofi()

        cache_dir = os.path.expanduser('~/.cache/rofi-skyss')
        self.stop_groups_cache = os.path.join(cache_dir, 'stop_groups.json')

        self.api_url = 'https://api.skyss.no/ws/mobile'
        self.api_auth = ('mobile', 'g7pEtkRF@')

        # ensure that the cache dir exists
        os.makedirs(cache_dir, exist_ok=True)

    def call_api(self, endpoint):
        url = '{}/{}'.format(self.api_url, endpoint)
        response = requests.get(url, auth=self.api_auth)
        if response.status_code == 200:
            return response.json()
        else:
            return False

    def get_stop_groups(self):
        if os.path.exists(self.stop_groups_cache):
            with open(self.stop_groups_cache) as f:
                return json.load(f)
        else:
            self.rofi.status('Downloading list of stop groups ...')
            stop_groups = self.call_api('stopgroups')
            if not stop_groups:
                self.rofi.error('Failed to download stop groups, sorry :(')
                sys.exit(1)

            with open(self.stop_groups_cache, 'w') as f:
                json.dump(stop_groups, f)

            self.rofi.close()
            return stop_groups

    def get_stops(self, identifier):
        self.rofi.status('Getting stops and passing times')
        stop_group = self.call_api('stopgroups/' + identifier)
        if not stop_group:
            self.rofi.error('Failed to get stops and passing times, sorry :(')
            sys.exit(1)

        routes = []
        for group in stop_group['StopGroups']:
            for stop in group['Stops']:
                if 'RouteDirections' not in stop:
                    self.rofi.error(
                        'The stop group is missing routes, sorry :(')
                    sys.exit(1)
                for route in stop['RouteDirections']:
                    routes.append(route)

        if not routes:
            self.rofi.error('The stop group is missing routes, sorry :(')
            sys.exit(1)

        route_names = [
            '{} - {}'.format(route['PublicIdentifier'], route['DirectionName'])
            for route in routes
        ]
        index, status = self.rofi.select('Route: ', route_names)
        if status == 0:
            route = routes[index]
            times = [time['DisplayTime'] for time in route['PassingTimes']]
            self.rofi.select('Time: ',
                             times,
                             '<b>{}</b>'.format(route_names[index]),
                             width=len(route_names[index]) * -1)

    def run(self):
        stop_groups = self.get_stop_groups()['StopGroups']
        stop_group_names = [group['Description'] for group in stop_groups]
        index, status = self.rofi.select('Stop group: ', stop_group_names)
        if status == 0:
            stop_group = stop_groups[index]
            self.get_stops(stop_group['Identifier'])
コード例 #3
0
ファイル: rofi-skyss.py プロジェクト: Freheims/.dotfiles
class RofiSkyss:
    def __init__(self):
        self.rofi = Rofi()

        cache_dir = os.path.expanduser('~/.cache/rofi-skyss')
        self.stop_groups_cache = os.path.join(cache_dir, 'stop_groups.json')

        self.api_url = 'https://api.skyss.no/ws/mobile'
        self.api_auth = ('mobile', 'g7pEtkRF@')

        # ensure that the cache dir exists
        os.makedirs(cache_dir, exist_ok=True)


    def call_api(self, endpoint):
        url = '{}/{}'.format(self.api_url, endpoint)
        response = requests.get(url, auth=self.api_auth)
        if response.status_code == 200:
            return response.json()
        else:
            return False


    def get_stop_groups(self):
        if os.path.exists(self.stop_groups_cache):
            with open(self.stop_groups_cache) as f:
                return json.load(f)
        else:
            self.rofi.status('Downloading list of stop groups ...')
            stop_groups = self.call_api('stopgroups')
            if not stop_groups:
                self.rofi.error('Failed to download stop groups, sorry :(')
                sys.exit(1)

            with open(self.stop_groups_cache, 'w') as f:
                json.dump(stop_groups, f)

            self.rofi.close()
            return stop_groups


    def get_stops(self, identifier):
        self.rofi.status('Getting stops and passing times')
        stop_group = self.call_api('stopgroups/' + identifier)
        if not stop_group:
            self.rofi.error('Failed to get stops and passing times, sorry :(')
            sys.exit(1)

        routes = []
        for group in stop_group['StopGroups']:
            for stop in group['Stops']:
                if 'RouteDirections' not in stop:
                    self.rofi.error('The stop group is missing routes, sorry :(')
                    sys.exit(1)
                for route in stop['RouteDirections']:
                    routes.append(route)

        if not routes:
            self.rofi.error('The stop group is missing routes, sorry :(')
            sys.exit(1)

        route_names = ['{} - {}'.format(route['PublicIdentifier'], route['DirectionName']) for route in routes]
        index, status = self.rofi.select('Route: ', route_names)
        if status == 0:
            route = routes[index]
            times = [time['DisplayTime'] for time in route['PassingTimes']]
            self.rofi.select('Time: ', times, '<b>{}</b>'.format(route_names[index]), width=len(route_names[index]) * -1)


    def run(self):
        stop_groups = self.get_stop_groups()['StopGroups']
        stop_group_names = [group['Description'] for group in stop_groups]
        index, status = self.rofi.select('Stop group: ', stop_group_names)
        if status == 0:
            stop_group = stop_groups[index]
            self.get_stops(stop_group['Identifier'])
コード例 #4
0
ファイル: rofi-todo.py プロジェクト: Signifies/dots
r = Rofi()

while True:
    titles = []
    show_titles()

    index, key = r.select(
        "Notes",
        titles,
        key1=("Alt+d", "delete note"),
        key2=("Alt+a", "add note"),
        rofi_args=["-i", "-no-custom", "-l", "15"],
    )

    if key == 0:
        r.error(notes["notes"][index]["description"])

    elif key == 1:
        del notes["notes"][index]

        with open(args.file, "w") as f:
            json.dump(notes, f, indent=2)

        r.error("Note deleted.")

    elif key == 2:
        name = r.text_entry("Enter note name", rofi_args=["-l", "0"])

        if name:
            desc = r.text_entry("Enter node description",
                                rofi_args=["-l", "0"])
コード例 #5
0
ファイル: spotlight.py プロジェクト: legendofa/rofi-spotlight
class Spotlight:
    def __init__(self):
        self.rofi = Rofi()

    def multifuncitonal(self, argument):
        def reformat_whitespaces(self, search):
            search = search.split(" ")
            while "" in search:
                search.remove("")
            del search[0]
            return search

        try:
            argument
        except:
            search = self.rofi.text_entry("function")
        else:
            search = argument + " " + self.rofi.text_entry("function")

        selector = search[0]
        if selector == "w":
            search = reformat_whitespaces(self, search)
            search = " ".join(search)
            self.websearch(search)
        elif selector == "s":
            search = reformat_whitespaces(self, search)
            search = " ".join(search)
            print(search)
            self.search(search)
        elif selector == "e":
            self.exit()
        elif selector == "x":
            search = reformat_whitespaces(self, search)
            self.execute(search)
        else:
            self.rofi.error(
                'Not a valid command. Type "s" for search, "!" for websearch, "e" for exit or "x" for executing a command.'
            )

    def websearch(self, search):
        subprocess.Popen(["firefox", "-search", search],
                         stdout=subprocess.PIPE)

    def search(self, search):
        def find(self, pattern, path):
            result = []
            for root, dirs, files in os.walk(path):
                for name in files:
                    if fnmatch.fnmatch(name, pattern):
                        result.append(os.path.join(root, name))
            return result

        output = find(self, search, os.path.expanduser("~"))
        index, key = self.rofi.select("out", output)
        self.open(output[index])

    def open(self, file):
        subprocess.Popen(["xdg-open", file], stdout=subprocess.PIPE)

    def exit(self):
        options = [
            "lock", "exit", "suspend", "hibernate", "reboot", "shutdown"
        ]
        index, key = self.rofi.select("exit", options)
        command = ""
        if index == 0:
            command = "sh i3exit.sh lock"
        elif index == 1:
            command = "sh i3exit.sh logout"
        elif index == 2:
            command = "sh i3exit.sh suspend"
        elif index == 3:
            command = "sh i3exit.sh hibernate"
        elif index == 4:
            command = "sh i3exit.sh reboot"
        elif index == 5:
            command = "sh i3exit.sh poweroff"
        subprocess.Popen(command.split(" "), stdout=subprocess.PIPE)

    def execute(self, command):
        proc = subprocess.Popen(command, stdout=subprocess.PIPE)
        output, errors = proc.communicate()
        output = output.decode("utf-8").split("\n")
        self.rofi.select("out", output)
コード例 #6
0
ファイル: rofi-spotify.py プロジェクト: M3NIX/rofi-spotify
        "Callback URL (e.g. http://localhost:8080/callback): ")

    scopes = ('user-modify-playback-state', 'user-read-currently-playing',
              'user-read-playback-state', 'playlist-read-private',
              'playlist-read-collaborative')
    oauth2 = spotify.OAuth2(client_id, redirect_uri, scopes=scopes)

    # open the browser so the user can authorize to spotify and save the resulting tokens
    webbrowser.open(oauth2.url)
    url = input("Paste localhost url: ")
    parsed_url = urlparse(url)
    code = parsed_url.query.split('=')[1]
    authorize(redirect_uri, client_id, secret, "authorization_code", code)
elif args.set_default_device:  # when --set-default-device is present
    if 'auth' not in config:
        r.error('Please start the script in the command line with --setup')
        exit(0)
    client = spotify.Client(config['global']['client_id'],
                            config['global']['secret'])
    user = client.user_from_token(config['auth']['access_token'])
    devices = user.get_devices()
    options = []
    for d in devices:
        options.append(d.name)
    index, key = r.select('Spotify Device', options)

    if (key == 0):  # Enter
        device = devices[index]
        config["global"]['default_device'] = str(device)
        os.makedirs(os.path.dirname(config_file), exist_ok=True)
        with open(config_file, 'w') as conf: