Exemplo n.º 1
0
 def copy_note(self, path: str) -> BaseAction:  # pylint: disable=no-self-use
     """
     Copy the contents of note file into the clipboard
     """
     with open(path, "rt") as f:
         text = os.linesep.join(f.readlines())
     return CopyToClipboardAction(text)
Exemplo n.º 2
0
    def on_event(self, event, extension):
        items = []

        if (event.get_argument() is not None):
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=event.get_argument(),
                    description="Press enter to open on mailinator.com",
                    on_enter=OpenUrlAction('{}{}'.format(
                        MAILINATOR_URL, event.get_argument()))))
        else:
            email = '{}{}{}'.format(extension.preferences.get("prefix"),
                                    fake.user_name(),
                                    str(random.randint(1000, 9999)))

            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='{}@mailinator.com'.format(email),
                    description=
                    "Press enter to copy to the cliboard. Alt+Enter to open",
                    highlightable=False,
                    on_enter=CopyToClipboardAction(email),
                    on_alt_enter=OpenUrlAction('{}{}'.format(
                        MAILINATOR_URL, email))))

        return RenderResultListAction(items)
Exemplo n.º 3
0
def generate_local_item(name, ip, description):
    text = f'{name} - {ip}'

    return ExtensionResultItem(icon=ICON_IMAGE,
                               name=text,
                               description=description,
                               on_enter=CopyToClipboardAction(text))
Exemplo n.º 4
0
    def searchBoxes(self, search_str):
        results = []
        pattern = re.compile(re.escape("[") + "display")

        config_lines = []
        qemu_path = self.preferences.get("gbox_sessions_path")
        with open(expanduser(qemu_path)) as boxesFile:
            config_lines = boxesFile.readlines()

        config_blocks = []
        for i, line in enumerate(config_lines):
            for match in re.finditer(pattern, line):
                config_blocks.append(self.get_config_block(config_lines, i))

        for block in config_blocks:
            if search_str == "Start typing..." \
                    or block["last-seen-name"].__contains__(search_str) \
                    or block["uuid"].__contains__(search_str):
                last_access = datetime.fromtimestamp(int(block["access-last-time"]) / 1000000)
                results.append(
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name=block["last-seen-name"],
                        description="UUID: " + block["uuid"] +
                                    "\n" + block["access-ntimes"] + " access, last " + last_access.__str__(),
                        on_enter=RunScriptAction(
                            'gnome-boxes --open-uuid %s &' % block["uuid"],
                            []
                        ),
                        on_alt_enter=CopyToClipboardAction(block["uuid"])
                    )
                )

        return results
Exemplo n.º 5
0
    def search_tabs(self, event):
        """ Search tabs """

        if not self.brotab_client.is_installed():
            return RenderResultListAction([
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Brotab is not installed on your system",
                    description="Press enter to open install instructions.",
                    highlightable=False,
                    on_enter=OpenUrlAction("https://github.com/balta2ar/brotab#installation"),
                )
            ])

        items = []
        tabs = self.brotab_client.search_tabs(event.get_argument())

        for tab in tabs[:DISPLAY_MAX_RESULTS]:
            data = {"tab": tab["prefix"], "mode": self.mode}

            items.append(
                ExtensionSmallResultItem(
                    icon="images/%s" % tab["icon"],
                    name=tab["name"],
                    description=tab["url"],
                    on_enter=ExtensionCustomAction(data),
                    on_alt_enter=CopyToClipboardAction(tab["url"]),
                ))

        if not items:
            return self.show_no_results_message()

        return RenderResultListAction(items)
Exemplo n.º 6
0
    def on_event(self, event, extension):
        """ Handles event """
        items = []

        if event.get_argument():
            pw_length = int(event.get_argument())
        else:
            pw_length = int(extension.preferences['pw_length'])

        pw_count = int(extension.preferences['pw_count'])

        passwords = self.generatePasswords(
            pw_length,
            pw_count,
        )

        for password in passwords:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=str(password),
                    description='Press Enter to copy this password to clipboard',
                    highlightable=False,
                    on_enter=CopyToClipboardAction(str(password))
                )
            )

        return RenderResultListAction(items)
Exemplo n.º 7
0
    def execute(self):
        _LOGGER_.debug("Executing GetAction")
        items = []
        exists = 0
        for row in self.db.execute_statement(
                "SELECT key, value, tags from KV where key like '%{}%' or tags like '%{}%'".format(self.text,
                                                                                                   self.text)):
            exists = 1
            key = row[0]
            value = row[1]
            value_fix = value.strip().replace('$', '\$').replace('"', '\\"').replace('`', '\\`') + '\n'
            script_action = 'sleep 0.01m && echo -n "' + value_fix + \
                            '" | xclip -i -selection clipboard && sleep 0.01m && xdotool key --clearmodifiers ctrl+v &'
            item = ExtensionResultItem(
                icon=ICON,
                name="{} = {}".format(key, value.replace('&', '&')),
                description="Press enter or click to copy '{}' to clipboard or type 'unset' to unset from db".format(
                    value),
                on_alt_enter=RunScriptAction(script_action, []),
                on_enter=CopyToClipboardAction(value))
            items.append(item)

        if not exists:
            item = ExtensionResultItem(icon=ICON, name=NAME)
            if self.text == "":
                item._description = "It looks like you have nothing stored"
            else:
                item._description = "No VALUE for KEY: '{}'".format(self.text)
            items.append(item)

        return items
Exemplo n.º 8
0
    def user_gists(self, query):
        """ List user gists"""

        query = query.lower()
        gists = []
        with open(self.gists_cache_file) as cache_file:
            gists = json.load(cache_file)

        items = []
        for gist in gists:

            desc = gist['description'] or ""

            if query and (query not in desc.lower(
            ) and query not in gist['filename'].lower()):
                continue

            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=gist['filename'],
                                    description=desc,
                                    highlightable=not query,
                                    on_enter=OpenUrlAction(gist['url']),
                                    on_alt_enter=CopyToClipboardAction(
                                        gist['url'])))

        return RenderResultListAction(items[:8])
Exemplo n.º 9
0
    def on_event(self, event, extension):
        """ Handles the event """
        items = []
        keyword = event.get_keyword()
        query = event.get_argument() or ""
        file_path = extension.get_recent_projects_file_path(keyword)

        projects = RecentProjectsParser.parse(file_path, query)

        if not projects:
            return RenderResultListAction([
                ExtensionResultItem(icon=extension.get_icon(keyword),
                                    name='No projects found',
                                    on_enter=HideWindowAction())
            ])
        for project in projects:
            items.append(
                ExtensionResultItem(
                    icon=project['icon'] if project['icon'] is not None else
                    extension.get_icon(keyword),
                    name=project['name'],
                    description=project['path'],
                    on_enter=RunScriptAction(
                        '%s "%s" &' % (extension.get_launcher_file(keyword),
                                       project['path']), []),
                    on_alt_enter=CopyToClipboardAction(project['path'])))
        return RenderResultListAction(items)
Exemplo n.º 10
0
    def search_users(self, query):
        """ Search GitHub users """

        if not query or len(query) < 3:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Please keep typing your search query',
                    description='Minimum 3 chars',
                    highlightable=False,
                    on_enter=HideWindowAction())
            ])

        users = self.github.search_users(query=query,
                                         sort="followers",
                                         order="desc")[:8]

        items = []

        for user in users:
            items.append(
                ExtensionResultItem(icon='images/icon.png',
                                    name=user.name,
                                    on_enter=OpenUrlAction(user.html_url),
                                    on_alt_enter=CopyToClipboardAction(
                                        user.html_url)))

        return RenderResultListAction(items)
Exemplo n.º 11
0
    def search_public_repos(self, query):
        """ Search public repos """

        if not query or len(query) < 3:
            return RenderResultListAction([
                ExtensionResultItem(
                    icon='images/icon.png',
                    name='Please keep typing your search query',
                    description='Minimum 3 chars',
                    highlightable=False,
                    on_enter=HideWindowAction())
            ])

        repos = self.github.search_repositories(query=query)[:8]

        items = []

        for repo in repos:
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name="%s (%s stars)" %
                    (repo.name, repo.stargazers_count),
                    description=repo.description,
                    on_enter=OpenUrlAction(repo.html_url),
                    on_alt_enter=CopyToClipboardAction(repo.html_url)))

        return RenderResultListAction(items)
Exemplo n.º 12
0
    def execute(self):
        _LOGGER_.debug("Executing GetAction")
        items = []
        exists = 0
        for row in self.db.execute_statement(
                "SELECT key, value from KV where key like '%{}%'".format(
                    self.text)):
            exists = 1
            key = row[0]
            value = row[1]
            item = ExtensionResultItem(
                icon=ICON,
                name="{} = {}".format(key, value),
                description=
                "Press enter or click to copy '{}' to clipboard or type 'unset' to unset from db"
                .format(value),
                on_enter=CopyToClipboardAction(value))
            items.append(item)

        if not exists:
            item = ExtensionResultItem(icon=ICON, name=NAME)
            if self.text == "":
                item._description = "It looks like you have nothing stored"
            else:
                item._description = "No VALUE for KEY: '{}'".format(self.text)
            items.append(item)

        return items
Exemplo n.º 13
0
    def get_action(self, key_filter):
        connection = sqlite3.connect(_db_)
        items = []
        exists = 0
        statement = "SELECT key, value from KV where key like '%{}%'".format(key_filter)
        for row in connection.execute(statement):
            exists = 1
            key = row[0]
            value = row[1]
            item = ExtensionResultItem(
                icon=_icon_, 
                name="{} = {}".format(key, value),
                description="Press enter or click to copy '{}' to clipboard or type 'unset' to unset from db".format(value),
                on_enter=CopyToClipboardAction(value))
            items.append(item)

        if not exists:
            item = ExtensionResultItem(icon=_icon_, name=_name_)
            if key_filter == "":
                item._description = "It looks like you have nothing stored"
            else:
                item._description = "No VALUE for KEY: '{}'".format(key_filter)
            items.append(item)

        return items
Exemplo n.º 14
0
 def on_event(self, event, extension):
     tmpSymbols = []
     tmpKey = event.get_argument()
     if tmpKey == None:
         return RenderResultListAction([
             ExtensionResultItem(
                 icon='images/icon.png',
                 name='Please specify the desired symbol set',
                 on_enter=DoNothingAction())
         ])
     elif tmpKey.upper() in mySymbols:
         for tmpMatch in mySymbols[tmpKey.upper()]:
             tmpSymbols.append(
                 ExtensionResultItem(
                     icon='images/icon.png',
                     name=tmpMatch,
                     description='Copy ' + tmpMatch + ' to clipboard',
                     on_enter=CopyToClipboardAction(tmpMatch)))
         return RenderResultListAction(tmpSymbols)
     else:
         return RenderResultListAction([
             ExtensionResultItem(icon='images/icon.png',
                                 name='Unknown code...',
                                 on_enter=DoNothingAction())
         ])
Exemplo n.º 15
0
    def on_event(self, event, extension):
        query = event.get_argument() or str()

        if len(query.strip()) == 0:
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name='No input',
                                    on_enter=HideWindowAction())
            ])

        if len(query) > 3 and ":" in query[0]:
            from_language = "auto"
            to_language = query[1:3]
            query = query[3:]
        elif len(query) > 5 and ":" in query[2]:
            from_language = query[:2]
            to_language = query[3:5]
            query = query[5:]
        else:
            from_language = extension.preferences["otherlang"]
            to_language = extension.preferences["mainlang"]
        ceviri = translate(query, to_language, from_language,
                           extension.preferences["wrap"])
        items = [
            ExtensionResultItem(icon='images/icon.png',
                                name=query.replace("\n", ""),
                                description=translate(
                                    query, to_language, from_language,
                                    extension.preferences["wrap"]),
                                on_enter=CopyToClipboardAction(ceviri))
        ]

        return RenderResultListAction(items)
Exemplo n.º 16
0
    def on_event(self, event, extension):
        arg = event.get_argument()
        items = []

        if arg is None:
            items = self.__help()
        else:
            try:
                results = locator.run(arg)
                alt_action = ExtensionCustomAction(results, True)
                for file in results:
                    items.append(
                        ExtensionSmallResultItem(icon='images/ok.png',
                                                 name=str(file, 'utf-8'),
                                                 on_enter=OpenAction(file),
                                                 on_alt_enter=alt_action))
            except Exception as e:
                error_info = str(e)
                items = [
                    ExtensionSmallResultItem(
                        icon='images/error.png',
                        name=error_info,
                        on_enter=CopyToClipboardAction(error_info))
                ]

        return RenderResultListAction(items)
Exemplo n.º 17
0
    def on_event(self, event, extension):
        """ Handles Keyword Event """
        items = []

        try:

            query = event.get_argument() or ""

            if len(query) < 3:
                return RenderResultListAction([
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name="Keep Typing to search on cdn.js ...",
                        on_enter=HideWindowAction(),
                        highlightable=False,
                    )
                ])

            max_results = int(extension.preferences['max_results'])
            payload = {
                'search': query,
                'fields': 'version,description,repository'.encode('utf-8')
            }

            headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'Ulauncher-cdnjs/2.0'
            }

            req = requests.get(CDN_URL, params=payload, headers=headers)
            req.raise_for_status()

            libraries = req.json()

            for library in libraries['results'][0:max_results]:
                repo_url = library['repository']['url'].replace(
                    'git://', 'https://').replace('git+', '')
                items.append(
                    ExtensionResultItem(
                        icon='images/icon.png',
                        name=library['name'] + " (" + library['version'] + ")",
                        description=library['description'],
                        on_enter=CopyToClipboardAction(library['latest']),
                        on_alt_enter=OpenUrlAction(repo_url)))

            return RenderResultListAction(items)

        except requests.exceptions.HTTPError as err:
            LOGGER.error(err)
            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name="Error requesting CDNjs",
                    description="Request error: " + str(req.status_code),
                    on_enter=HideWindowAction(),
                    highlightable=False,
                ))

            return RenderResultListAction(items)
Exemplo n.º 18
0
def generate_items(gen_name, results):
    return [
        ExtensionResultItem(icon=generate_icon(gen_name),
                            name=result['name'],
                            description=result['description'],
                            on_enter=CopyToClipboardAction(result['copy']))
        for result in results
    ]
Exemplo n.º 19
0
def show_hosts_items():
    return [
        ExtensionResultItem(icon='images/icon.png',
                            name=host,
                            description=ip,
                            on_enter=CopyToClipboardAction(ip))
        for (host, ip) in get_hosts().items()
    ]
Exemplo n.º 20
0
    def on_event(self, event, extension):
        data = event.get_data()
        type = data.get("type")

        if type == "select":
            extension.snippet = data.get("snippet")
            extension.state = "var"
        elif type == "cancel":
            extension.reset()
            return SetUserQueryAction("")

        next_variable = extension.snippet.next_variable()
        if extension.state == "var" and next_variable:
            keyword = extension.preferences["snippets_keyword"]
            extension.variable = next_variable
            return ActionList([
                SetUserQueryAction(keyword + " "),
                RenderResultListAction(
                    show_var_input(extension.snippet, next_variable,
                                   next_variable.get("default", "")))
            ])

        try:
            copy_mode = extension.preferences["snippets_copy_mode"]
            if extension.snippet.file_path_template:
                try:
                    file_path = extension.snippet.render_to_file_path(
                        copy_mode=copy_mode)
                    self._notify(extension,
                                 file_path,
                                 title="Snippet written to file")
                except FileExistsError as e:
                    self._notify(extension,
                                 e.args[0],
                                 title="File already exists")
                return HideWindowAction()
            else:
                (mimetype,
                 snippet) = extension.snippet.render(copy_mode=copy_mode)

                action = None
                if copy_mode == "xsel":
                    copy_to_clipboard_xsel(snippet, mimetype)
                    action = HideWindowAction()
                elif copy_mode == "wl":
                    copy_to_clipboard_wl(snippet, mimetype)
                    action = HideWindowAction()
                else:
                    action = CopyToClipboardAction(snippet)

                self._notify(extension, snippet, mimetype)
                return action
        except Exception as e:
            logger.exception(e)
            return RenderResultListAction(
                [ExtensionResultItem(name=str(e), on_enter=DoNothingAction())])
        finally:
            extension.reset()
Exemplo n.º 21
0
    def on_event(self, event, extension):
        items = []

        md5Hash = hashlib.md5(event.get_argument()).hexdigest()
        sha1Hash = hashlib.sha1(event.get_argument()).hexdigest()
        sha224Hash = hashlib.sha224(event.get_argument()).hexdigest()
        sha256Hash = hashlib.sha256(event.get_argument()).hexdigest()
        sha512Hash = hashlib.sha512(event.get_argument()).hexdigest()

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name=md5Hash,
                                description='md5',
                                highlightable=False,
                                on_enter=CopyToClipboardAction(md5Hash)))

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name=sha1Hash,
                                description='sha1',
                                highlightable=False,
                                on_enter=CopyToClipboardAction(sha1Hash)))

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name=sha224Hash,
                                description='sha224',
                                highlightable=False,
                                on_enter=CopyToClipboardAction(sha224Hash)))

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name=sha256Hash,
                                description='sha256',
                                highlightable=False,
                                on_enter=CopyToClipboardAction(sha256Hash)))

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name=sha512Hash,
                                description='sha512',
                                highlightable=False,
                                on_enter=CopyToClipboardAction(sha512Hash)))

        return RenderResultListAction(items)
Exemplo n.º 22
0
 def on_event(self, event, extension):
     results = event.get_data()
     items = []
     for file in results:
         items.append(
             ExtensionSmallResultItem(icon='images/copy.png',
                                      name=file,
                                      on_enter=CopyToClipboardAction(file)))
     return RenderResultListAction(items)
Exemplo n.º 23
0
	def on_event(self, event, extension):

		search_term = ''.join(['%', event.get_argument().replace('%', ''), '%']) if event.get_argument() else None
		if not search_term:
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name='Type in paste name...',
									on_enter=DoNothingAction())
			])
		search_terms = event.get_argument().replace('%', '').split(' ')
		search_term = ' '.join(search_terms)
		print(search_terms)
		print(' '.join(search_terms))
		if search_terms[0] == 'create':
			try:
				if not search_terms[1] and not search_terms[2]:
					return RenderResultListAction([
						ExtensionResultItem(icon=extension_icon,
											name='Type in new paste name and value',
											on_enter=DoNothingAction()),
						ExtensionResultItem(
											name='Format: [prefix] create <name of new paste> <value of new paste>',
											on_enter=DoNothingAction())
					])
			except: 
				return RenderResultListAction([
						ExtensionResultItem(icon=extension_icon,
											name='Type in new paste name and value',
											on_enter=DoNothingAction()),
						ExtensionResultItem(
											name='Format: [prefix] create <name of new paste> <value of new paste>',
											on_enter=DoNothingAction())
					])
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name="Create paste \"" + search_terms[1] + "\" with value \"" + ' '.join(x for x in search_terms[2:])+"\"",
									on_enter=pe.registerPaste(search_terms[1]," ".join(x for x in search_terms[2:])))
			])

		items = []
		try:
			for row in pe.getPastes(' '.join(search_terms)):
				if len(items) < 8:
					items.append(ExtensionResultItem(icon=extension_icon,
													 name="Copy paste: "+row['name'].capitalize(),
													 on_enter=CopyToClipboardAction(row['value'])))
		except:
			return RenderResultListAction([
				ExtensionResultItem(icon=extension_icon,
									name='No pastes found with name "'+ ' '.join(search_terms)+ '"',
									on_enter=DoNothingAction()),
				ExtensionResultItem(icon=extension_icon,
									name='Add a paste with "cp create <name> <value>"',
									on_enter=DoNothingAction())
			])
		return RenderResultListAction(items)
Exemplo n.º 24
0
    def get_items(self, query):

        items = []

        # Handle credentials error
        if not self.headers['X-Api-Key'] or not self.headers['X-Api-Token']:
            items.append(
                ExtensionResultItem(
                    icon='images/cacher.png',
                    name='Credentials not found!',
                    description='Press Enter to go straight to cacher.io',
                    on_enter=OpenUrlAction('https://app.cacher.io')))
            return items

        if self.data is None or (time.time() -
                                 self.cache_start) > self.cache_max:
            response = requests.get(
                'https://api.cacher.io/integrations/show_all',
                headers=self.headers)
            self.data = response.json()

            # Handle API error
            if 'status' in self.data and self.data['status'] == 'error':
                logger.error(self.data['message'])
                items.append(
                    ExtensionResultItem(icon='images/cacher.png',
                                        name='An error just occured!',
                                        description='Error content: ' +
                                        self.data['message']))
                return items

        matches = []
        self.matches_len = 0

        if query is None:
            query = ''

        snippets_data = self.data['personalLibrary']['snippets']
        labels_data = self.data['personalLibrary']['labels']
        for i in range(0, len(self.data['teams'])):
            snippets_data.extend(self.data['teams'][i]['library']['snippets'])
            labels_data.extend(self.data['teams'][i]['library']['labels'])

        matches = self.find_rec(snippets_data, query, matches)

        for i in range(0, self.matches_len):
            labels = self.get_labels(labels_data, matches[i]['guid'])
            items.append(
                ExtensionResultItem(icon='images/cacher.png',
                                    name='%s' % matches[i]['title'],
                                    description='%s' % matches[i]['file'] +
                                    ' ' + ''.join(labels),
                                    on_enter=CopyToClipboardAction(
                                        matches[i]['data'])))

        return items
Exemplo n.º 25
0
    def on_event(self, event, extension):

        items = []

        user_input = event.get_argument() or ""

        if user_input != "":

            queries = user_input.split(' ')
            key = queries[0]

            mode = extension.preferences['charlist']
            length = -1
            exclude = ""
            include = ""
            if len(queries) > 1:
                for i in range(1, len(queries)):
                    query = queries[i].lower()
                    if query.startswith('mode:') or query.startswith('m:'):
                        m = query.split(':')[1]
                        if m == 'alphanumeric' or m == 'an':
                            mode = 'alphanumeric'
                        elif m == 'loweralphanumeric' or m == 'lower' or m == 'lan' or m == 'ln':
                            mode = 'loweralphanumeric'
                        elif m == 'alphabets' or m == 'ab':
                            mode = 'alphabets'
                        elif m == 'all':
                            mode = 'all'
                    elif query.startswith('length:') or query.startswith(
                            'len:') or query.startswith('l:'):
                        try:
                            length = int(query.split(':')[1])
                        except Exception:
                            length = -1
                    elif query.startswith('exclude:') or query.startswith(
                            'e:') or query.startswith('ex:'):
                        exclude = query.split(':')[1]
                    elif query.startswith('include:') or query.startswith(
                            'in:') or query.startswith('i:'):
                        include = query.split(':')[1]

            password_generator = PasswordGenerator(
                extension.preferences['password_namespace'],
                extension.preferences['password_header'])
            password = password_generator.generate(key, length, mode, exclude,
                                                   include)

            items.append(
                ExtensionResultItem(
                    icon='images/icon.png',
                    name=password,
                    description=
                    'Press Enter to copy this password to clipboard',
                    on_enter=CopyToClipboardAction(password)))

        return RenderResultListAction(items)
Exemplo n.º 26
0
    def on_event(self, event, extension):
        items = []

        ext_ip = findip.get_external_ip()
        int_ip = findip.get_local_ip()

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name='Local IP',
                                description='IP:  %s' % int_ip,
                                on_enter=CopyToClipboardAction(int_ip)))

        items.append(
            ExtensionResultItem(icon='images/icon.png',
                                name='External IP',
                                description='IP: %s' % ext_ip,
                                on_enter=CopyToClipboardAction(ext_ip)))

        return RenderResultListAction(items)
Exemplo n.º 27
0
    def on_event(self, event, extension):
        reload(config)
        try:
            if config.database_path == "" or config.master_key == "":
                raise ValueError("您尚未配置数据库路径或密码,请按回车配置")
            try:
                extension.db = PyKeePass(config.database_path,
                                         password=config.master_key)
            except:
                raise IOError("数据库或密码错误,回车后请重新配置")
            arg = event.get_argument()
            args_list = None
            try:
                args_list = arg.split(" ")
            except:
                pass
            if len(args_list) >= 1:
                arg = args_list[0]
                if arg == "add":
                    return RenderResultListAction([
                        ExtensionResultItem(icon='images/icon.png',
                                            name='%s' % "添加密码到数据库",
                                            on_enter=ExtensionCustomAction(
                                                args_list, keep_app_open=True))
                    ])
                else:
                    if len(args_list) > 1:
                        raise AttributeError("参数填写错误")
                    # 执行密码查询
                    items = []
                    for e in extension.db.entries:
                        title = e.title
                        name = e.username
                        if title is None:
                            title = ""
                        if name is None:
                            name = ""
                        if arg in title or arg in name:
                            items.append(
                                ExtensionResultItem(
                                    icon='images/icon.png',
                                    name='%s' % title,
                                    description='%s' % name,
                                    on_enter=CopyToClipboardAction(
                                        e.password)))
                    return RenderResultListAction(items)

        except (ValueError, IOError, AttributeError), e:
            print type(e)
            return RenderResultListAction([
                ExtensionResultItem(icon='images/icon.png',
                                    name='%s' % e.message,
                                    on_enter=ExtensionCustomAction(
                                        e, keep_app_open=True))
            ])
Exemplo n.º 28
0
 def on_event(self, event, extension):
     logging.debug('Clipboard History event: %s, argument: %s',
                   event.__class__.__name__, event.get_argument())
     items = search(event.get_argument() or None)
     entries = []
     for item in items:
         entries.append(
             ExtensionResultItem(name=item['text'],
                                 on_enter=CopyToClipboardAction(
                                     item['text'])))
     return RenderResultListAction(entries)
Exemplo n.º 29
0
    def search_package(self, query_package):
        results = []

        if query_package == "":
            return [
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="Start typing the package name",
                    description="Remember, you can use regular expresions\nFor example: apty ^steam",
                )
            ]

        terminal_app = self.preferences.get("apty_terminal_app")
        max_results = int(self.preferences.get("apty_n_results"))

        data = subprocess.Popen(["apt-cache", "search", str(query_package)], stdout=subprocess.PIPE)
        query_results = str(data.communicate())\
            .replace("(b\"", "")\
            .replace("(b'", "")\
            .replace("\\n', None)", "")\
            .replace("\\n\", None)", "")\
            .replace("', None)", "")\
            .replace("\", None)", "")

        if query_results == "":
            return [
                ExtensionResultItem(
                    icon="images/icon.png",
                    name="No package " + query_package + " could be found",
                    description="Are your repositories updated? (sudo apt update)\n"
                                "Remember, you can use regular expresions\nFor example: apty ^steam",
                )
            ]

        packages = query_results.split("\\n")
        n_results = int(len(packages))

        max_range = min(max_results, n_results)

        for i in range(int(max_range)):
            package = packages[i]
            package_name = package.split(" - ")[0]
            package_description = package.split(" - ")[1]
            results.append(
                ExtensionResultItem(
                    icon="images/icon.png",
                    name=package_name,
                    description=package_description,
                    on_enter=RunScriptAction('%s sudo apt install %s' % (terminal_app, package_name), []),
                    on_alt_enter=CopyToClipboardAction(package_name)
                )
            )

        return results
Exemplo n.º 30
0
    def on_event(self, event, extension):
        query = event.get_argument()
        logger.info("preferences %s" % json.dumps(extension.preferences))
        expression = subprocess.run(
            ["qalc", query], stdout=subprocess.PIPE, text=True
        ).stdout
        result = subprocess.run(
            ["qalc", '-t', query], stdout=subprocess.PIPE, text=True
        ).stdout
        items = [
            ExtensionResultItem(
                icon="images/icon.svg",
                name=expression,
                description="Enter to copy the result\nAlt-enter to copy the expression",
                on_enter=CopyToClipboardAction(result),
                on_alt_enter=CopyToClipboardAction(expression),
            )
        ]

        return RenderResultListAction(items)