Example #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
Example #2
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))
Example #3
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')
Example #4
0
def get_actions():
	arr = []
	isChrome = bool(int(applescript("isChrome")))
	isSafari = bool(int(applescript("isSafari")))
	isClipboard = applescript("isClipboard")

	if isChrome:
		chrome_url = applescript("chrome")
		arr.append(alfred.Item(
			attributes={'uid': alfred.uid(0), 'arg': "chrome"},
			title='Pocket - save url from Chrome',
			icon='icon.png',
			subtitle= chrome_url["title"].decode('utf8')
		))
	if isSafari:
		s_url = applescript("safari")
		arr.append(alfred.Item(
			attributes={'uid': alfred.uid(0), 'arg': "safari"},
			title='Pocket - save url from Safari',
			icon='icon.png',
			subtitle=s_url["title"].decode('utf8')
		))
	if isClipboard:
		c_url = applescript("clip")
		arr.append(alfred.Item(
				attributes={'uid': alfred.uid(0), 'arg': "clip"},
				title='Pocket - save url from Clipboard',
				icon='icon.png',
				subtitle=c_url["url"].decode('utf8')
			))
	xml = alfred.xml(arr)
	alfred.write(xml)
Example #5
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
Example #6
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')
Example #7
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
Example #8
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
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
def results(arg, com):
    uid = 0
    tasks = os.popen('./todo.sh ls' + com + ' ' + arg).read().splitlines()
    if com == 'prj':
        uid += 1
        yield alfred.Item({'uid': alfred.uid(uid), 'arg': ''}, 'ALL Projects', 'Enter to display all ...', 'EBD226C2-1E22-4F65-BD43-556E6EF3C463.png')
    for task in tasks:
        uid += 1
        task = task.rstrip()
        yield alfred.Item({'uid': alfred.uid(uid), 'arg': task}, task, 'Enter to display' + task, 'EBD226C2-1E22-4F65-BD43-556E6EF3C463.png')
Example #11
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))
def alfred_items_for_value(value):
    """
    Given a delorean datetime object, return a list of
    alfred items for each of the results
    """

    index = 0
    results = []

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

    # Various formats
    formats = [
        # 1937-01-01
        ("%Y-%m-%d", ''),
        # 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.shift('Asia/Shanghai').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
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
Example #14
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 "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
Example #15
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))
Example #16
0
def searchComics(search_term):
	feedback_items = []
	for i in getPlugins():
		plugin = loadPlugin(i)
		title = plugin.title()
		subtitle = plugin.subtitle()
		should_add = (plugin.enabled() 
			and (search_term == None 
				or title.lower().find(search_term.lower()) >= 0 
				or subtitle.lower().find(search_term.lower()) >= 0)
			)
		if should_add:	
			feedback_items.append(
				alfred.Item(
					attributes = { 
					'uid' : alfred.uid(i["name"]),
					'arg' : i["name"]
					},
					title = title,
					subtitle = subtitle,
					icon = os.path.join(i["location"], "icon.png")
				)
			)
	xml = alfred.xml(feedback_items)
	alfred.write(xml)
def alfred_items_for_query(query):
    index = 0
    alfred_results = []
    with open('port', 'r') as infile:
        port = int(infile.read())

    search_results = gsearch.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': title + ';' + href,
            },
            quicklookurl=href,
            icon='icon.png',
        ))

        index += 1

    return alfred_results
Example #18
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
Example #19
0
def history_results(db, query, favicons=True):
    q = u'%{}%'.format(query)
    if favicons:
        favicon_select = FAVICON_SELECT
        favicon_join = FAVICON_JOIN
    else:
        favicon_select = ''
        favicon_join = ''
    for row in db.execute(
            HISTORY_QUERY.format(favicon_select=favicon_select,
                                 favicon_join=favicon_join), (
                                     q,
                                     q,
                                 )):
        if favicons:
            (uid, title, url, image_data, image_last_updated) = row
            icon = cache_favicon(
                image_data, uid, convert_chrometime(image_last_updated)
            ) if image_data and image_last_updated else None
        else:
            (uid, title, url) = row
            icon = None

        yield alfred.Item(
            {
                u'uid': alfred.uid(uid),
                u'arg': url,
                u'autocomplete': url
            }, title or url, url, icon)
Example #20
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
Example #21
0
def empty_result(exit = True):
    empty = Item(
            attributes={'uid': alfred.uid('empty'), 'arg': ''},
            title='Gradle Please',
            subtitle=u':( Nothing found.',
            icon=u'icon.png')
    xml_result([empty], exit)
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
Example #23
0
def getPlayerInfo(value):
	selectItem = None
	for item in value:
		if item['rating'] == rating:
			selectItem = item
			break
	statusDic = {
	u'PACE(速度)': selectItem['attr1'],
	u'SHOOTING(射门)': selectItem['attr2'],
	u'PASSING(传球)': selectItem['attr3'],
	u'DRIBBLING(盘带)': selectItem['attr4'],
	u'DEFENDING(防守)': selectItem['attr5'],
	u'PHYSICAL(身体)': selectItem['attr6']
	}
	results = []
	index = 0

	for (key, value) in statusDic.items():
		# print key, value
		results.append(alfred.Item(
            title= key,
            subtitle=value,
            attributes={
                'uid': alfred.uid(index), 
                'arg': u'%s\'s %s is %d' % (selectItem['full_name'], key , value),
            },
        	icon='icon.png',
        ))
		index += 1
	xml = alfred.xml(results)
	alfred.write(xml)
Example #24
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
def alfred_items_for_value(value):
    """
    Given a Chinese language string, return a list of alfred items for each of the results
    """
    index = 0
    results = []

    config_list = [
        ('t2s.json', u'繁體到簡體', 'SimplifiedChinese.png'),
        ('s2t.json', u'簡體到繁體', 'TraditionalChinese.png'),
        ('s2tw.json', u'簡體到臺灣正體', 'TW_taiwan.png'),
        ('tw2s.json', u'臺灣正體到簡體', 'CN_china.png'),
        ('s2hk.json', u'簡體到香港繁體', 'HK_hongKong.png'),
        ('hk2s.json', u'香港繁體(香港小學學習字詞表標準)到簡體', 'CN_china.png'),
        ('tw2sp.json', u'繁體(臺灣正體標準)到簡體並轉換爲中國大陸常用詞彙', 'CN_china.png'),
        ('s2twp.json', u'簡體到繁體(臺灣正體標準)並轉換爲臺灣常用詞彙', 'TW_taiwan.png'),
    ]
    for config_file, description, icon in config_list:
        converter = opencc.OpenCC(
            config=config_file, opencc_path='/usr/local/bin/opencc')
        item_value = converter.convert(value)
        results.append(alfred.Item(
            title=item_value,
            subtitle=description,
            attributes={
                'uid': alfred.uid(index),
                'arg': item_value,
            },
            icon=icon,
        ))
        index += 1

    return results
Example #26
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)
def makeItem(itemData, itemIdx, itemPos):
    mo = roItem.search(itemData, itemPos)
    if mo is None or mo.lastindex is None:
        return (None, None);

    url = urllib.quote(mo.group(2), ":/&?=")  # .replace(" ", "%20")
    name = parser.unescape(mo.group(3))
    imageUrl = mo.group(4)
    price = parser.unescape(mo.group(5))
    itemPos = mo.end()

    if price == "":
        title = name
    else:
        title = "%s (%s)" % (name, price)
    # subTitle = price
    subTitle = 'View "%s" on Steam' % name

    # to make alfred not to remember same uid
    _uid = str(itemIdx + 1) + "." + str(int(time.time() * 100.0))

    filepath = ""
    if imageUrl and useIcon:  # cache image
        idx = imageUrl.find("=")
        if idx == -1:
            imageFileName = roImageName.sub(replImageName, imageUrl)
        else:
            imageFileName = imageUrl[idx + 1:] + ".jpg"

        filepath = os.path.join(alfred.work(True), imageFileName)
        if not os.path.exists(filepath):
            urllib.urlretrieve(imageUrl, filepath)

    item = alfred.Item(title=title, subtitle=subTitle, attributes={'uid': alfred.uid(_uid), 'arg': url}, icon=filepath)
    return (item, itemPos)
Example #28
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))
Example #29
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))
Example #30
0
def convert(query):
    #Input data
    query2 = unicodedata.normalize('NFC', query)

    parsed_data = string_div(query2)
    #	print(parsed_data)
    unit = parsed_data['unit']
    number = parsed_data['number']

    #Load convert data file
    try:
        f = open("unit.json", 'r')
    except:
        print("ERROR:can't create file")

    unit_data = json.load(f, encoding='utf-8')

    #print(unit_data['inch'])

    #Data check & convert
    output_list = []
    #	item = alfred.Item({'uid': alfred.uid(1), 'arg': 'some arg', 'valid': 'no'}, unit, number, ('someicon.png', {'type': 'filetype'}))
    #	output_list.append(item)

    for unit_group in unit_data:
        inputs = unit_data[unit_group]['input']
        outputs = unit_data[unit_group]['output']

        for input_keyword in inputs:
            if input_keyword == unit:
                for output_unit in outputs:

                    #convert calc type check
                    find_index = outputs[output_unit].find("?")
                    if find_index >= 0:
                        #special pattern
                        float_str = eval(outputs[output_unit].replace(
                            '?', number))
                        float_data = float(float_str)
                    else:
                        #normal pattern
                        float_data = float(
                            outputs[output_unit]) * float(number)

                    #output_data = {'number':str(float_data),'unit':output_unit}
                    output_str = str(float_data) + output_unit
                    item = alfred.Item(
                        {
                            'uid': alfred.uid(len(output_list) + 1),
                            'arg': output_str,
                            'valid': 'yes'
                        }, output_str, query, ('icon.png', {
                            'type': 'png'
                        }))
                    output_list.append(item)
#	print(output_list)

    xml = alfred.xml(output_list)
    alfred.write(xml)
Example #31
0
def search_imfdb( query ):
	args = { "action":"query", "list":"search", "srprop":"timestamp", "format":"json", "srsearch":query }
	response = json.loads( urllib2.urlopen("http://www.imfdb.org/api.php?"+urllib.urlencode(args)).read() )
	wiki = response["query"]["search"]
	
	result = []
	default_title = u"更多详细结果……"
	if len(wiki) == 0:
		default_title = u"找不到结果,请使用网页查询……"
	default_link = "http://www.imfdb.org/index.php?" + urllib.urlencode({"search":query})
	result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, default_title, default_link, ("imfdb.png") ) )

	for w in wiki:
		link = u"http://www.imfdb.org/wiki/" + urllib.quote( w["title"].encode("utf8") )
		result.append( alfred.Item( {"uid":alfred.uid(w["title"]), "arg":link}, 
			unescape_html(w["title"]), link, ("imfdb.png")) ) 
	return result
def search_sina( query ):
	args = { "app_key":"1335320450", "c":"news", "sort":"rel", "range":"all", "ie":"utf-8", "video":"1", "q":query }
	response = json.loads( urllib2.urlopen("http://platform.sina.com.cn/search/search?"+urllib.urlencode(args)).read() )
	news = response["result"]["list"]
	
	result = []
	default_title = u"更多详细结果……"
	if len(news) == 0:
		default_title = u"找不到结果,请使用网页查询……"
	default_link = "http://search.sina.com.cn/?c=news&q=" + urllib.urlencode( args )
	result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, default_title, default_link, ("sina.png") ) )
		
	for n in news:
		result.append( alfred.Item( {"uid":alfred.uid(n["url"]), "arg":n["url"]}, 
			unescape_html(n["title"]), n["datetime"]+" "+n["url"], ("sina.png")) )

	return result
def addResult(title, subtitle, icon, c_digest=None):
  global results
  results.append(alfred.Item(
      attributes= {'uid': alfred.uid(0), 'arg': c_digest},
      title=title,
      subtitle=subtitle,
      icon=icon
  ))
Example #34
0
def search_sina( query ):
	args = { "app_key":"1335320450", "c":"news", "sort":"rel", "range":"all", "ie":"utf-8", "video":"1", "q":query }
	response = json.loads( urllib2.urlopen("http://platform.sina.com.cn/search/search?"+urllib.urlencode(args)).read() )
	news = response["result"]["list"]
	
	result = []
	default_title = u"更多详细结果……"
	if len(news) == 0:
		default_title = u"找不到结果,请使用网页查询……"
	default_link = "http://search.sina.com.cn/?c=news&q=" + urllib.urlencode( args )
	result.append( alfred.Item( {"uid":alfred.uid("0"), "arg":default_link}, default_title, default_link, ("sina.png") ) )
		
	for n in news:
		result.append( alfred.Item( {"uid":alfred.uid(n["url"]), "arg":n["url"]}, 
			unescape_html(n["title"]), n["datetime"]+" "+n["url"], ("sina.png")) )

	return result
Example #35
0
def config_file_is_empty():
    yield alfred.Item({
        u'uid': alfred.uid(0),
        u'arg': '',
        u'ignore': 'yes'
    }, 'Google Authenticator is not yet configured',
                      "You must add your secrets to the '~/.gauth' file " +
                      "(see documentation)", 'warning.png')
Example #36
0
def results(db, query):
    db.create_function("regexp", 2, regexp)
    found = set()
    for result in db.execute(sql(query)):
        if result in found:
            continue
        found.add(result)
        (uid, title, url, faviconid) = result
        yield alfred.Item({u'uid': alfred.uid(uid), u'arg': url}, title, url, icon(db, faviconid))
Example #37
0
def default():
    return alfred.Item(
        attributes={
            'uid': alfred.uid("language"),
            'arg': ''
        },
        title='Enter a language code followed by the search term',
        subtitle='e.g. "w en workflow" to search for workflows',
        icon='icon.png')
Example #38
0
def empty_result(exit=True):
    empty = Item(attributes={
        'uid': alfred.uid('empty'),
        'arg': ''
    },
                 title='Gradle Please',
                 subtitle=u':( Nothing found.',
                 icon=u'icon.png')
    xml_result([empty], exit)
Example #39
0
def noresults(query):
    return alfred.Item(attributes={
        'uid':
        alfred.uid("google"),
        'arg':
        'http://google.com/search?q=' + urllib.quote(query.encode("utf8"))
    },
                       title="Search Google for '" + query + "'",
                       subtitle='',
                       icon='google.png')
Example #40
0
File: cf.py Project: Eronana/OJOJO
def add_contest(result, contest):
    url = "http://codeforces.com/contest/%d" % contest["id"]
    result.append(
        alfred.Item(
            {"uid": alfred.uid(len(result)), "arg": url},
            contest["name"],
            "Type:%s Problems:%d" % (contest["type"], len(contest["problems"])),
            "13D691AA-D2EE-47FD-88FF-1653B5A6815C.png",
        )
    )
Example #41
0
def parse(uid, action, title, subtitle):
    return alfred.Item(
        attributes={
            'uid': alfred.uid(uid),
            'arg': action,
            },
        title=title.replace("+", ", "),
        subtitle=subtitle,
        icon="icon.png",
        )
Example #42
0
def addResult(title, subtitle, icon, c_digest=None):
    global results
    results.append(
        alfred.Item(attributes={
            'uid': alfred.uid(0),
            'arg': c_digest
        },
                    title=title,
                    subtitle=subtitle,
                    icon=icon))
Example #43
0
File: oj.py Project: Eronana/OJOJO
	def ad_prob(this,result,p):
		result.append(alfred.Item(
	        {
	            "uid":alfred.uid(len(result)),
	            "arg":p["url"]
	        },
	        p["title"],
	        p["subtext"],
	        this.ICON
	    ))
Example #44
0
File: oj.py Project: Eronana/OJOJO
	def checkresult(this,result,hit):
		if len(result)==0:
			result.append(alfred.Item(
				{
					"uid":alfred.uid(len(result))
				},
				hit,
				None,
				this.ICON
			))
Example #45
0
def default_no_tags():
    title = "Sorry, no tags exist"
    subtitle = "Type something to create a new todo"
    return alfred.Item(attributes={
        'uid': alfred.uid("notags"),
        'arg': ''
    },
                       title=title,
                       subtitle=subtitle,
                       icon="todo_tag.png")
Example #46
0
def noresults(query):
    return alfred.Item(
        attributes = { 
            'uid' : alfred.uid("google"),
            'arg' : 'http://google.com/search?q=' + urllib.quote(query.encode("utf8"))
        },
        title = "Search Google for '" + query + "'",
        subtitle = '',
        icon = 'google.png'
    )
Example #47
0
def default():
    return alfred.Item(
        attributes = { 
            'uid' : alfred.uid("language"),
            'arg' : ''
        },
        title = 'Enter a language code followed by the search term',
        subtitle = 'e.g. "w en workflow" to search for workflows',
        icon = 'icon.png'
    )
Example #48
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
Example #49
0
def default_no_tags():
	title = "Sorry, no tags exist"
	subtitle = "Type something to create a new todo"
	return alfred.Item(
		attributes = { 
		'uid' : alfred.uid("notags"),
		'arg' : ''
		},
		title = title,
		subtitle = subtitle,
		icon = "todo_tag.png"
	)
def results(arg):
    uid = 0
    # read todo.txt
    path = alfred.work(False) + '/todo.txt'
    file = open(path)
    tasks = file.read().splitlines()
    file.close()

    for task in tasks:
        uid += 1
        # filter with keyword
        if arg in task:
            yield alfred.Item({'uid': alfred.uid(uid), 'arg': str(uid)}, task, u'Enter to Prioritize this task! Press ⌥ to Deprioritize it', 'EBD226C2-1E22-4F65-BD43-556E6EF3C463.png')
Example #51
0
def login():
	code = pocket.getRequestCode()
	with open('code.json', 'w') as myFile:
		myFile.write(json.dumps(code))

	results = [alfred.Item(
		attributes={'uid': alfred.uid(0), 'arg': code["code"]},
		title='Login!',
		icon='icon.png',
		subtitle=u'Login with Pocket.com (you will be taken to pocket.com)'
	)] # a single Alfred result
	xml = alfred.xml(results) # compiles the XML answer
	alfred.write(xml) # writes the XML back to Alfred
Example #52
0
File: w.py Project: trunda/my-mac
def parse(lang, item):
    item_arg = u'http://' + lang + '.wikipedia.org/wiki/' + urllib.quote(item['title'].encode("utf8"))

    return alfred.Item(
        attributes={
            'uid': alfred.uid(item['title']),
            'arg': item_arg,
            'autocomplete': item['title']
        },
        title=item['title'],
        subtitle=get_content(item),
        icon='icon.png'
    )
Example #53
0
File: w.py Project: trunda/my-mac
def opensearch_parse(lang, item):
    item_arg = u'http://' + lang + '.wikipedia.org/wiki/' + urllib.quote(item.encode("utf8"))

    return alfred.Item(
        attributes={
            'uid': alfred.uid(item),
            'arg': item_arg,
            'autocomplete': item
        },
        title=item,
        subtitle='Read about ' + item + ' on ' + lang + '.wikipedia.org',
        icon='icon.png'
    )
Example #54
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))
Example #55
0
def opensearch_parse(lang, item):
    item_arg = u'http://' + lang + '.wikipedia.org/wiki/' + urllib.quote(item.encode("utf8"))

    return alfred.Item(
        attributes = { 
            'uid' : alfred.uid(item),
            'arg' : item_arg,
            'autocomplete' : item
        },
        title = item,
        subtitle = 'Read about ' + item + ' on ' + lang + '.wikipedia.org',
        icon = 'icon.png'
    )
Example #56
0
def get_actions():
    arr = []
    isChrome = bool(int(applescript("isChrome")))
    isSafari = bool(int(applescript("isSafari")))
    isClipboard = applescript("isClipboard")

    if isChrome:
        chrome_url = applescript("chrome")
        arr.append(
            alfred.Item(attributes={
                'uid': alfred.uid(0),
                'arg': "chrome"
            },
                        title='Pocket - save url from Chrome',
                        icon='icon.png',
                        subtitle=chrome_url["title"].decode('utf8')))
    if isSafari:
        s_url = applescript("safari")
        arr.append(
            alfred.Item(attributes={
                'uid': alfred.uid(0),
                'arg': "safari"
            },
                        title='Pocket - save url from Safari',
                        icon='icon.png',
                        subtitle=s_url["title"].decode('utf8')))
    if isClipboard:
        c_url = applescript("clip")
        arr.append(
            alfred.Item(attributes={
                'uid': alfred.uid(0),
                'arg': "clip"
            },
                        title='Pocket - save url from Clipboard',
                        icon='icon.png',
                        subtitle=c_url["url"].decode('utf8')))
    xml = alfred.xml(arr)
    alfred.write(xml)
Example #57
0
def gen_alfred_items(timestamp):
    index = 0
    results = []
    results.append(
        alfred.Item(
            title=str(timestamp),
            subtitle='',
            icon='icon.png',
            attributes={
                'uid': alfred.uid(index),
                'arg': timestamp,
            },
        ))
    index += 1

    # Various formats
    formats = [
        "%Y-%m-%d %H:%M:%S",
        "%Y/%m/%d %H:%M:%S",
        "%Y%m%d%H%M%S",
    ]
    for format in formats:
        date_str = datetime.strftime(datetime.fromtimestamp(timestamp), format)
        results.append(
            alfred.Item(
                title=str(date_str),
                subtitle='',
                attributes={
                    'uid': alfred.uid(index),
                    'arg': date_str,
                },
                icon='icon.png',
            ))
        index += 1

    return results