當前位置: 首頁>>代碼示例>>Python>>正文


Python Scrobbler.handshake方法代碼示例

本文整理匯總了Python中scrobbler.Scrobbler.handshake方法的典型用法代碼示例。如果您正苦於以下問題:Python Scrobbler.handshake方法的具體用法?Python Scrobbler.handshake怎麽用?Python Scrobbler.handshake使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在scrobbler.Scrobbler的用法示例。


在下文中一共展示了Scrobbler.handshake方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from scrobbler import Scrobbler [as 別名]
# 或者: from scrobbler.Scrobbler import handshake [as 別名]
class Doubanfm:
    def __init__(self):
        self._load_config()
        self.douban = Douban(self.email, self.password, self.user_id, self.expire, self.token, self.user_name)
        self.player = Player()
        self.current_channel = 0
        self.current_song = None
        self.current_play_list = None
        self.get_channels()
        
        self.palette = [('selected', 'bold', 'default'),
                        ('title', 'yellow', 'default')]
        self.selected_button = None
        self.main_loop = None
        self.song_change_alarm = None
        
        if self.scrobbling:
            self.scrobbler = Scrobbler(self.last_fm_username, self.last_fm_password)
            r =  self.scrobbler.handshake()
            if r:
                print("Last.FM logged in.")
            else:
                print("Last.FM login failed")
        if self.douban_account:
            r, err = self.douban.do_login()
            if r:
                print("Douban logged in.")
                self._save_cache()
            else:
                print("Douban login failed: " + err)
        
    def _load_config(self):
        self.email = None
        self.password = None
        self.user_id = None
        self.expire = None
        self.token = None
        self.user_name = None
        self.lasf_fm_username = None
        self.last_fm_password = None
        self.scrobbling = True
        self.douban_account = True
        self.channels = None
        
        config = None
        token = None
        try:
            f = open('config.json', 'r')
            config = json.load(f)
            
            self.email = config['email']
            self.password = config['password']
            
        except (KeyError,ValueError):
            self.douban_account = False
            print("Douban account not found. Personal FM disabled.")
        
        try:
            if config == None:
                raise ValueError 
            self.last_fm_username = config['last_fm_username']
            self.last_fm_password = config['last_fm_password']
        except (KeyError,ValueError):
            self.scrobbling = False
            print("Last.fm account not found. Scrobbling disabled.")
            
        try:
            f = open('channels.json', 'r')
            self.channels = json.load(f)
            print("Load channel file.")
        except FileNotFoundError:
            print("Channels file not found.")
         
    def _save_cache(self):
        f = None
        try:
            f = open('cache.json', 'w')
            f2 = open('channels.json', 'w')
            json.dump({
                'user_name': self.douban.user_name,
                'user_id': self.douban.user_id,
                'expire': self.douban.expire,
                'token': self.douban.token
            }, f)
            json.dump(self.channels, f2)
        except IOError:
            raise Exception("Unable to write cache file")
            
    def get_channels(self):
        if self.channels is None:
            self.channels = self.douban.get_channels()
        return self.channels
    
    def _choose_channel(self, channel):
        self.current_channel = channel
        self.current_play_list = deque(self.douban.get_new_play_list(self.current_channel))
        
    def _play_track(self):
        _song = self.current_play_list.popleft()                
        self.current_song = Song(_song)
#.........這裏部分代碼省略.........
開發者ID:beanmoon,項目名稱:pyfm,代碼行數:103,代碼來源:pyfm.py

示例2: Doubanfm

# 需要導入模塊: from scrobbler import Scrobbler [as 別名]
# 或者: from scrobbler.Scrobbler import handshake [as 別名]
class Doubanfm(object):
    def __init__(self):
        self.login_data = {}
        self.lastfm = True  # lastfm 登陸

    def init_login(self):
        print LOGO
        self.douban_login()  # 登陸
        self.lastfm_login()  # 登陸 last.fm
        print '\033[31m♥\033[0m Get channels ',
        self.get_channels()  # 獲取頻道列表
        print '[\033[32m OK \033[0m]'
        # 存儲的default_channel是行數而不是真正發送數據的channel_id
        # 這裏需要進行轉化一下
        self.set_channel(self.default_channel)
        print '\033[31m♥\033[0m Check PRO ',
        # self.is_pro()
        print '[\033[32m OK \033[0m]'

    def win_login(self):
        '''登陸界麵'''
        email = raw_input('Email: ')
        password = getpass.getpass('Password: ')
        return email, password

    def lastfm_login(self):
        '''Last.fm登陸'''
        # username & password
        self.last_fm_username = \
            self.login_data['last_fm_username'] if 'last_fm_username' in self.login_data\
            else None
        self.last_fm_password = \
            self.login_data['last_fm_password'] if 'last_fm_password' in self.login_data\
            else None
        if len(sys.argv) > 1 and sys.argv[1] == 'last.fm':
            from hashlib import md5
            username = raw_input('Last.fm username: ') or None
            password = getpass.getpass('Last.fm password :') or None
            if username and password:
                self.last_fm_username = username
                self.last_fm_password = md5(password).hexdigest()
            with open(config.PATH_TOKEN, 'r') as f:
                data = pickle.load(f)
            with open(config.PATH_TOKEN, 'w') as f:
                data['last_fm_username'] = username
                data['last_fm_password'] = self.last_fm_password
                pickle.dump(data, f)

        # login
        if self.lastfm and self.last_fm_username and self.last_fm_password:
            self.scrobbler = Scrobbler(
                self.last_fm_username, self.last_fm_password)
            r, err = self.scrobbler.handshake()
            if r:
                logger.info("Last.fm login succeeds!")
                print '\033[31m♥\033[0m Last.fm logged in: %s' % self.last_fm_username
            else:
                logger.error("Last.fm login fails: " + err)
                self.lastfm = False
        else:
            self.lastfm = False

    def __last_fm_account_required(func):
        '''裝飾器,用於需要登錄Last.fm後才能使用的接口'''
        @wraps(func)
        def wrapper(self, *args, **kwds):
            if not self.lastfm:
                return
            # Disable pylint callable check due to pylint's incompability
            # with using a class method as decorator.
            # Pylint will consider func as "self"
            return func(self, *args, **kwds)    # pylint: disable=not-callable
        return wrapper

    @__last_fm_account_required
    def submit_current_song(self):
        '''提交播放過的曲目'''
        # Submit the track if total playback time of the track > 30s
        if self.playingsong['length'] > 30:
            self.scrobbler.submit(
                self.playingsong['artist'],
                self.playingsong['title'],
                self.playingsong['albumtitle'],
                self.playingsong['length']
            )

    @__last_fm_account_required
    def scrobble_now_playing(self):
        '''提交當前正在播放曲目'''
        self.scrobbler.now_playing(
            self.playingsong['artist'],
            self.playingsong['title'],
            self.playingsong['albumtitle'],
            self.playingsong['length']
        )

    def douban_login(self):
        '''登陸douban.fm獲取token'''
        if os.path.exists(config.PATH_TOKEN):
            # 已登陸
#.........這裏部分代碼省略.........
開發者ID:NCZkevin,項目名稱:douban.fm,代碼行數:103,代碼來源:douban_token.py

示例3: __init__

# 需要導入模塊: from scrobbler import Scrobbler [as 別名]
# 或者: from scrobbler.Scrobbler import handshake [as 別名]
class Doubanfm:

    def __init__(self):
        self.email = None
        self.password = None
        self.user_name = None
        self.user_id = None
        self.expire = None
        self.token = None
        self.cookies = None
        
        self.last_fm_username = None
        self.last_fm_password = None
        self.scrobbling = True
        self.douban_account = True
        self.channels = None
        
        # Set up config
        try:
            arg = sys.argv[1]
            self._do_config()
        except IndexError:
            self._load_config()
        
        # Init API tools
        self.douban = Douban(
            self.email, self.password, self.user_id, self.expire, self.token, self.user_name, self.cookies)
        self.player = Player()
        self.current_channel = 0
        self.current_song = None
        self.current_play_list = None

        # Init terminal ui
        self.palette = [('selected', 'bold', 'default'),
                        ('title', 'yellow', 'default')]
        self.selected_button = None
        self.main_loop = None
        self.song_change_alarm = None
        
        # Try to login
        if self.last_fm_username is None or self.last_fm_username == "":
            self.scrobbling = False
        if (self.email is None or self.email == "") and self.cookies == None:
            self.douban_account = False
            
        if self.scrobbling:
            self.scrobbler = Scrobbler(
                self.last_fm_username, self.last_fm_password)
            r, err = self.scrobbler.handshake()
            if r:
                print("Last.FM 已登陸")
            else:
                print("Last.FM 登錄失敗: " + err)
        if self.douban_account:
            r, err = self.douban.do_login()
            if r:
                print("Douban 已登陸")
            else:
                print("Douban 登錄失敗: " + err)
        self.get_channels()
        self._save_cache()

    def _do_config(self):
        self.email = input('豆瓣賬戶 (Email地址): ') or None
        self.password = getpass('豆瓣密碼: ') or None
        self.last_fm_username = input('Last.fm 用戶名: ') or None
        password = getpass('Last.fm 密碼: ') or None
        self.last_fm_password = md5(password.encode('utf-8')).hexdigest() 
                
    def _load_config(self):
        try:
            f = open('channels.json', 'r')
            self.channels = deque(json.load(f))
            logger.debug("Load channel file.")
        except FileNotFoundError:
            logger.debug("Channels file not found.")
            
        try: 
            f = open('cache.json', 'r')
            cache = json.load(f)
            try:
                self.user_name = cache['user_name']
                self.user_id = cache['user_id']
                self.expire = cache['expire']
                self.token = cache['token']
                self.cookies = cache['cookies']
            except (KeyError, ValueError):
                self.douban_account = False
            try:
                self.last_fm_username = cache['last_fm_username']
                self.last_fm_password = cache['last_fm_password']
            except (KeyError, ValueError):
                self.scrobbling = False
    
        except FileNotFoundError:
            logger.debug("Cache file not found.")

    def _save_cache(self):
        f = None
        try:
#.........這裏部分代碼省略.........
開發者ID:JamesTing,項目名稱:pyfm,代碼行數:103,代碼來源:pyfm.py

示例4: Doubanfm

# 需要導入模塊: from scrobbler import Scrobbler [as 別名]
# 或者: from scrobbler.Scrobbler import handshake [as 別名]
class Doubanfm(object):
    def __init__(self):
        self.login_data = {}
        self.lastfm = True  # lastfm 登陸

    def init_login(self):
        print '''
        ──╔╗─────╔╗────────╔═╗
        ──║║─────║║────────║╔╝
        ╔═╝╠══╦╗╔╣╚═╦══╦═╗╔╝╚╦╗╔╗
        ║╔╗║╔╗║║║║╔╗║╔╗║╔╗╬╗╔╣╚╝║
        ║╚╝║╚╝║╚╝║╚╝║╔╗║║║╠╣║║║║║
        ╚══╩══╩══╩══╩╝╚╩╝╚╩╩╝╚╩╩╝

        '''
        self.douban_login()  # 登陸
        self.login_lastfm()  # 登陸 last.fm
        print '\033[31m♥\033[0m Get channels ',
        # self.get_channels()  # 獲取頻道列表
        print '[\033[32m OK \033[0m]'
        # self.get_channellines()  # 重構列表用以顯示
        print '\033[31m♥\033[0m Check PRO ',
        # self.is_pro()
        print '[\033[32m OK \033[0m]'

    def win_login(self):
        '''登陸界麵'''
        email = raw_input('Email:')
        password = getpass.getpass('Password:')
        return email, password

    def login_lastfm(self):
        '''Last.fm登陸'''
        if self.lastfm and self.last_fm_username and self.last_fm_password:
            self.scrobbler = Scrobbler(
                self.last_fm_username, self.last_fm_password)
            r, err = self.scrobbler.handshake()
            if r:
                logger.info("Last.fm login succeeds!")
                print '\033[31m♥\033[0m Last.fm logged in: %s' % self.last_fm_username
            else:
                logger.error("Last.fm login fails: " + err)
                self.lastfm = False
        else:
            self.lastfm = False

    def last_fm_account_required(fun):
        '''裝飾器,用於需要登錄Last.fm後才能使用的接口'''
        @wraps(fun)
        def wrapper(self, *args, **kwds):
            if not self.lastfm:
                return
            return fun(self, *args, **kwds)
        return wrapper

    @last_fm_account_required
    def submit_current_song(self):
        '''提交播放過的曲目'''
        # Submit the track if total playback time of the track > 30s
        if self.playingsong['length'] > 30:
            self.scrobbler.submit(
                self.playingsong['artist'],
                self.playingsong['title'],
                self.playingsong['albumtitle'],
                self.playingsong['length']
            )

    @last_fm_account_required
    def scrobble_now_playing(self):
        '''提交當前正在播放曲目'''
        self.scrobbler.now_playing(
            self.playingsong['artist'],
            self.playingsong['title'],
            self.playingsong['albumtitle'],
            self.playingsong['length']
        )

    def douban_login(self):
        '''登陸douban.fm獲取token'''
        path_token = os.path.expanduser('~/.douban_token.txt')
        if os.path.exists(path_token):
            # 已登陸
            logger.info("Found existing Douban.fm token.")
            with open(path_token, 'r') as f:
                self.login_data = pickle.load(f)
                self.token = self.login_data['token']
                self.user_name = self.login_data['user_name']
                self.user_id = self.login_data['user_id']
                self.expire = self.login_data['expire']
                self.default_volume = int(self.login_data['volume'])\
                    if 'volume' in self.login_data else 50
                self.default_channel = int(self.login_data['channel'])\
                    if 'channel' in self.login_data else 1

                # 存儲的default_channel是行數而不是真正發送數據的channel_id
                # 這裏需要進行轉化一下
                self.set_channel(self.default_channel)
            print '\033[31m♥\033[0m Get local token - Username: \033[33m%s\033[0m' % self.user_name
        else:
            # 未登陸
#.........這裏部分代碼省略.........
開發者ID:cckiss,項目名稱:douban.fm-1,代碼行數:103,代碼來源:douban_token.py


注:本文中的scrobbler.Scrobbler.handshake方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。