Exemplo n.º 1
0
class Dict(object):
    def __init__(self):
        self.service = services['qq']
        self.query_word = ''
        self.feedback = Feedback()

    def fetch(self, word):
        return {}

    def parse(self, data):
        pass

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse(self.fetch(word))

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(title=self.query_word,
                         subtitle='Sorry, no result.',
                         arg=self.query_word)
        print(self.feedback.get(unescape=True))
Exemplo n.º 2
0
class Dict(object):
    def __init__(self):
        self.service = services['qq']
        self.query_word =''
        self.feedback = Feedback()

    def fetch(self, word):
        return {}

    def parse(self, data):
        pass

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse( self.fetch(word) )

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(
                title       = self.query_word, 
                subtitle    = 'Sorry, no result.', 
                arg         = self.query_word )
        print(self.feedback.get(unescape = True))
Exemplo n.º 3
0
    def __init__(self):
        self.service = service
        self.query_word = ''
        self.feedback = Feedback()

        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''
Exemplo n.º 4
0
def get_suggest(q, headers):
    q = q.strip()
    url = 'http://dict-mobile.iciba.com/interface/index.php?c=word&m=getsuggest&nums=5&client=6&uid=0&is_need_mean=1&word=%s' % q
    try:
        r = requests.get(url, headers=headers)
        res = r.json()
        fb = Feedback()
        for msg in res['message']:
            means = msg['means']
            if not means:
                kwargs = {
                    'title': msg['key'],
                    'autocomplete': '> %s' % msg['key'],
                    'valid': False,
                }
                fb.addItem(**kwargs)
                continue

            for mean in means:
                if mean['part']:
                    subtitle = mean['part'] + ' ' + '; '.join(mean['means'])
                else:
                    subtitle = '; '.join(mean['means'])
                kwargs = {
                    'title': msg['key'],
                    'subtitle': subtitle,
                    'arg': 'http://www.iciba.com/%s' % q,
                    'autocomplete': '> %s' % msg['key'],
                    'valid': False,
                }
                fb.addItem(**kwargs)
        fb.output()
    except:
        pass
Exemplo n.º 5
0
    def __init__(self):
        self.service = service
        self.query_word =''
        self.feedback = Feedback()

        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''
Exemplo n.º 6
0
def search(word):
    feedback = Feedback()
    data = _api(SEARCH_API, params={'word': word})
    if data is None:
        return

    word = data['content']
    pron = data['pron']
    title = "%s [%s]" % (word, pron)
    feedback.addItem(title=title, arg=word)
    for chinese in data['definition'].decode("utf-8").split('\n'):
        feedback.addItem(title=chinese, arg=word)

    if 'en_definitions' in data and data['en_definitions']:
        for type_ in data['en_definitions']:
            for line in data['en_definitions'][type_]:
                title = type_ + ', ' + line
                if not title:
                    continue
                feedback.addItem(title=title, arg=word)
    feedback.output()
Exemplo n.º 7
0
def run(q, xq_a_token):
    q = str(q).strip()
    if not q:
        return

    try:
        headers = {
            'Host':
            'xueqiu.com',
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36',
        }

        url = 'https://xueqiu.com/v4/stock/quote.json?code=%s' % q
        cookies = {
            'xq_a_token': xq_a_token,
        }
        r = requests.get(url, headers=headers, cookies=cookies)
        res = r.json()
        data = res[q]
        title = '当前价:{current} 涨:{change} 涨幅:{percentage}%'.format(**data)
        link = 'https://xueqiu.com/S/%s' % q
        subtitle = '{name} 昨收:{last_close} 今开:{open} 最高:{high} 最低:{low}'.format(
            **data)

        kwargs = {'title': title, 'subtitle': subtitle, 'arg': link}

        fb = Feedback()
        fb.addItem(**kwargs)
        fb.output()
    except Exception, e:
        print 'EXCEPT:', e
        pass
Exemplo n.º 8
0
def get_phonetic_symbols(word, headers):
    word = word.strip()
    url = 'http://www.iciba.com/index.php?a=getWordMean&c=search&list=1&word=%s' % word
    try:
        r = requests.get(url, headers=headers)
        res = r.json()
        fb = Feedback()
        for symbol in res['baesInfo']['symbols']:
            means = symbol['parts']
            for mean in means:
                if mean['part']:
                    subtitle = mean['part'] + ' ' + '; '.join(mean['means'])
                else:
                    subtitle = '; '.join(mean['means'])
                if 'ph_en' in symbol and 'ph_am' in symbol:
                    title = '{word} 英:[{en}] 美:[{am}]'.format(
                        word=word, en=symbol['ph_en'], am=symbol['ph_am'])
                elif 'word_symbol' in symbol:
                    title = '{word} 拼音:[{word_symbol}]'.format(
                        word=word, word_symbol=symbol['word_symbol'])
                kwargs = {
                    'title': title,
                    'subtitle': subtitle,
                    'arg': 'http://www.iciba.com/%s' % word,
                }
                fb.addItem(**kwargs)
        fb.output()
    except:
        pass
Exemplo n.º 9
0
def get_phonetic_symbols_new(word, headers):
    word = word.strip()
    # url = "https://dict.iciba.com/dictionary/word/query/web?client=6&key=1000006&timestamp=1628233093905&word=hello&signature=0a78228c59344a8c368f20d47fe6fd2b"
    data = [
        ("client", "6"),
        ("key", "1000006"),
        ("timestamp", str(int(time.time() * 1000))),
        ("word", word),
    ]
    url = "https://dict.iciba.com/dictionary/word/query/web"

    to_sign = url[len("https:"):].replace("//dict.iciba.com", "")
    for k, v in data:
        to_sign += v
    to_sign += "7ece94d9f9c202b0d2ec557dg4r9bc"
    sign = hashlib.md5(to_sign.encode('utf8')).hexdigest()
    data.append(("signature", sign))
    url += "?"
    for k, v in data:
        url += "{k}={v}&".format(k=k, v=v)
    url.rstrip("&")
    r = requests.get(url, headers=headers)
    res = r.json()

    try:
        fb = Feedback()
        msg = res["message"]
        for symbol in msg['baesInfo']['symbols']:
            means = symbol['parts']
            for mean in means:
                if mean['part']:
                    subtitle = mean['part'] + ' ' + '; '.join(mean['means'])
                else:
                    subtitle = '; '.join(mean['means'])
                if 'ph_en' in symbol and 'ph_am' in symbol:
                    title = '{word} 英:[{en}] 美:[{am}]'.format(
                        word=word, en=symbol['ph_en'], am=symbol['ph_am'])
                elif 'word_symbol' in symbol:
                    title = '{word} 拼音:[{word_symbol}]'.format(
                        word=word, word_symbol=symbol['word_symbol'])
                kwargs = {
                    'title': title,
                    'subtitle': subtitle,
                    'arg': 'http://www.iciba.com/%s' % word,
                }
                fb.addItem(**kwargs)
        fb.output()
    except Exception as ex:
        print("EXCEPT:", ex)
Exemplo n.º 10
0
def run(q):
    import requests
    from BeautifulSoup import BeautifulSoup as Soup
    from soupselect import select
    from alfred.feedback import Feedback

    fb = Feedback()

    q = q.strip()
    url = 'http://m.lianjia.com/bj/chengjiao/rs%s' % q
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
        'Referer': 'https://m.lianjia.com/bj/sold/search/',
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch, br',
        'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,zh-TW;q=0.2',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
    }
    r = requests.get(url, headers=headers)
    r.encoding = 'utf8'
    content = r.text
    soup = Soup(content)
    items = select(soup, 'ul.lists li.pictext')
    for item in items:
        try:
            deal_date = select(item, 'div.item_date')[0].text
            title = select(item, 'div.item_main')[0].text
            desc = select(item, 'span.q_oriention')[0].text
            price = select(item, 'span.price_total')[0].text
            unit_price = select(item, 'span.unit_price')[0].text
            link = select(item, 'a.flexbox')[0]['href']
            kwargs = {
                'title': title + ' ' + price + ' ' + unit_price,
                'subtitle': deal_date + '成交' + ' ' + '位置:' + desc,
                'arg': 'https://m.lianjia.com' + link,
            }
            fb.addItem(**kwargs)
        except:
            pass

    fb.output()
Exemplo n.º 11
0
            return cache

    options = config['options'] if config else {}
    dict_name = cndict.get_full_name(dictionary)
    options = options.get(dict_name, {})

    result = cndict.lookup(dictionary, word, **options)
    if result:
        result = [item.decode('utf-8') for item in result]
        if enable_cache:
            dict_cache.set(cache_name, result, cache_expire)
        return result


alfred = Alfred()
feedback = Feedback()
plist = Plist()
plist.read(os.path.abspath('./info.plist'))
dict_cache = Cache(os.path.join(alfred.get_cache_dir(), plist.get_bundleid()))

try:
    config_data = open(os.path.abspath('./config.json')).read()
    config = json.loads(re.sub(r'//.*', '', config_data))
except:
    config = {}

sys.argv = [arg for arg in sys.argv if arg != '']
argc = len(sys.argv)
if argc == 1:
    feedback.add_item(title=u'Dict - Lookup Word',
                      subtitle=u'Format: "word @ dict". Available dicts are "nj", "ld", "yd", "cb", "by", "hc".',
Exemplo n.º 12
0
 def __init__(self):
     self.service = services['qq']
     self.query_word =''
     self.feedback = Feedback()
Exemplo n.º 13
0
 def __init__(self):
     self.feedback = Feedback()
Exemplo n.º 14
0
class ShanbayDict():
    def __init__(self):
        self.feedback = Feedback()

    def check_token(self, isexit=True):
        if not self.read_token():
            self.addItem(title='授权登陆扇贝',
                         subtitle='授权后才可以将单词添加到词库',
                         arg='need_auth')
            if isexit:
                self.output()
                sys.exit()
            return False
        return True

    def read_token(self):
        if os.path.isfile(token_file):
            token_json = json.loads(open(token_file).read().strip())
            #已过期
            if token_json and token_json['timestamp'] + token_json[
                    'expires_in'] < int(time.time()):
                return ''
            return token_json['access_token']
        return ''

    def parse(self, voc):
        if (voc):
            word = voc['content']
            # 发音
            pron = voc['pron']

            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition'].decode("utf-8")
            subtitle = subtitle.replace("\n", '').replace('&', '')

            self.addItem(title=title, subtitle=subtitle, arg=word)
            self.check_token(False)

            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type + ', ' + line
                        self.addItem(title=title, arg=word)
        else:
            self.addItem(title='no results')

    def query_voc(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return None
        self.query_word = word

        url = 'https://api.shanbay.com/bdc/search/?word=' + word
        try:
            r = urllib2.urlopen(url).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                return res['data']
            else:
                return None
        except:
            return None

    def query(self, word):
        voc = self.query_voc(word)
        if voc:
            self.parse(voc)
        else:
            self.addItem(title='word not exists')

    def open_word(self, word):
        voc = self.query_voc(word)
        if voc:
            word_url = 'http://www.shanbay.com/bdc/vocabulary/%d/' % (
                voc['id'])
            os.system('open ' + word_url)
            return True
        else:
            print 'word not exists'

    def open_oauth(self):
        auth_url = 'https://api.shanbay.com/oauth2/authorize/?client_id=00eef0bf7a879381c08b\&response_type=code\&state=123'
        os.system('open ' + auth_url)
        return True

    def get_token(self, code):
        url = 'http://sbalfred.sinaapp.com/token'
        data = urllib.urlencode({'code': code})
        req = urllib2.Request(url, data)

        try:
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if 'error' in res:
                print '授权失败: ' + res['error']
                sys.exit()

            #save json to local
            f = open(token_file, 'w')
            f.write(r)
            f.close()
            os.system('open https://sbalfred.sinaapp.com/oauth_success')
            print '授权成功,现在可以使用添加单词或例句了'
        except:
            print '请求错误'

        return True

    def add(self, word):
        if word == 'need_auth':
            self.open_oauth()
            return False

        hastoken = self.check_token(0)
        if not hastoken:
            self.open_oauth()
            print '请先授权登陆扇贝'
            sys.exit()

        voc = self.query_voc(word)
        if not voc:
            print 'word not exists'
            return False

        url = 'https://api.shanbay.com/bdc/learning/?access_token=' + self.read_token(
        )
        try:
            data = urllib.urlencode({'id': voc['id']})
            req = urllib2.Request(url, data)
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                #通知内容会换行,这里直接返回全部字符
                print '"' + word + '" 添加成功'
            else:
                print 'add fail'
        except:
            print 'request fail'

    def examples(self, word):
        self.check_token()
        voc = self.query_voc(word)
        if not voc:
            self.addItem(title='word not exists')
            return False

        url = 'https://api.shanbay.com/bdc/example/?vocabulary_id=%d&type=%s&access_token=%s' \
            % (voc['id'], '', self.read_token())
        try:
            r = urllib2.urlopen(url).read()
            res = json.loads(r)
        except:
            self.addItem(title='request fail')
            return False

        if res['status_code'] == 0:
            for s in res['data']:
                title = s['annotation']
                title = title.replace('<vocab>', '[')
                title = title.replace('</vocab>', ']')
                self.addItem(title=title,
                             subtitle=s['translation'],
                             arg=str(s['id']))
                #print s['annotation'] + s['translation'] + "\n"
        else:
            self.addItem(title='request error')

    def add_example(self, example_id):
        hastoken = self.check_token(0)
        if not hastoken:
            self.open_oauth()
            print '请先授权登陆扇贝'
            sys.exit()

        url = 'https://api.shanbay.com/bdc/learning_example/?access_token=' + self.read_token(
        )
        try:
            data = urllib.urlencode({'example_id': example_id})
            req = urllib2.Request(url, data)
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                print '例句收藏成功'
            else:
                print 'add fail'
        except:
            print 'request fail'

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(title=self.query_word,
                         subtitle='Sorry, no result.',
                         arg=self.query_word)
        print(self.feedback.get(unescape=True))
Exemplo n.º 15
0
 def __init__(self):
     self.feedback = Feedback()
Exemplo n.º 16
0
class ShanbayDict():
    def __init__(self):
        self.feedback = Feedback()

    def check_token(self, isexit = True):
        if not self.read_token():
            self.addItem(title = '授权登陆扇贝', subtitle = '授权后才可以将单词添加到词库', arg = 'need_auth')
            if isexit:
                self.output()
                sys.exit()
            return False
        return True

    def read_token(self):
        if os.path.isfile(token_file):
            token_json = json.loads(open(token_file).read().strip())
            #已过期
            if token_json and token_json['timestamp'] + token_json['expires_in'] < int(time.time()):
                return ''
            return token_json['access_token']
        return ''

    def parse(self, voc):
        if(voc):
            word = voc['content']
            # 发音
            pron = voc['pron']

            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition'].decode("utf-8")
            subtitle = subtitle.replace("\n", '').replace('&', '')

            self.addItem(title = title, subtitle = subtitle, arg = word)
            self.check_token(False)

            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type+', '+line
                        self.addItem(title = title, arg = word)
        else:
            self.addItem(title='no results')

    def query_voc(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return None
        self.query_word = word

        url = 'https://api.shanbay.com/bdc/search/?word='+word
        try:
            r = urllib2.urlopen(url).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                return res['data']
            else:
                return None
        except:
            return None

    def query(self, word):
        voc = self.query_voc(word)
        if voc:
            self.parse(voc)
        else:
            self.addItem(title='word not exists')

    def open_word(self, word):
        voc = self.query_voc(word)
        if voc:
            word_url = 'http://www.shanbay.com/bdc/vocabulary/%d/' % (voc['id'])
            os.system('open ' + word_url)
            return True
        else:
            print 'word not exists'

    def open_oauth(self):
        auth_url = 'https://api.shanbay.com/oauth2/authorize/?client_id=00eef0bf7a879381c08b\&response_type=code\&state=123'
        os.system('open ' + auth_url)
        return True

    def get_token(self, code):
        url = 'http://sbalfred.sinaapp.com/token'
        data = urllib.urlencode({'code':code})
        req = urllib2.Request(url, data)

        try:
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if 'error' in res:
                print '授权失败: ' + res['error']
                sys.exit()

            #save json to local
            f = open(token_file, 'w')
            f.write(r)
            f.close()
            os.system('open https://sbalfred.sinaapp.com/oauth_success')
            print '授权成功,现在可以使用添加单词或例句了'
        except:
            print '请求错误'

        return True

    def add(self, word):
        if word == 'need_auth':
            self.open_oauth()
            return False

        hastoken = self.check_token(0)
        if not hastoken:
            self.open_oauth()
            print '请先授权登陆扇贝'
            sys.exit()

        voc = self.query_voc(word)
        if not voc:
            print 'word not exists'
            return False

        url = 'https://api.shanbay.com/bdc/learning/?access_token='+self.read_token()
        try:
            data = urllib.urlencode({'id':voc['id']})
            req = urllib2.Request(url, data)
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                #通知内容会换行,这里直接返回全部字符
                print '"'+word+'" 添加成功'
            else:
                print 'add fail'
        except:
            print 'request fail'

    def examples(self, word):
        self.check_token()
        voc = self.query_voc(word)
        if not voc:
            self.addItem(title='word not exists')
            return False

        url = 'https://api.shanbay.com/bdc/example/?vocabulary_id=%d&type=%s&access_token=%s' \
            % (voc['id'], '', self.read_token())
        try:
            r = urllib2.urlopen(url).read()
            res = json.loads(r)
        except:
            self.addItem(title = 'request fail')
            return False

        if res['status_code'] == 0:
            for s in res['data']:
                title = s['annotation']
                title = title.replace('<vocab>', '[')
                title = title.replace('</vocab>', ']')
                self.addItem(title = title, subtitle = s['translation'], arg = str(s['id']))
                #print s['annotation'] + s['translation'] + "\n"
        else:
            self.addItem(title = 'request error')

    def add_example(self, example_id):
        hastoken = self.check_token(0)
        if not hastoken:
            self.open_oauth()
            print '请先授权登陆扇贝'
            sys.exit()

        url = 'https://api.shanbay.com/bdc/learning_example/?access_token='+self.read_token()
        try:
            data = urllib.urlencode({'example_id':example_id})
            req = urllib2.Request(url, data)
            r = urllib2.urlopen(req).read()
            res = json.loads(r)
            if res['status_code'] == 0:
                print '例句收藏成功'
            else:
                print 'add fail'
        except:
            print 'request fail'

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(
                title       = self.query_word,
                subtitle    = 'Sorry, no result.',
                arg         = self.query_word )
        print(self.feedback.get(unescape = True))
Exemplo n.º 17
0
class ShanbayDict():
    def __init__(self):
        self.service = service
        self.query_word = ''
        self.feedback = Feedback()

        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''

    def get_csrfmiddlewaretoken(self):
        page = requests.get(loginurl).text
        script = html.fromstring(page).xpath(
            "(//input[@name='csrfmiddlewaretoken']/@value)[1]")[0]
        return script

    def login(self):

        csrftoken = self.get_csrfmiddlewaretoken()

        postdata = {}
        postdata['csrfmiddlewaretoken'] = csrftoken
        postdata['username'] = username
        postdata['password'] = pwd
        postdata['login'] = ''
        postdata['continue'] = 'home'
        postdata['u'] = 1
        postdata['next'] = '/review/new/'
        headers = {
            'User-Agent':
            'Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0',
            'Host': 'www.shanbay.com',
            'Origin': 'http://www.shanbay.com',
            'Referer': 'http://www.shanbay.com/accounts/login/',
            'Cookie': 'csrftoken=' + csrftoken + ';csrftoken=' + csrftoken +
            ';sessionid=f7df88e25d184e487df6ddc6a88caafb;',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'UTF-8,*;q=0.5',
            'Accept-Encoding': 'gzip,deflate,sdc',
            'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        #r = requests.post(url, data=json.dumps(postdata), headers=headers)
        r = requests.post(loginurl, data=postdata, headers=headers)
        #print r.status_code
        #print r.headers
        self.cookies = r.cookies
        return True if r.status_code == 200 else False

    def fetch(self, word):
        islogin = self.login()
        if islogin == False:
            print '登陆失败'
            return

        url = self.service + word

        try:
            r = requests.get(url, cookies=self.cookies)
            res = json.loads(r.text)
        except:
            return {}
        return res

    def parse(self, data):

        if (data['voc']):
            voc = data['voc']
            word = voc['content']

            # 发音
            pron = voc['pron']
            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition']
            self.addItem(title=title, subtitle=subtitle, arg=word)
            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type + ', ' + line
                        if not title:
                            continue
                        self.addItem(title=title, arg=word)
        else:
            self.addItem(title='no results')

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse(self.fetch(word))

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(title=self.query_word,
                         subtitle='Sorry, no result.',
                         arg=self.query_word)
        print(self.feedback.get(unescape=True))
Exemplo n.º 18
0
 def __init__(self):
     self.service = services['qq']
     self.query_word = ''
     self.feedback = Feedback()
Exemplo n.º 19
0
class ShanbayDict():
    def __init__(self):
        self.service = service
        self.query_word =''
        self.feedback = Feedback()

        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''

    def get_csrfmiddlewaretoken(self):
        page = requests.get(loginurl).text
        script = html.fromstring(page).xpath("(//input[@name='csrfmiddlewaretoken']/@value)[1]")[0]
        return script

    def login(self):

        csrftoken = self.get_csrfmiddlewaretoken()

        postdata = {}
        postdata['csrfmiddlewaretoken'] = csrftoken
        postdata['username'] = username
        postdata['password'] = pwd
        postdata['login'] = ''
        postdata['continue'] = 'home'
        postdata['u'] = 1
        postdata['next'] = '/review/new/'
        headers = {
                    'User-Agent':'Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0',
                    'Host':'www.shanbay.com',
                    'Origin':'http://www.shanbay.com',
                    'Referer':'http://www.shanbay.com/accounts/login/',
                    'Cookie':'csrftoken='+csrftoken+';csrftoken='+csrftoken+';sessionid=f7df88e25d184e487df6ddc6a88caafb;',
                    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'Accept-Charset':'UTF-8,*;q=0.5',
                    'Accept-Encoding':'gzip,deflate,sdc',
                    'Accept-Language':'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4',
                    'Cache-Control':'max-age=0',
                    'Connection':'keep-alive',
                    'Content-Type':'application/x-www-form-urlencoded'
                  }

        #r = requests.post(url, data=json.dumps(postdata), headers=headers)
        r = requests.post(loginurl, data=postdata, headers=headers)
        #print r.status_code
        #print r.headers
        self.cookies = r.cookies
        return True if r.status_code == 200 else False


    def fetch(self, word):
        islogin = self.login()
        if islogin == False:
            print '登陆失败'
            return

        url = self.service+word

        try:
            r = requests.get(url, cookies = self.cookies)
            res = json.loads(r.text)
        except:
            return {}
        return res

    def parse(self, data):

        if(data['voc']):
            voc = data['voc']
            word = voc['content']

            # 发音
            pron = voc['pron']
            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition']
            self.addItem(title = title, subtitle = subtitle, arg = word)
            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type+', '+line
                        if not title:
                            continue
                        self.addItem(title = title, arg = word)
        else:
            self.addItem(title='no results')

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse( self.fetch(word) )

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(
                title       = self.query_word, 
                subtitle    = 'Sorry, no result.', 
                arg         = self.query_word )
        print(self.feedback.get(unescape = True))
Exemplo n.º 20
0
class ShanbayDict():
    def __init__(self):
        self.service = service
        self.query_word = ''
        self.feedback = Feedback()
        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''

    def login(self):

        headers = {
            'Host':
            host,
            'User-Agent': (' Mozilla/5.0 (Windows NT 6.2; rv:23.0) Gecko' +
                           '/20100101 Firefox/23.0'),
        }

        # 首先访问一次网站,获取 cookies
        r_first_vist = requests.get(loginurl, headers=headers, stream=True)
        # 判断 HTTP 状态码是否是 200
        if r_first_vist.status_code != requests.codes.ok:
            raise LoginException
        # 获取 cookies 信息
        cookies_first_vist = r_first_vist.cookies.get_dict()

        # 登陆post操作相关信息
        url_post = loginurl
        # 获取csrftoken
        token = cookies_first_vist.get('csrftoken')
        # post请求的headers
        headers_post = copy.deepcopy(headers)
        headers_post.update({
            'Refere':
            loginurl,
            'Content-Type':
            'application/x-www-form-urlencoded',
        })
        cookies_post = cookies_first_vist
        # post 提交的内容
        data_post = {
            'csrfmiddlewaretoken': token,  # csrf
            'username': username,  # 用户名
            'password': pwd,  # 密码
            'login': '',
            'continue': 'home',
            'u': 1,
            'next': '',
        }

        # 提交登录表单同时提交第一次访问网站时生成的 cookies
        r_login = requests.post(url_post,
                                headers=headers_post,
                                cookies=cookies_post,
                                data=data_post,
                                allow_redirects=False,
                                stream=True)

        self.cookies = r_login.cookies
        # print r_login.url
        if r_login.status_code == requests.codes.found:
            # 返回登录成功后生成的 cookies
            self.cookies = r_login.cookies
            return True
        else:
            raise LoginException

    def fetch(self, word):
        islogin = self.login()

        if islogin == False:
            print '登陆失败'
            return

        url = self.service + word

        try:
            r = requests.get(url, cookies=self.cookies)
            res = json.loads(r.text)
        except:
            return {}
        return res

    def parse(self, data):

        if (data['voc']):
            voc = data['voc']
            word = voc['content']

            # 发音
            pron = voc['pron']
            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition']
            self.addItem(title=title, subtitle=subtitle, arg=word)
            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type + ', ' + line
                        if not title:
                            continue
                        self.addItem(title=title, arg=word)
        else:
            self.addItem(title='no results')

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse(self.fetch(word))

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(title=self.query_word,
                         subtitle='Sorry, no result.',
                         arg=self.query_word)
        print(self.feedback.get(unescape=True))
Exemplo n.º 21
0
class ShanbayDict():
    def __init__(self):
        self.service = service
        self.query_word =''
        self.feedback = Feedback()
        # 从字典中安全的取出值
        self.save_get_dict_value = lambda d, k: d[k] if d.has_key(k) else ''

    def login(self):

        headers = {
        'Host': host,
        'User-Agent': (' Mozilla/5.0 (Windows NT 6.2; rv:23.0) Gecko'
                       + '/20100101 Firefox/23.0'),
        }

        # 首先访问一次网站,获取 cookies
        r_first_vist = requests.get(loginurl, headers=headers,
                                    stream=True)
        # 判断 HTTP 状态码是否是 200
        if r_first_vist.status_code != requests.codes.ok:
            raise LoginException
        # 获取 cookies 信息
        cookies_first_vist = r_first_vist.cookies.get_dict()

        # 登陆post操作相关信息
        url_post = loginurl
        # 获取csrftoken
        token = cookies_first_vist.get('csrftoken')
        # post请求的headers
        headers_post = copy.deepcopy(headers)
        headers_post.update({
            'Refere': loginurl,
            'Content-Type': 'application/x-www-form-urlencoded',
        })
        cookies_post = cookies_first_vist
        # post 提交的内容
        data_post = {
            'csrfmiddlewaretoken': token,  # csrf
            'username': username,  # 用户名
            'password': pwd,  # 密码
            'login': '',
            'continue': 'home',
            'u': 1,
            'next': '',
        }

        # 提交登录表单同时提交第一次访问网站时生成的 cookies
        r_login = requests.post(url_post, headers=headers_post,
                                cookies=cookies_post, data=data_post,
                                allow_redirects=False, stream=True)
        
        self.cookies = r_login.cookies
         # print r_login.url
        if r_login.status_code == requests.codes.found:
            # 返回登录成功后生成的 cookies
            self.cookies = r_login.cookies
            return True
        else:
            raise LoginException

    def fetch(self, word):
        islogin = self.login()

        if islogin == False:
            print '登陆失败'
            return

        url = self.service+word

        try:
            r = requests.get(url, cookies = self.cookies)
            res = json.loads(r.text)
        except:
            return {}
        return res

    def parse(self, data):

        if(data['voc']):
            voc = data['voc']
            word = voc['content']

            # 发音
            pron = voc['pron']
            title = "%s [%s]" % (word, pron)
            subtitle = voc['definition']
            self.addItem(title = title, subtitle = subtitle, arg = word)
            # 解释
            if voc.has_key('en_definitions') and voc['en_definitions']:
                for type in voc['en_definitions']:
                    for line in voc['en_definitions'][type]:
                        title = type+', '+line
                        if not title:
                            continue
                        self.addItem(title = title, arg = word)
        else:
            self.addItem(title='no results')

    def query(self, word):
        if not word or not isinstance(word, (str, unicode)):
            return
        self.query_word = word
        self.parse( self.fetch(word) )

    def addItem(self, **kwargs):
        self.feedback.addItem(**kwargs)

    def output(self):
        if self.feedback.isEmpty():
            self.addItem(
                title       = self.query_word, 
                subtitle    = 'Sorry, no result.', 
                arg         = self.query_word )
        print(self.feedback.get(unescape = True))
Exemplo n.º 22
0
def list(devices=None):
    if devices is None:
        devices = get_devices()
    feedback = Feedback()
    if len(devices) == 0:
        feedback.addItem(title="No device found")
    for device in devices:
        command = device.get("id")
        feedback.addItem(title=device.get("name"),
                         subtitle=command,
                         arg=command)
    feedback.addVariable(name="fromDevices", value="1")
    feedback.addVariable(name="deviceNum", value=str(len(devices)))
    if len(sys.argv) > 1 and len(sys.argv[1].strip()) > 0:
        feedback.addVariable(name="originQuery", value=sys.argv[1].strip())
    print feedback.get(unescape=True)