Exemplo n.º 1
0
def search_suggest(query, api):
    if api == "bing":
        args = {"query": query}
        response = urllib2.urlopen("http://api.bing.com/osjson.aspx?" +
                                   urllib.urlencode(args)).read()
        suggests = json.loads(response)[1]
    else:
        set_proxy()
        args = {"output": "firefox", "hl": "zh-CN", "q": query}
        response = urllib2.urlopen(
            "https://www.google.com.hk/complete/search?" +
            urllib.urlencode(args)).read()
        suggests = json.loads(unicode(response, "gbk"))[1]

    result = []
    default_title = u"更多详细结果……"
    if len(suggests) == 0:
        default_title = u"找不到提示建议,请使用网页查询……"
    args = {"hl": "zh-CN", "q": query}
    default_link = "https://www.google.com/search?" + urllib.urlencode(args)
    result.append(
        alfred.Item({
            "uid": alfred.uid("0"),
            "arg": default_link
        }, default_title, default_link, ("google.png")))

    for q in suggests:
        args = {"hl": "zh-CN", "q": q.encode("gb18030")}
        link = "https://www.google.com/search?" + urllib.urlencode(args)
        result.append(
            alfred.Item({
                "uid": alfred.uid(q),
                "arg": link
            }, q, link, ("google.png")))
    return result
Exemplo n.º 2
0
def list_accounts(config, query):
    i = 0
    for section in config.sections():
        if len(query.strip()) and not query.lower() in str(section).lower():
            continue

        try:
            token = get_section_token(config, section)
            yield alfred.Item({u'uid': alfred.uid(i), u'arg': token,
                               u'autocomplete': section},
                              section,
                              'Post {} at cursor'.format(token),
                              'icon.png')
            i += 1
        except:
            pass

    if i > 0:
        # The uid for the remaining time will be the current time,
        # so it will appears always at the last position in the list
        yield alfred.Item({u'uid': time.time(), u'arg': '', u'ignore': 'yes'},
                          'Time Remaining: {}s'.format(get_time_remaining()),
                          None, 'time.png')
    else:
        yield alfred.Item({u'uid': alfred.uid(0), u'arg': '',
                           u'ignore': 'yes'},
                          "Account not found",
                          "There is no account named '" + query +
                          "' on your configuration file (~/.gauth)",
                          'warning.png')
Exemplo n.º 3
0
def _getNow():
    nowTime = time.time()
    nowDate = datetime.now()

    t1 = nowDate.strftime(_pattern1)
    t2 = nowDate.strftime(_pattern2)
    t3 = int(nowTime * 1000)
    t4 = int(nowTime)
    result = [
        alfred.Item({
            "uid": 1,
            "arg": t1
        }, "{}".format(t1), "当前时间1", None),
        alfred.Item({
            "uid": 2,
            "arg": t2
        }, "{}".format(t2), "当前时间2", None),
        alfred.Item({
            "uid": 3,
            "arg": t3
        }, "{}".format(t3), "时间戳(毫秒)", None),
        alfred.Item({
            "uid": 4,
            "arg": t4
        }, "{}".format(t4), "时间戳(秒)", None)
    ]
    _out(result)
Exemplo n.º 4
0
def latest_results(maxresults=_MAX_RESULTS):
    response = fetch_justadded()

    if not response:
        return alfred.xml([
            alfred.Item(
                attributes={
                    'uid': u'trailer://404',
                    'valid': u'no'
                },
                title=u'404 Latest Movies Not Found',
                subtitle=
                u'Sorry, the iTunes Movie Trailers server isn\'t responding',
                icon=u'icon.png')
        ])

    results = []
    for r in response[:maxresults]:
        address = u''.join((_BASE_URL, r['location']))
        results.append(
            alfred.Item(attributes={
                'uid': u'trailer://%s' % r['location'],
                'arg': address,
                'autocomplete': r['title']
            },
                        title=r['title'],
                        subtitle=u'Studio: %(studio)s' % r,
                        icon=fetch_poster(r['poster'])))

    return results
Exemplo n.º 5
0
def tell_days(days):
    if len(days.strip()) == 0:
        settings = _load_settings(False)
        length = '{} day'.format(settings['days'])
        if settings['days'] != 1:
            length += 's'
        return [
            alfred.Item('days',
                        'Currently showing {} of forecast'.format(length),
                        'Enter a new value to change')
        ]
    else:
        days = int(days)

        if days < 0 or days > 10:
            raise Exception('Value must be between 1 and 10')

        length = '{} day'.format(days)
        if days != 1:
            length += 's'
        return [
            alfred.Item('days',
                        'Show {} of forecast'.format(length),
                        arg=days,
                        valid=True)
        ]
Exemplo n.º 6
0
def main():
    #read
    knowledge_dir = '~/Knowledges'
    query = sys.argv[1:]
    result = "grep -r key %s" % knowledge_dir
    for argu in query:
        if argu:
            result += "| grep " + argu
    (status, output) = commands.getstatusoutput(result)
    result = []

    i = 1
    for line in output.split('\n'):
        if line:
            file_name = line.split(':')[0]
            key_list = line.split(':')[1].decode('utf8')
            preview = commands.getoutput("cat %s | grep title" %
                                         file_name).decode('utf8')
            result.append(
                alfred.Item({
                    "uid": alfred.uid(i),
                    'arg': file_name
                }, key_list, preview, None))
            i = i + 1

    if not result:
        result.append(
            alfred.Item({"uid": alfred.uid(i)}, "nothing find", "", None))

    alfred.write(alfred.xml(result))
Exemplo n.º 7
0
def tell_units(arg):
    items = []

    us = alfred.Item('us',
                     'US',
                     u'US units (°F, in, mph)',
                     arg='us',
                     valid=True)
    metric = alfred.Item('si',
                         'SI',
                         u'SI units (°C, cm, kph)',
                         arg='si',
                         valid=True)

    if len(arg.strip()) == 0:
        items.append(us)
        items.append(metric)
    elif 'us'.startswith(arg.lower()):
        items.append(us)
    elif 'metric'.startswith(arg.lower()):
        items.append(metric)
    else:
        items.append(alfred.Item('bad', 'Invalid units'))

    return items
Exemplo n.º 8
0
def search_results(query, maxresults=_MAX_RESULTS):
    response = fetch_terms(query)

    results = []
    for r in response[:maxresults]:
        address = u'/'.join((_BASE_URL, quote(r)))
        results.append(
            alfred.Item(attributes={
                'uid': address,
                'arg': address,
                'autocomplete': r
            },
                        title=r,
                        subtitle=u"Open %s on term.ly" % r,
                        icon=u'icon.png'))

    # no matches
    if results == []:
        results.append(
            alfred.Item(attributes={'valid': u'no'},
                        title=u'404 Term Not Found: %s' % query,
                        subtitle=u"Sorry, term '%s' was not found on term.ly" %
                        r,
                        icon=u'icon.png'))

    return results
Exemplo n.º 9
0
def search_wiki(query):
    set_proxy()
    args = {
        "action": "query",
        "list": "search",
        "srprop": "timestamp",
        "format": "json",
        "srsearch": query
    }
    response = json.loads(
        urllib2.urlopen("https://zh.wikipedia.org/w/api.php?" +
                        urllib.urlencode(args)).read())
    wiki = response["query"]["search"]

    result = []
    default_title = u"更多详细结果……"
    if len(wiki) == 0:
        default_title = u"找不到结果,请使用网页查询……"
    default_link = "https://zh.wikipedia.org/w/index.php?" + urllib.urlencode(
        {"search": query})
    result.append(
        alfred.Item({
            "uid": alfred.uid("0"),
            "arg": default_link
        }, default_title, default_link, ("wiki.png")))

    for w in wiki:
        link = u"https://zh.wikipedia.org/wiki/" + urllib.quote(
            w["title"].encode("utf8"))
        result.append(
            alfred.Item({
                "uid": alfred.uid(w["title"]),
                "arg": link
            }, unescape_html(w["title"]), link, ("wiki.png")))
    return result
Exemplo n.º 10
0
def search_google(query):
    set_proxy()
    args = {"hl": "zh-CN", "q": query}
    request = urllib2.Request(
        "https://www.google.com.hk/search?" + urllib.urlencode(args), None, {
            'User-Agent':
            "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3",
        })
    response = urllib2.urlopen(request).read().replace("rwt(",
                                                       "\nrwt(").split("\n")

    result = []
    default_link = "https://www.google.com/search?" + urllib.urlencode(args)
    result.append(
        alfred.Item({
            "uid": alfred.uid("0"),
            "arg": default_link
        }, u"更多详细结果……", default_link, ("google.png")))

    buffer_line = ""
    prev_line = ""
    for line in response:

        prev_line = buffer_line
        buffer_line = line
        if "rwt(" not in line or "<em>" not in line:
            continue

        title_begin = line.find("\"_blank\">")
        title_end = line.find("</a>")
        if title_begin == -1 or title_end == -1:
            continue
        title = strip_html(line[title_begin + 9:title_end])

        #link = parse_href( prev_line )
        link_begin = prev_line.rfind("<a href=\"http")
        link_end = prev_line.find("\" ", link_begin)
        if link_begin == -1 or link_end == -1:
            continue
        link = strip_html(prev_line[link_begin + 9:link_end])

        result.append(
            alfred.Item({
                "uid": alfred.uid(link),
                "arg": link
            }, unescape_html(unicode(title, "utf-8")), unicode(link, "utf-8"),
                        ("google.png")))

    if len(result) == 1:
        result = []
        result.append(
            alfred.Item({
                "uid": alfred.uid("0"),
                "arg": default_link
            }, u"找不到结果,请使用网页查询……", default_link, ("google.png")))

    return result
Exemplo n.º 11
0
def complete():
    query = sys.argv[1].strip()
    maxresults = int(os.getenv('alfredman_max_results', DEFAULT_MAX_RESULTS))
    cache_ttl = int(os.getenv('alfredman_cache_ttl', DEFAULT_CACHE_TTL))

    whatis = fetch_whatis(cache_ttl)
    sections = fetch_sections(whatis, cache_ttl)

    results = []

    if ' ' in query:
        # section page
        (_section, _title) = query.split()
        pattern = re.compile(r'^.+\(%s\)$' % _section)
        _whatis = filter_whatis_name(pattern.match, whatis)
        results.extend(result_list(_title, _whatis))
    else:
        # section filtering
        if query in sections:
            _uri = man_uri('(%s)' % query)
            results.append(
                alfred.Item(attributes={
                    'uid': _uri,
                    'arg': _uri,
                    'valid': 'no'
                },
                            title='Open man page',
                            subtitle='Scope restricted to section %s' % query,
                            icon='icon.png'))
        # direct hit
        if query in whatis:
            _arg = man_arg(query)
            _uri = man_uri(query)
            results.append(
                alfred.Item(attributes={
                    'uid': _uri,
                    'arg': _arg
                },
                            title=query,
                            subtitle=whatis[query],
                            icon='icon.png'))
        # standard filtering
        results.extend(result_list(query, whatis))

    # no matches
    if not results:
        results.append(
            alfred.Item(attributes={
                'uid': 'x-man-page://404',
                'valid': 'no'
            },
                        title='404 Page Not Found',
                        subtitle='',
                        icon='icon.png'))

    return alfred.xml(results, maxresults=maxresults)
Exemplo n.º 12
0
def search_weibo( query ):
	set_proxy()
	params = { "xsort":"time" }
	response = urllib2.urlopen( "http://s.weibo.com/weibo/"+urllib.quote_plus(query)
		+"&"+urllib.urlencode(params) ).read().decode("unicode-escape").split( "\n" )
	
	result = []
	default_link = u"http://s.weibo.com/weibo/" + urllib.quote_plus(query) + "&" + urllib.urlencode(params)
	result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, u"更多详细结果……", default_link, ("weibo.png") ) )
	
	name = ""
	weibo = ""
	link = ""	
	for line in response:
		if "pincode" in line:
			result.append( alfred.Item( {"uid":alfred.uid(link), "arg":default_link}, u"搜素行为异常,请退出微博登录并打开以下网页输入验证码", default_link, ("weibo.png")) )				
		
		if u"您可能感兴趣的结果" in line:
			break				

		elif "nick-name" in line:
			content = strip_html( line )
			weibo_pos = content.find( u":" )
			if weibo_pos == -1:
				continue
			name = content[1:weibo_pos]
			if name[0:1] == u"@":
				name = name[1:]
			weibo = content[weibo_pos+1:]
		
		elif "action-data=\"allowForward" in line and name!="" and weibo!="":
			link_begin = line.find( "&url=http:\/\/weibo.com\/" )
			link_end = line.find( "&mid=" )
			if link_begin==-1 or link_end==-1:
				name = ""
				weibo = ""
				continue
			link =line[link_begin+5:link_end]
			link = link.replace( "\\", "" )

			# append
			if name!="" and weibo!="" and link!="":
				result.append( alfred.Item( {"uid":link, "arg":link}, "@"+name+": "+unescape_html(weibo), link, ("weibo.png")) )
			# next
			name = ""
			weibo = ""
			link = ""
			
		else:
			continue
	
	if len(result) == 1:
		result = []
		result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, u"找不到结果,请使用网页查询……", default_link, ("weibo.png") ) )
	
	return result
Exemplo n.º 13
0
def complete(query, maxresults=_MAX_RESULTS):
    whatis = fetch_whatis()
    sections = fetch_sections(whatis)

    results = []

    # direct hit
    if query in whatis:
        _arg = man_arg(query)
        _uri = man_uri(query)
        results.append(
            alfred.Item(attributes={
                'uid': _uri,
                'arg': _arg
            },
                        title=query,
                        subtitle=whatis[query],
                        icon='icon.png'))

    # section filtering
    elif query in sections:
        _uri = man_uri('(%s)' % query)
        results.append(
            alfred.Item(attributes={
                'uid': _uri,
                'arg': _uri,
                'valid': 'no'
            },
                        title='Open man page',
                        subtitle='Scope restricted to section %s' % query,
                        icon='icon.png'))
    elif ' ' in query:
        (_section, _title) = query.split()
        pattern = re.compile(r'^.+\(%s\)$' % _section)
        _whatis = filter_whatis_name(pattern.match, whatis)
        results.extend(result_list(_title, _whatis))

    # substring matching
    elif query.startswith('~'):
        results.extend(result_list('*%s*' % query, whatis))
    # standard filtering
    else:
        results.extend(result_list(query, whatis))

    # no matches
    if results == []:
        results.append(
            alfred.Item(attributes={
                'uid': 'x-man-page://404',
                'valid': 'no'
            },
                        title='404 Page Not Found',
                        subtitle='No man page was found for %s' % query,
                        icon='icon.png'))

    return alfred.xml(results, maxresults=maxresults)
Exemplo n.º 14
0
def alfred_items_for_value(value):
    """
    Given a delorean datetime object, return a list of
    alfred items for each of the results
    """
    subtitleStr = u'UTC Timestamp'

    if _offset != 0:
        tmpStr = construct_offset_string()
        subtitleStr = u'UTC' + tmpStr + u' Timestamp'

    index = 0
    results = []

    # First item as timestamp
    item_value = calendar.timegm(value.datetime.utctimetuple())
    results.append(
        alfred.Item(
            title=str(item_value),
            subtitle=subtitleStr,
            attributes={
                'uid': alfred.uid(index),
                'arg': item_value,
            },
            icon='icon.png',
        ))
    index += 1

    # Various formats
    formats = [
        # 1937-01-01 12:00:27
        ("%Y-%m-%d %H:%M:%S", ''),
        # 19 May 2002 15:21:36
        ("%d %b %Y %H:%M:%S", ''),
        # Sun, 19 May 2002 15:21:36
        ("%a, %d %b %Y %H:%M:%S", ''),
        # 1937-01-01T12:00:27
        ("%Y-%m-%dT%H:%M:%S", ''),
        # 1996-12-19T16:39:57-0800
        ("%Y-%m-%dT%H:%M:%S%z", ''),
    ]
    for format, description in formats:
        item_value = value.datetime.strftime(format)
        results.append(
            alfred.Item(
                title=str(item_value),
                subtitle=description,
                attributes={
                    'uid': alfred.uid(index),
                    'arg': item_value,
                },
                icon='icon.png',
            ))
        index += 1

    return results
Exemplo n.º 15
0
def tell(name, query=''):
    '''Tell something'''
    try:
        cmd = 'tell_{}'.format(name)
        if cmd in globals():
            items = globals()[cmd](query)
        else:
            items = [alfred.Item('tell', 'Invalid action "{}"'.format(name))]
    except SetupError, e:
        items = [alfred.Item('error', e.title, e.subtitle, icon='error.png')]
Exemplo n.º 16
0
def process_sortoption(q):
    result = []
    result.append(alfred.Item(title='last accessed time', subtitle='^l ',
                              attributes={'valid':'no','autocomplete':q+(q and " " or "")+'^l ','uid':alfred.uid(4)}, icon="num-des.png"))
    result.append(alfred.Item(title='time ascending', subtitle='^d ',
                              attributes={'valid':'no','autocomplete':q+(q and " " or "")+'^d ','uid':alfred.uid(1)}, icon="general-des.png"))
    result.append(alfred.Item(title='title ascending', subtitle='^a ',
                              attributes={'valid':'no','autocomplete':q+(q and " " or "")+'^a ','uid':alfred.uid(2)}, icon="alpha-asc.png"))
    result.append(alfred.Item(title='title descending', subtitle='^z ',
                              attributes={'valid':'no','autocomplete':q+(q and " " or "")+'^z ','uid':alfred.uid(3)}, icon="alpha-des.png"))
    alfred.write(alfred.xml(result,maxresults=None))
Exemplo n.º 17
0
def main():
    try:
        q = unicode(sys.argv[1])
        q = unicodedata.normalize('NFC', q).lower().replace(' ', '')
    except:
        q = ""

    rss = rss_data()
    config = config_data()
    try:
        max_results = config['max_results']
    except:
        max_results = None

    results = []
    for e in itertools.islice(rss, max_results):
        if not q or q in e['title'].lower().replace(' ', ''):
            results.append(
                alfred.Item(title=e['title'],
                            subtitle=e['published'],
                            attributes={'arg': e['link']},
                            icon=e['image']))

    try:
        last_updated = config['last_updated']
    except:
        last_updated = 0
    subtitle = "Last updated: " + (
        last_updated and util.pretty_date(config['last_updated']) or "no info")

    diff = int(time.time()) - last_updated
    if diff > RELOAD_ASK_THRESHOLD or len(rss) == 0:
        results.insert(
            0,
            alfred.Item(title="BackToTheMac - Reload Data?",
                        subtitle=subtitle,
                        attributes={
                            'arg': 'reload',
                            'uid': alfred.uid('t')
                        },
                        icon="icon.png"))
    else:
        results.insert(
            0,
            alfred.Item(title="BackToTheMac",
                        subtitle=subtitle,
                        attributes={
                            'arg': 'http://macnews.tistory.com',
                            'uid': alfred.uid('t')
                        },
                        icon="icon.png"))

    alfred.write(alfred.xml(results, maxresults=None))
Exemplo n.º 18
0
def define_alias(_dict, definition, alias_file):
    if '=' in definition:
        (alias, pipe) = definition.split('=', 1)
    else:
        (alias, pipe) = (definition, '')

    terminator = os.getenv("alias_terminator", DEFAULT_ALIAS_TERMINATOR)

    if not alias:
        return alfred.xml([
            alfred.Item(
                attributes={'valid': 'no'},
                title="alias NAME=ARBITRARY-ONE-LINER",
                subtitle=
                "Terminate ONE-LINER with '{0}' to save or 'NAME={0}' to delete alias"
                .format(terminator),
                icon='icon.png')
        ])

    if pipe and pipe == terminator:
        _dict.pop(alias, None)
        write_aliases(_dict, alias_file)
        return alfred.xml([
            alfred.Item(attributes={
                'valid': 'no',
                'autocomplete': ''
            },
                        title="alias {0}={1}".format(alias, pipe),
                        subtitle='Alias deleted! TAB to continue',
                        icon='icon.png')
        ])

    if pipe and pipe.endswith(terminator):
        pipe = pipe[:-len(terminator)]
        _dict[alias] = pipe
        write_aliases(_dict, alias_file)
        return alfred.xml([
            alfred.Item(attributes={
                'valid': 'no',
                'autocomplete': alias
            },
                        title="alias {0}={1}".format(alias, pipe),
                        subtitle='Alias saved! TAB to continue',
                        icon='icon.png')
        ])

    return alfred.xml([
        alfred.Item(attributes={'valid': 'no'},
                    title="alias {0}={1}".format(alias, pipe),
                    subtitle='Terminate with {0} to save'.format(terminator),
                    icon='icon.png')
    ])
Exemplo n.º 19
0
def tell(name, query=''):
    '''Tell something'''
    try:
        cmd = 'tell_{}'.format(name)
        if cmd in globals():
            items = globals()[cmd](query)
        else:
            items = [alfred.Item('Invalid action "{}"'.format(name))]
    except SetupError, e:
        if show_exceptions:
            import traceback
            traceback.print_exc()
        items = [alfred.Item(e.title, e.subtitle, icon='error.png')]
Exemplo n.º 20
0
def help():
    result = []
    result.append(alfred.Item(title='Look up Documentation', subtitle='Goto project site', attributes={'arg':'https://github.com/jmjeong/alfred-extension/blob/master/alfred-pinboard/README.md','uid':alfred.uid(0)}, icon="icon.png"))
    result.append(alfred.Item(title='pbauth username:token', subtitle='set pinboard authentication token', attributes={'valid':'no','uid':alfred.uid(1)}, icon="icon.png"))
    result.append(alfred.Item(title='pbreload', subtitle='load latest bookmarks from pinboard.in', attributes={'valid':'no','uid':alfred.uid(2)}, icon="icon.png"))
    result.append(alfred.Item(title='pba query', subtitle='search all fields of bookmarks', attributes={'valid':'no','uid':alfred.uid(3)}, icon="icon.png"))
    result.append(alfred.Item(title='pbtag', subtitle='display tags list', attributes={'valid':'no','uid':alfred.uid(7)}, icon="icon.png"))
    result.append(alfred.Item(title='pbnote query', subtitle='display note list', attributes={'valid':'no','uid':alfred.uid(10)}, icon="icon.png"))
    result.append(alfred.Item(title='pbl query', subtitle='search link of bookmarks', attributes={'valid':'no','uid':alfred.uid(5)}, icon="icon.png"))
    result.append(alfred.Item(title='pbu query', subtitle='search title of toread bookmarks', attributes={'valid':'no','uid':alfred.uid(8)}, icon="icon.png"))
    result.append(alfred.Item(title='pbauthpocket', subtitle='Login with Pocket!', attributes={'valid':'no','uid':alfred.uid(1)}, icon="icon.png"))
    result.append(alfred.Item(title='To selected bookmark', subtitle='enter:goto site, cmd:copy url, alt:delete bookmark, tab:expand', attributes={'valid':'no','uid':alfred.uid(9)}, icon="icon.png"))
    alfred.write(alfred.xml(result,maxresults=None))
Exemplo n.º 21
0
def tell(name, query=''):
    '''Tell something'''
    try:
        cmd = 'tell_{}'.format(name)
        if cmd in globals():
            LOG.info('Running command {}'.format(name))
            items = globals()[cmd](query)
        else:
            LOG.warn('Invalid command {}'.format(name))
            items = [alfred.Item('Invalid action "{}"'.format(name))]
    except SetupError, e:
        LOG.exception('Error telling')
        items = [alfred.Item(e.title, e.subtitle, icon='error.png')]
Exemplo n.º 22
0
def showFileList(query):
    result = []
    filetypes = []
    count = 1
    filetype = ''
    pos = query.find('.')
    if pos != -1:
        filetype = query[pos + 1:]
        query = query[:query.index('.')]
        filetypes = [tp for tp in alltypes if tp.startswith(filetype)]
        if filetype not in filetypes and filetype != '':
            filetypes.insert(0, filetype)

    elif query != '':
        result.append(
            alfred.Item({
                'uid': count,
                'arg': query
            }, 'Make new file..', 'file name "' + query + '"', 'default.png'))
        count += 1
        if 'Makefile'.startswith(query):
            result.append(
                alfred.Item({
                    'uid': count,
                    'arg': 'Makefile'
                }, 'Make new file..', 'file name "Makefile"', 'make.png'))
            count += 1
        if 'makefile'.startswith(query):
            result.append(
                alfred.Item({
                    'uid': count,
                    'arg': 'makefile'
                }, 'Make new file..', 'file name "makefile"', 'make.png'))
            count += 1

        filetypes = alltypes

    for ch in filetypes:
        filename = query + '.' + ch
        result.append(
            alfred.Item({
                'uid': count,
                'arg': filename
            }, 'Make new file..', 'file name "' + filename + '"',
                        (ch, {
                            'type': 'filetype'
                        })))
        count += 1

    xml = alfred.xml(result)
    alfred.write(xml)
Exemplo n.º 23
0
def main(query):
    suggested_items = []
    uid = uid_generator()
    suggested_items.append(alfred.Item(
        attributes = { 'uid': uid.next(), 'arg': query },
        title = 'Execute following commands', subtitle = '', 
        icon = 'icon.png'))
    for command, script in keymacro.generate_applescripts(query):
        script = script.replace('''tell application "System Events" to ''', '')
        suggested_items.append(alfred.Item(
            attributes = { 'uid': uid.next(), 'arg': command },
            title = script, subtitle = '', 
            icon = 'icon.png'))
    alfred.write(alfred.xml(suggested_items))
Exemplo n.º 24
0
def search_zhihu( query ):
	params = { "type":"question", "q":query }
	response = urllib2.urlopen( "http://m.zhihu.com/search?"+urllib.urlencode(params) ).read().split( "\n" )
	
	result = []
	default_link = "http://www.zhihu.com/search?" + urllib.urlencode(params)
	result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, u"更多详细结果……", default_link, ("zhihu.png") ) )
	
	title = ""
	link = ""
	answers = "" 
	for line in response:
		# <a class="question_link" target="_blank" href="/question/{id}">{title}</a>
		# <a href="/question/{id}" class="answer zg-link-gray" target="_blank"><i></i>{answers}</a><a

		if "question_link" in line:
			title_begin = line.find( "\">" )
			title_end = line.rfind( "</a>" )
			if title_begin==-1 or title_end==-1:
				continue
			title = strip_html( line[title_begin+2:title_end] )
			
		elif "class=\"answer" in line and title!="":
			link_begin = line.find( "<a href=\"/question/" )
			link_end = line.find( "\" class=\"answer" )
			answers_begin = line.find( "<i></i>" )
			answers_end = line.rfind( "</a>" )			
			if link_begin==-1 or link_end==-1 or answers_begin==-1 or answers_end==-1:
				title = ""			
				continue
			link = line[link_begin+19:link_end]
			answers = line[answers_begin+7:answers_end]
	
			# append
			if title!="" and link!="" and answers!="":
				result.append( alfred.Item( {"uid":alfred.uid(link), "arg":"http://www.zhihu.com/question/"+link}, 
					unescape_html(unicode(title,"utf-8")), unicode(answers,"utf-8"), ("zhihu.png")) )				
			# next
			title = ""
			link = ""
			answers = ""
			
		else:
			continue
		
	if len(result) == 1:
		result = []
		result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, u"找不到结果,请使用网页查询……", default_link, ("zhihu.png") ) )
	
	return result
Exemplo n.º 25
0
def main():
    reload(sys)  # reload unicode decoder
    sys.setdefaultencoding('utf-8')  # use utf-8
    (param, word) = alfred.args()
    cityCode = '100010000'  # Beijing

    if word.isspace():
        url = "http://m.nuomi.com/client/gethotkeyword?cityid=%s&limit=20&client=ios&version=3.2.0" % (
            cityCode)
    else:
        word = OnlyCharNum(word)
        url = "http://m.nuomi.com/client/searchsuggest?k=%s&cityid=%s" % (
            word, cityCode)
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    data = json.loads(response.read())
    results = []
    if word.isspace():
        if len(data['keywords']) == 0:
            results.append(
                alfred.Item({
                    'uid': 0,
                    'arg': word
                }, word, '', 'icon.png'))
        else:
            for i in range(0, len(data['keywords'])):
                results.append(
                    alfred.Item(
                        {
                            'uid': i,
                            'arg': data['keywords'][i]['keyword']
                        }, data['keywords'][i]['keyword'], '', 'icon.png'))
    else:
        if len(data['data']) == 0:
            results.append(
                alfred.Item({
                    'uid': 0,
                    'arg': word
                }, word, '', 'icon.png'))
        else:
            for i in range(0, len(data['data'])):
                results.append(
                    alfred.Item({
                        'uid': i,
                        'arg': data['data'][i]['t']
                    }, data['data'][i]['t'], '', 'icon.png'))
    xml = alfred.xml(results)  # compiles the XML answer
    alfred.write(xml)
Exemplo n.º 26
0
def main(action, query):
    # If the configuration file doesn't exist, create an empty one
    if not os.path.isfile(_CONFIG_FILE):
        create_config()
        alfred.write(alfred.xml(config_file_is_empty()))
        return

    try:
        config = get_config()
        if not config.sections() and action != 'add':
            # If the configuration file is empty, tell the user to add secrets to it
            alfred.write(alfred.xml(config_file_is_empty()))
            return
    except Exception as e:
        alfred.write(alfred.xml([alfred.Item({u'uid': alfred.uid(0),
                                              u'arg': '', u'ignore': 'yes'},
                                             "~/.gauth: Invalid syntax",
                                             str(e).replace('\n', ' '),
                                             "error.png")]))
        sys.exit(1)

    if action == 'list' and not is_command(query):
        alfred.write(alfred.xml(list_accounts(config, query), maxresults=_MAX_RESULTS))
    elif action == 'add':
        alfred.write(add_account(config, query))
Exemplo n.º 27
0
def history_results(db, query):
    q = u'%{}%'.format('%'.join(query.split(' ')))
    for row in db.execute(HISTORY_QUERY, (q, q,)):
        (uid, title, url) = row
        icon = None

        yield alfred.Item({u'uid': alfred.uid(uid), u'arg': url, u'autocomplete': url}, title or url, url)
Exemplo n.º 28
0
def process_tag(pins, deleted_url, q, prefix):
    tag_list = {}

    for p in pins:
        url = p['href']
        if url in map(lambda x: x.lower(), deleted_url): continue
        try:
            tags = p['tags'].encode('utf-8').split(' ')
        except:
            tags = []
        for t in tags:
            if t in tag_list:
                tag_list[t] += 1
            else:
                tag_list[t] = 1
    resultData = []
    tag_list_key = sorted(tag_list.keys(), key=str.lower)
    for (idx, i) in enumerate(tag_list_key):
        if not q or q in i.lower():
            expand_str = prefix + (prefix and " " or "") + "#" + i + " : "
            resultData.append(
                alfred.Item(title=(i and i or "untagged") + " (" +
                            str(tag_list[i]) + ")",
                            subtitle='',
                            attributes={
                                'autocomplete': expand_str,
                                'valid': 'no',
                                'uid': alfred.uid(idx)
                            },
                            icon='tag.png'))
    alfred.write(alfred.xml(resultData, maxresults=None))
    return
Exemplo n.º 29
0
def search_rfc( query ):
    result = []

    # params = { "q":query }
    # response = urllib2.urlopen( "https://m.zhihu.com/search?"+urllib.urlencode(params) ).read().split( "\n" )
    response = urllib2.urlopen( 'https://m.zhihu.com/search?q=%s' % query ).read()

    print(response)
    # response=response.decode('utf-8')
    title = ""
    link = ""
    answers = ""
    for line in response:
        # <a class="question_link" target="_blank" href="/question/{id}">{title}</a>
        # <a href="/question/{id}" class="answer zg-link-gray" target="_blank"><i></i>{answers}</a><a

        if "js-title-link" in line:
            title_begin = line.find( "\">" )
            title_end = line.rfind( "</a>" )
            if title_begin==-1 or title_end==-1:
                continue
            title = strip_html( line[title_begin+2:title_end] )

            if title!="" and link!="" and answers!="":
                result.append( alfred.Item( {"uid":alfred.uid(link), "arg":"http://www.zhihu.com/question/"+link},
                    unescape_html(unicode(title,"utf-8")), unicode(answers,"utf-8"), ("zhihu.png")) )

        else:
            continue



    return result
Exemplo n.º 30
0
def alfred_items_for_query(query):
    index = 0
    alfred_results = []
    with open('port', 'r') as infile:
        port = int(infile.read())

    search_results = google.search(query, port)
    for result in search_results:
        title = result.get('title', '').decode('utf-8')
        href = result.get('href', '').decode('utf-8')

        alfred_results.append(
            alfred.Item(
                title=title,
                subtitle=href,
                attributes={
                    'uid': alfred.uid(index),
                    'arg': query + ';' + href,
                },
                icon='icon.png',
            ))

        index += 1

    return alfred_results