def getTop_playlistsId(request): getlistAll = [] global getLists getLists = [] global getListName getListName = [] global getListImage getListImage = [] getDict = {} #getDict. ease = NetEase() s = ease.top_playlists(limit=50) req = simplejson.dumps(s) getReq = simplejson.loads(req) print(getReq) # req = simplejson.loads(s) # 遍历整个字典取出需要的数据并加入到list for getid in getReq: global getLists getLists.append(getid["id"]) global getListName getListName.append(getid["name"]) global getListImage getListImage.append(getid["coverImgUrl"]) getlistAll.append(getLists) getlistAll.append(getListName) getlistAll.append(getListImage) jsonArray = simplejson.dumps(getlistAll) return HttpResponse(jsonArray)
def getPlayListDetail(request): sendJsonAll = [] global getSongIDs getSongIDs = [] getSongTimes = [] getSongNames = [] getSongMp3Url = [] getId = simplejson.loads(request.body) print(getId) id = getId["id"] ease = NetEase() s = ease.playlist_detail(id) jsonData = simplejson.dumps(s) parjson = simplejson.loads(jsonData) print(parjson) for getKeys in parjson: global getSongIDs getSongIDs.append(getKeys["id"]) getSongNames.append(getKeys["name"]) getSongTimes.append(getKeys["duration"]) getSongMp3Url.append(getKeys["mp3Url"]) sendJsonAll.append(getSongIDs) sendJsonAll.append(getSongNames) sendJsonAll.append(getSongTimes) sendJsonAll.append(getSongMp3Url) global getSongIDs sendJsonData = simplejson.dumps(sendJsonAll) print(sendJsonData) return HttpResponse(sendJsonData)
def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.config = Config() self.datatype = 'main' self.title = '网易云音乐' self.datalist = [ '排行榜', '艺术家', '新碟上架', '精选歌单', '我的歌单', 'DJ节目', '每日推荐', '私人FM', '搜索', '帮助' ] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database['collections'][0] self.player = Player() self.cache = Cache() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = self.storage.database["user"]["user_id"] self.username = self.storage.database["user"]["nickname"] self.resume_play = True self.at_playing_list = False signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) self.START = time.time()
def on_get(self, req, resp): query = req.get_param('q', True) limit = req.get_param_as_int('limit') or 60 offset = req.get_param_as_int('offset') or 0 ne = NetEase() # 搜索单曲(1),歌手(100),专辑(10),歌单(1000),用户(1002) *(type)* resp.body = json.dumps(ne.search(query, 1, offset, 'true', limit))
def search_music(q, limit): netease = NetEase() r = netease.search(q, limit=limit) if r['code'] != 200: return jsonify({ "error" : True }) else: ids = [] for song in r['result']['songs']: ids.append(song['id']) musics = netease.songs_detail(ids) outputs = [] for music in musics: outputs.append({ "error" : False, "name" : music['name'], "cover" : music['album']['blurPicUrl'], "album_name": music['album']['name'], "author": music['artists'][0]['name'], "url" : music['mp3Url'] }) outputs = { "error" : False, "type" : "music", "musics" : outputs } return jsonify(outputs)
def play_list(): cate = '全部' if request.method == "POST": cate = request.form['cate'] play_song_list = NetEase.top_playlists(NetEase(),cate) categoty = NetEase.get_play_category(NetEase(),play_song_list) return render_template('play_list.html',play_song_list = play_song_list,categoty = categoty,now_cate=cate)
def __init__(self): self.home = os.path.expanduser("~") + '/.musicbox' if not os.path.isdir(self.home): os.mkdir(self.home) locale.setlocale(locale.LC_ALL, "") code = locale.getpreferredencoding() try: sfile = file(self.home + "/config.json", 'r') data = json.loads(sfile.read()) #version check assert ('v' in data and data['v'] <= APP_VER) self.collection = data['collection'] self.userid = data['account']['id'] self.username = data['account']['nickname'] self.netease = NetEase(cookie=data['account']['cookie']) sfile.close() except: self.collection = [] self.userid = None self.username = None self.netease = NetEase() self.ui = Ui(self.netease) self.player = Player(self.ui) self.menu = Menu(self.netease, self.ui, self.player, [self.userid, self.username, self.update_profile])
def __init__(self): self.screen = curses.initscr() self.screen.timeout(100) # the screen refresh every 100ms # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.lyric = '' self.now_lyric = '' self.tlyric = '' self.storage = Storage() self.config = Config() self.newversion = False
def get_song_infos(): n = NetEase() songlist = [] for i in n.top_songlist(): singers = "" for t in[j['name'] for j in i['artists']]: singers = singers+" "+t songlist.append([i['name'],singers,i['mp3Url']]) return songlist
def getLyric(): if 'lyric' not in self.songs[str(self.playing_id)].keys(): self.songs[str(self.playing_id)]["lyric"] = [] if len(self.songs[str(self.playing_id)]["lyric"]) > 0: return netease = NetEase() lyric = netease.song_lyric(self.playing_id) if (not lyric == []) or lyric == '未找到歌词': lyric = lyric.split('\n') self.songs[str(self.playing_id)]["lyric"] = lyric return
def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
def getLyric(): if "lyric" not in self.songs[str(self.playing_id)].keys(): self.songs[str(self.playing_id)]["lyric"] = [] if len(self.songs[str(self.playing_id)]["lyric"]) > 0: return netease = NetEase() lyric = netease.song_lyric(self.playing_id) if lyric == [] or lyric == "未找到歌词": return lyric = lyric.split("\n") self.songs[str(self.playing_id)]["lyric"] = lyric return
def gettLyric(): if 'tlyric' not in self.songs[str(self.playing_id)].keys(): self.songs[str(self.playing_id)]["tlyric"] = [] if len(self.songs[str(self.playing_id)]["tlyric"]) > 0: return netease = NetEase() tlyric = netease.song_tlyric(self.playing_id) if tlyric == [] or tlyric == '未找到歌词翻译': return tlyric = tlyric.split('\n') self.songs[str(self.playing_id)]["tlyric"] = tlyric return
def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_RED) curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_RED) self.screen.bkgd(' ',curses.color_pair(1) )
def __init__(self): self.config = Config() # self.ui = Ui() self.popen_handler = None # flag stop, prevent thread start self.playing_flag = False self.refrese_url_flag = False self.process_length = 0 self.process_location = 0 self.storage = Storage() self.cache = Cache() self.end_callback = None self.playing_song_changed_callback = None self.api = NetEase()
def __init__(self, song_name): self.mp3_date = None netease = NetEase() data = netease.search(song_name, stype=1, offset=0, total='true', limit=60) # print data song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] else: for i in range(0, len(data['result']['songs']) ): song_ids.append( data['result']['songs'][i]['id'] ) songs = netease.songs_detail(song_ids) self.mp3_data = netease.dig_info(songs, 'songs') #歌曲信息,album, artist, song_name, mp3_url
def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.datatype = 'main' self.title = 'NetEase Music' self.datalist = ['Ranking', 'Artist', 'Mew', 'Feature', 'Mine', 'Broadcast', 'DJing', 'Collection', 'Search', 'Help'] self.offset = 0 self.index = 0 self.presentsongs = [] self.player = Player() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = None self.username = None try: sfile = file(home + "/netease-musicbox/flavor.json", 'r') data = json.loads(sfile.read()) self.collection = data['collection'] self.account = data['account'] sfile.close() except: self.collection = [] self.account = {}
def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.config = Config() self.datatype = 'main' self.title = 'NetEase Music' self.datalist = ['Charts', 'Artists', 'New Songs', 'Songs', 'My Songs', 'Radio Stations', 'Recommended', 'Personal Radio', 'Search', 'Help'] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database['collections'][0] self.player = Player() self.player.playing_song_changed_callback = self.song_changed_callback self.cache = Cache() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = self.storage.database['user']['user_id'] self.username = self.storage.database['user']['nickname'] self.resume_play = True self.at_playing_list = False signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) self.START = time.time()
def __init__(self): reload(sys) sys.setdefaultencoding("UTF-8") self.config = Config() self.datatype = "main" self.title = "网易云音乐" self.datalist = ["排行榜", "艺术家", "新碟上架", "精选歌单", "我的歌单", "DJ节目", "每日推荐", "私人FM", "搜索", "帮助"] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database["collections"][0] self.player = Player() self.player.playing_song_changed_callback = self.song_changed_callback self.cache = Cache() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = self.storage.database["user"]["user_id"] self.username = self.storage.database["user"]["nickname"] self.resume_play = True self.at_playing_list = False signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) self.START = time.time()
def search(): if request.method == "GET": s = request.args.get('s') search_list = NetEase.get_search(NetEase(),s) return render_template('search.html',search_list = search_list['result']['songs']) else: return render_template('search.html',search_list = None)
def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.datatype = 'main' self.title = '网易云音乐' self.datalist = [ '排行榜', '艺术家', '新碟上架', '精选歌单', '我的歌单', 'DJ节目', '打碟', '收藏', '搜索', '帮助' ] self.offset = 0 self.index = 0 self.presentsongs = [] self.player = Player() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = None self.username = None signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) try: sfile = file(Constant.conf_dir + "/flavor.json", 'r') data = json.loads(sfile.read()) self.collection = data['collection'] self.account = data['account'] sfile.close() except: self.collection = [] self.account = {}
def __init__(self): self.screen = curses.initscr() self.screen.timeout(100) # the screen refresh every 100ms # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.lyric = "" self.now_lyric = "" self.storage = Storage() self.newversion = False # Set cursor to invisible. try: curses.curs_set(0) except curses.error: # The terminal does not supports the visibility requested. pass
def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.config = Config() self.datatype = 'main' self.title = '网易云音乐' self.datalist = ['排行榜', '艺术家', '新碟上架', '精选歌单', '我的歌单', 'DJ节目', '每日推荐', '私人FM', '搜索', '帮助'] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database['collections'][0] self.player = Player() self.player.playing_song_changed_callback = self.song_changed_callback self.cache = Cache() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = self.storage.database["user"]["user_id"] self.username = self.storage.database["user"]["nickname"] self.resume_play = True self.at_playing_list = False signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) self.START = time.time()
def runInThread(onExit, arg): para = ['mpg123', '-R'] para[1:1] = self.mpg123_parameters self.popen_handler = subprocess.Popen(para, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.popen_handler.stdin.write('V ' + str(self.info['playing_volume']) + '\n') if arg: self.popen_handler.stdin.write('L ' + arg + '\n') else: self.next_idx() onExit() return self.process_first = True while True: if self.playing_flag is False: break strout = self.popen_handler.stdout.readline() if re.match('^\@F.*$', strout): process_data = strout.split(' ') process_location = float(process_data[4]) if self.process_first: self.process_length = process_location self.process_first = False self.process_location = 0 else: self.process_location = self.process_length - process_location # NOQA continue elif strout[:2] == '@E': # get a alternative url from new api sid = popenArgs['song_id'] new_url = NetEase().songs_detail_new_api([sid])[0]['url'] if new_url is None: log.warning(('Song {} is unavailable ' 'due to copyright issue').format(sid)) break log.warning( 'Song {} is not compatible with old api.'.format(sid)) popenArgs['mp3_url'] = new_url self.popen_handler.stdin.write('\nL ' + new_url + '\n') self.popen_handler.stdout.readline() elif strout == '@P 0\n': self.popen_handler.stdin.write('Q\n') self.popen_handler.kill() break if self.playing_flag: self.next_idx() onExit() return
def change_user(): #file = open('163.md') file = open('account.txt') try: alist = file.read() finally: file.close() account_list = alist.splitlines() account = random.choice(account_list) user = account.split(",")[0] passwd = md5(account.split(",")[1]) joker = NetEase() login_info = joker.login(user, passwd) print login_info return login_info
def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space()
class User(object): def __init__(self): self.netease = NetEase() self.is_login = False self.uid = str() # '' def login(self, username, password): data = self.netease.login(username, password) code = data['code'] if code is 200: self.uid = data['profile']['userId'] self.is_login = True return True else: # 501 return False def get_favorite_playlist_id(self): """ login required success: return playlist id fail: return empty string '' """ if self.is_login: playlist = self.netease.user_playlist(self.uid) for each in playlist: if each['specialType'] is 5: # favorite playlist return each['id'] # the favorite playlist id return '' return '' def get_music_title_and_url(self, pid): """ :param pid: playlist id :return re: return list re """ playlist = self.netease.playlist_detail(pid) re = list() if playlist is not []: for music in playlist: tmp = dict() tmp['title'] = music['name'] tmp['url'] = music['mp3Url'] re.append(tmp) return re
def __init__(self): self.config = Config() self.datatype = "main" self.title = "网易云音乐" self.datalist = [ "排行榜", "艺术家", "新碟上架", "精选歌单", "我的歌单", "主播电台", "每日推荐歌曲", "每日推荐歌单", "私人FM", "搜索", "帮助", ] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database["collections"] self.player = Player() self.player.playing_song_changed_callback = self.song_changed_callback self.cache = Cache() # self.ui = Ui() self.api = NetEase() # self.screen = curses.initscr() # self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.at_playing_list = False self.enter_flag = True # signal.signal(signal.SIGWINCH, self.change_term) # signal.signal(signal.SIGINT, self.send_kill) self.menu_starts = time.time() self.countdown_start = time.time() self.countdown = -1 self.is_in_countdown = False self.keyword = ''
def start_download(self): check = self.download_lock.acquire(False) if not check: return False while True: if self.stop: break if not self.enable: break self.check_lock.acquire() if len(self.downloading) <= 0: self.check_lock.release() break data = self.downloading.pop() self.check_lock.release() song_id = data[0] song_name = data[1] artist = data[2] url = data[3] onExit = data[4] output_path = Constant.download_dir output_file = str(artist) + ' - ' + str(song_name) + '.mp3' full_path = os.path.join(output_path, output_file) new_url = NetEase().songs_detail_new_api([song_id])[0]['url'] log.info('Old:{}. New:{}'.format(url, new_url)) try: para = [ 'aria2c', '--auto-file-renaming=false', '--allow-overwrite=true', '-d', output_path, '-o', output_file, new_url ] para[1:1] = self.aria2c_parameters self.aria2c = subprocess.Popen(para, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.aria2c.wait() except OSError as e: log.warning( '{}.\tAria2c is unavailable, fall back to wget'.format(e)) self._mkdir(output_path) para = ['wget', '-O', full_path, new_url] self.wget = subprocess.Popen(para, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.wget.wait() if self._is_cache_successful(): log.debug(str(song_id) + ' Cache OK') onExit(song_id, full_path) self.download_lock.release()
def __init__(self, song_name): self.mp3_date = None netease = NetEase() data = netease.search(song_name, stype=1, offset=0, total='true', limit=60) # print data song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] else: for i in range(0, len(data['result']['songs'])): song_ids.append(data['result']['songs'][i]['id']) songs = netease.songs_detail(song_ids) self.mp3_data = netease.dig_info( songs, 'songs') #歌曲信息,album, artist, song_name, mp3_url
def search_music(q, limit): netease = NetEase() r = netease.search(q, limit=limit) if r['code'] != 200: return jsonify({"error": True}) else: ids = [] for song in r['result']['songs']: ids.append(song['id']) musics = netease.songs_detail(ids) outputs = [] for music in musics: outputs.append({ "error": False, "name": music['name'], "cover": music['album']['blurPicUrl'], "album_name": music['album']['name'], "author": music['artists'][0]['name'], "url": music['mp3Url'] }) outputs = {"error": False, "type": "music", "musics": outputs} return jsonify(outputs)
def get_lyric(request): lyricId = simplejson.loads(request.body) print(lyricId) ids = lyricId['id'] print(ids) s = NetEase() getly = s.song_lyric(ids) print(getly) sendDict = dict() sendDict["id"] = getly sendly = simplejson.dumps(sendDict) return HttpResponse(sendly)
def __init__(self, parent=None): super(LoginDialog, self).__init__(parent) self.username_lable = QLabel() self.password_lable = QLabel() self.hint_label = QLabel() self.username_widget = QLineEdit() self.password_widget = QLineEdit() self.login_btn = QPushButton() self.layout = QVBoxLayout() self.ne = NetEase() self.__set_signal_binding() self.__set_widgets_prop() self.__set_layouts_prop() self.__set_me()
def __init__(self): curses.setupterm() #初始化终端 self.screen = curses.initscr() self.LINES=curses.tigetnum('lines') #终端行数 self.COLS=curses.tigetnum('cols') #列数 self.show_begin_line=int((int(self.LINES)-22)/2-1) # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
def login(): if request.method == "POST": phone = request.form['phone'] password = request.form['password'] if phone and password: data = NetEase.user_login(NetEase(),phone,password) if data is not True: session['phone'] = phone return redirect(url_for('user_song_list')) else: flash('Password or Phone is not ture') return redirect(url_for('login')) else: flash('field can not be empty') return redirect(url_for('login')) else: return render_template('login.html')
def __init__(self): # Initializing curses # initialize window object to curses.initscr() self.screen = curses.initscr() # character break buffer, to read in any key without the need to press 'Enter'. curses.cbreak() # make those navigation keys to normal key that can be processed in program. self.screen.keypad(1) # initialize the some color pair curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Initializing NetEase object to communicate with NetEase server. self.netease = NetEase()
def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x)/5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space()
def __init__(self, parent=None): super(MainWidget, self).__init__(parent) # set app name before mediaObject was created to avoid phonon problem QCoreApplication.setApplicationName("NetEaseMusic-ThirdParty") self.ui = UiMainWidget() self.ui.setup_ui(self) self.signal_mapper = QSignalMapper(self) self.player = Phonon.createPlayer(Phonon.MusicCategory) self.net_manager = QNetworkAccessManager() self.searchShortcut = QShortcut(QKeySequence("Ctrl+F"), self) self.sources = [] self.net_ease = NetEase() self.model = DataModel() self.set_self_prop() self.set_signal_binding() self.init_table_widget()
def start_playing(self, on_exit, args): """ Runs the given args in subprocess.Popen, and then calls the function on_exit when the subprocess completes. on_exit is a callable object, and args is a lists/tuple of args that would give to subprocess.Popen. """ # log.debug("%s,%s,%s" % (args['song_id'], args['song_name'], args['mp3_url'])) if "cache" in args.keys() and os.path.isfile(args["cache"]): thread = threading.Thread( target=self.run_mpg123, args=(on_exit, args["cache"]) ) else: new_url = NetEase().songs_url([args["song_id"]])[0]["url"] #使用新地址 if not new_url: #如果没有获得新地址 new_url = args["mp3_url"] #使用老地址传给mpg123 thread = threading.Thread( target=self.run_mpg123, args=(on_exit, new_url, args["expires"], args["get_time"]), ) cache_thread = threading.Thread( target=self.download_song, args=( args["song_id"], args["song_name"], args["artist"], args["mp3_url"], ), ) cache_thread.start() thread.start() lyric_download_thread = threading.Thread(target=self.download_lyric) lyric_download_thread.start() tlyric_download_thread = threading.Thread( target=self.download_lyric, args=(True,) ) tlyric_download_thread.start() # returns immediately after the thread starts return thread
class Ui: def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() #cbreak模式,按键事件互动 self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x)/5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() def build_playinfo(self, song_name, artist, album_name, quality, pause=False): curses.noecho() # refresh top 2 line self.screen.move(1, 1) self.screen.clrtoeol() self.screen.move(2, 1) self.screen.clrtoeol() if pause: self.screen.addstr(1, self.indented_startcol, '_ _ z Z Z ' + quality, curses.color_pair(3)) else: self.screen.addstr(1, self.indented_startcol, '♫ ♪ ♫ ♪ ' + quality, curses.color_pair(3)) self.screen.addstr(1, min(self.indented_startcol + 18, self.x-1), song_name + self.space + artist + ' < ' + album_name + ' >', curses.color_pair(4)) self.screen.refresh() def build_loading(self): self.screen.addstr(6, self.startcol, '享受高品质音乐,loading...', curses.color_pair(1)) self.screen.refresh() def build_menu(self, datatype, title, datalist, offset, index, step): # keep playing info in line 1 curses.noecho() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(4, self.startcol, title, curses.color_pair(1)) if len(datalist) == 0: self.screen.addstr(8, self.startcol, '这里什么都没有 -,-') else: if datatype == 'main': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'songs': iter_range = min(len(datalist), offset + step) for i in range(offset, iter_range): # this item is focus if i == index: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) self.screen.addstr(i - offset + 8, self.indented_startcol, str('-> ' + str(i) + '. ' + datalist[i]['song_name'] + self.space + datalist[i][ 'artist'] + ' < ' + datalist[i]['album_name'] + ' >')[:int(self.x*2)], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) self.screen.addstr(i - offset + 8, self.startcol, str(str(i) + '. ' + datalist[i]['song_name'] + self.space + datalist[i][ 'artist'] + ' < ' + datalist[i]['album_name'] + ' >')[:int(self.x*2)]) self.screen.addstr(iter_range - offset + 8, 0, ' ' * self.x) elif datatype == 'artists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + self.space + str( datalist[i]['alias']), curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['artists_name'] + self.space + datalist[i][ 'alias']) elif datatype == 'albums': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i][ 'artists_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i][ 'artists_name']) elif datatype == 'playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['title'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['title']) elif datatype == 'top_playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i]['creator_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i][ 'creator_name']) elif datatype == 'toplists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'playlist_classes' or datatype == 'playlist_class_detail': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'djchannels': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['song_name']) elif datatype == 'search': self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(8, self.startcol, '选择搜索类型:', curses.color_pair(1)) for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 10, self.indented_startcol, '-> ' + str(i) + '.' + datalist[i - 1], curses.color_pair(2)) else: self.screen.addstr(i - offset + 10, self.startcol, str(i) + '.' + datalist[i - 1]) elif datatype == 'help': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][ 1] + ' ' + datalist[i][2], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][1] + ' ' + datalist[i][2]) self.screen.addstr(20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存') self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~') self.screen.addstr(22, self.startcol, 'Build with love to music by omi') self.screen.refresh() def build_search(self, stype): netease = self.netease if stype == 'songs': song_name = self.get_param('搜索歌曲:') try: data = netease.search(song_name, stype=1) song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] # if search song result do not has mp3Url # send ids to get mp3Url else: for i in range(0, len(data['result']['songs'])): song_ids.append(data['result']['songs'][i]['id']) songs = netease.songs_detail(song_ids) return netease.dig_info(songs, 'songs') except: return [] elif stype == 'artists': artist_name = self.get_param('搜索艺术家:') try: data = netease.search(artist_name, stype=100) if 'artists' in data['result']: artists = data['result']['artists'] return netease.dig_info(artists, 'artists') except: return [] elif stype == 'albums': artist_name = self.get_param('搜索专辑:') try: data = netease.search(artist_name, stype=10) if 'albums' in data['result']: albums = data['result']['albums'] return netease.dig_info(albums, 'albums') except: return [] elif stype == 'search_playlist': artist_name = self.get_param('搜索网易精选集:') try: data = netease.search(artist_name, stype=1000) if 'playlists' in data['result']: playlists = data['result']['playlists'] return netease.dig_info(playlists, 'top_playlists') except: return [] return [] def build_login(self): self.build_login_bar() local_account = self.get_account() local_password = hashlib.md5(self.get_password()).hexdigest() login_info = self.netease.login(local_account, local_password) account = [local_account,local_password] if login_info['code'] != 200: x = self.build_login_error() if x == ord('1'): return self.build_login() else: return -1 else: return [login_info, account] def build_login_bar(self): curses.noecho() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, '请输入登录信息(支持手机登陆)',curses.color_pair(1)) self.screen.addstr(8, self.startcol, "账号:", curses.color_pair(1)) self.screen.addstr(9, self.startcol, "密码:", curses.color_pair(1)) self.screen.move(8,24) self.screen.refresh() def build_login_error(self): self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(8, self.startcol, '艾玛,登录信息好像不对呢 (O_O)#', curses.color_pair(1)) self.screen.addstr(10, self.startcol, '[1] 再试一次') self.screen.addstr(11, self.startcol, '[2] 稍后再试') self.screen.addstr(14, self.startcol, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() return x def get_account(self): curses.echo() account = self.screen.getstr(8, self.startcol+6,60) return account def get_password(self): curses.noecho() password = self.screen.getstr(9, self.startcol+6,60) return password def get_param(self, prompt_string): # keep playing info in line 1 curses.echo() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, prompt_string, curses.color_pair(1)) self.screen.refresh() info = self.screen.getstr(10, self.startcol, 60) if info.strip() is '': return self.get_param(prompt_string) else: return info def update_size(self): # get terminal size size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) # update intendations curses.resizeterm(self.y, self.x) self.startcol = int(float(self.x)/5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.screen.clear() self.screen.refresh() def update_space(self): if self.x > 140: self.space = " - " elif self.x > 80: self.space = " - " else: self.space = " - " self.screen.refresh()
class Ui: def __init__(self): self.screen = curses.initscr() self.screen.timeout(100) # the screen refresh every 100ms # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.lyric = '' self.now_lyric = '' self.tlyric = '' self.storage = Storage() self.config = Config() self.newversion = False def notify(self, summary, song, album, artist): if summary != 'disable': body = '%s\nin %s by %s' % (song, album, artist) content = escape_quote(summary + ': ' + body) notify(content) def build_playinfo(self, song_name, artist, album_name, quality, start, pause=False): curses.noecho() # refresh top 2 line self.screen.move(1, 1) self.screen.clrtoeol() self.screen.move(2, 1) self.screen.clrtoeol() if pause: self.screen.addstr(1, self.indented_startcol, '_ _ z Z Z ' + quality, curses.color_pair(3)) else: self.screen.addstr(1, self.indented_startcol, '♫ ♪ ♫ ♪ ' + quality, curses.color_pair(3)) self.screen.addstr( 1, min(self.indented_startcol + 18, self.x - 1), song_name + self.space + artist + ' < ' + album_name + ' >', curses.color_pair(4)) self.screen.refresh() def build_process_bar(self, now_playing, total_length, playing_flag, pause_flag, playing_mode): if (self.storage.database['player_info']['idx'] >= len( self.storage.database['player_info']['player_list'])): return curses.noecho() self.screen.move(3, 1) self.screen.clrtoeol() self.screen.move(4, 1) self.screen.clrtoeol() if not playing_flag: return if total_length <= 0: total_length = 1 if now_playing > total_length or now_playing <= 0: now_playing = 0 process = '[' for i in range(0, 33): if i < now_playing / total_length * 33: if (i + 1) > now_playing / total_length * 33: if not pause_flag: process += '>' continue process += '=' else: process += ' ' process += '] ' now_minute = int(now_playing / 60) if now_minute > 9: now_minute = str(now_minute) else: now_minute = '0' + str(now_minute) now_second = int(now_playing - int(now_playing / 60) * 60) if now_second > 9: now_second = str(now_second) else: now_second = '0' + str(now_second) total_minute = int(total_length / 60) if total_minute > 9: total_minute = str(total_minute) else: total_minute = '0' + str(total_minute) total_second = int(total_length - int(total_length / 60) * 60) if total_second > 9: total_second = str(total_second) else: total_second = '0' + str(total_second) process += '(' + now_minute + ':' + now_second + '/' + total_minute + ':' + total_second + ')' # NOQA if playing_mode == 0: process = '顺序播放 ' + process elif playing_mode == 1: process = '顺序循环 ' + process elif playing_mode == 2: process = '单曲循环 ' + process elif playing_mode == 3: process = '随机播放 ' + process elif playing_mode == 4: process = '随机循环 ' + process else: pass self.screen.addstr(3, self.startcol - 2, process, curses.color_pair(1)) song = self.storage.database['songs'][ self.storage.database['player_info']['player_list'][ self.storage.database['player_info']['idx']]] if 'lyric' not in song.keys() or len(song['lyric']) <= 0: self.now_lyric = '暂无歌词 ~>_<~ \n' if dbus_activity and self.config.get_item('osdlyrics'): self.now_playing = song['song_name'] + ' - ' + song[ 'artist'] + '\n' else: key = now_minute + ':' + now_second for line in song['lyric']: if key in line: if 'tlyric' not in song.keys() or len(song['tlyric']) <= 0: self.now_lyric = line else: self.now_lyric = line for tline in song['tlyric']: if key in tline and self.config.get_item( 'translation'): self.now_lyric = tline + ' || ' + self.now_lyric # NOQA self.now_lyric = re.sub('\[.*?\]', '', self.now_lyric) if dbus_activity and self.config.get_item('osdlyrics'): try: bus = dbus.SessionBus().get_object('org.musicbox.Bus', '/') if self.now_lyric == '暂无歌词 ~>_<~ \n': bus.refresh_lyrics(self.now_playing, dbus_interface='local.musicbox.Lyrics') else: bus.refresh_lyrics(self.now_lyric, dbus_interface='local.musicbox.Lyrics') except Exception as e: log.error(e) pass self.screen.addstr(4, self.startcol - 2, str(self.now_lyric), curses.color_pair(3)) self.screen.refresh() def build_loading(self): self.screen.addstr(7, self.startcol, '享受高品质音乐,loading...', curses.color_pair(1)) self.screen.refresh() # start is the timestamp of this function being called def build_menu(self, datatype, title, datalist, offset, index, step, start): # keep playing info in line 1 curses.noecho() self.screen.move(5, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, title, curses.color_pair(1)) if len(datalist) == 0: self.screen.addstr(8, self.startcol, '这里什么都没有 -,-') else: if datatype == 'main': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'songs' or datatype == 'fmsongs': iter_range = min(len(datalist), offset + step) for i in range(offset, iter_range): # this item is focus if i == index: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) lead = '-> ' + str(i) + '. ' self.screen.addstr(i - offset + 8, self.indented_startcol, lead, curses.color_pair(2)) name = '{}{}{} < {} >'.format( datalist[i]['song_name'], self.space, datalist[i]['artist'], datalist[i]['album_name']) # the length decides whether to scoll if truelen(name) < self.x - self.startcol - 1: self.screen.addstr( i - offset + 8, self.indented_startcol + len(lead), name, curses.color_pair(2)) else: name = scrollstring(name + ' ', start) self.screen.addstr( i - offset + 8, self.indented_startcol + len(lead), str(name), curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) self.screen.addstr( i - offset + 8, self.startcol, str( str(i) + '. ' + datalist[i]['song_name'] + self.space + datalist[i]['artist'] + ' < ' + datalist[i]['album_name'] + ' >')[:int(self.x * 2)]) self.screen.addstr(iter_range - offset + 9, 0, ' ' * self.x) elif datatype == 'artists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + self.space + str(datalist[i]['alias']), curses.color_pair(2)) else: self.screen.addstr( i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['artists_name'] + self.space + datalist[i]['alias']) elif datatype == 'albums': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i]['artists_name'], curses.color_pair(2)) else: self.screen.addstr( i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i]['artists_name']) elif datatype == 'playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['title'], curses.color_pair(2)) else: self.screen.addstr( i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['title']) elif datatype == 'top_playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i]['creator_name'], curses.color_pair(2)) else: self.screen.addstr( i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i]['creator_name']) elif datatype == 'toplists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype in ('playlist_classes', 'playlist_class_detail'): for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'djchannels': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2)) else: self.screen.addstr( i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['song_name']) elif datatype == 'search': self.screen.move(6, 1) self.screen.clrtobot() self.screen.timeout(-1) self.screen.addstr(8, self.startcol, '选择搜索类型:', curses.color_pair(1)) for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 10, self.indented_startcol, '-> ' + str(i) + '.' + datalist[i - 1], curses.color_pair(2)) else: self.screen.addstr(i - offset + 10, self.startcol, str(i) + '.' + datalist[i - 1]) self.screen.timeout(100) elif datatype == 'help': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr( i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][1] + ' ' + datalist[i][2], curses.color_pair(2)) else: self.screen.addstr( i - offset + 9, self.startcol, str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][1] + ' ' + datalist[i][2]) self.screen.addstr( 20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存') self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~') self.screen.addstr(22, self.startcol, 'Build with love to music by omi') self.screen.refresh() def build_search(self, stype): self.screen.timeout(-1) netease = self.netease if stype == 'songs': song_name = self.get_param('搜索歌曲:') if song_name == '/return': return [] else: try: data = netease.search(song_name, stype=1) song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] # if search song result do not has mp3Url # send ids to get mp3Url else: for i in range(0, len(data['result']['songs'])): song_ids.append( data['result']['songs'][i]['id']) songs = netease.songs_detail(song_ids) return netease.dig_info(songs, 'songs') except Exception as e: log.error(e) return [] elif stype == 'artists': artist_name = self.get_param('搜索艺术家:') if artist_name == '/return': return [] else: try: data = netease.search(artist_name, stype=100) if 'artists' in data['result']: artists = data['result']['artists'] return netease.dig_info(artists, 'artists') except Exception as e: log.error(e) return [] elif stype == 'albums': albums_name = self.get_param('搜索专辑:') if albums_name == '/return': return [] else: try: data = netease.search(albums_name, stype=10) if 'albums' in data['result']: albums = data['result']['albums'] return netease.dig_info(albums, 'albums') except Exception as e: log.error(e) return [] elif stype == 'search_playlist': search_playlist = self.get_param('搜索网易精选集:') if search_playlist == '/return': return [] else: try: data = netease.search(search_playlist, stype=1000) if 'playlists' in data['result']: playlists = data['result']['playlists'] return netease.dig_info(playlists, 'top_playlists') except Exception as e: log.error(e) return [] return [] def build_login(self): self.build_login_bar() local_account = self.get_account() local_password = hashlib.md5(self.get_password()).hexdigest() login_info = self.netease.login(local_account, local_password) account = [local_account, local_password] if login_info['code'] != 200: x = self.build_login_error() if x == ord('1'): return self.build_login() else: return -1 else: return [login_info, account] def build_login_bar(self): curses.noecho() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, '请输入登录信息(支持手机登陆)', curses.color_pair(1)) self.screen.addstr(8, self.startcol, '账号:', curses.color_pair(1)) self.screen.addstr(9, self.startcol, '密码:', curses.color_pair(1)) self.screen.move(8, 24) self.screen.refresh() def build_login_error(self): self.screen.move(4, 1) self.screen.timeout(-1) # disable the screen timeout self.screen.clrtobot() self.screen.addstr(8, self.startcol, '艾玛,登录信息好像不对呢 (O_O)#', curses.color_pair(1)) self.screen.addstr(10, self.startcol, '[1] 再试一次') self.screen.addstr(11, self.startcol, '[2] 稍后再试') self.screen.addstr(14, self.startcol, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() self.screen.timeout(100) # restore the screen timeout return x def get_account(self): self.screen.timeout(-1) # disable the screen timeout curses.echo() account = self.screen.getstr(8, self.startcol + 6, 60) self.screen.timeout(100) # restore the screen timeout return account def get_password(self): self.screen.timeout(-1) # disable the screen timeout curses.noecho() password = self.screen.getstr(9, self.startcol + 6, 60) self.screen.timeout(100) # restore the screen timeout return password def get_param(self, prompt_string): # keep playing info in line 1 curses.echo() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, prompt_string, curses.color_pair(1)) self.screen.refresh() info = self.screen.getstr(10, self.startcol, 60) if info == '': return '/return' elif info.strip() is '': return self.get_param(prompt_string) else: return info def update_size(self): # get terminal size size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) # update intendations curses.resizeterm(self.y, self.x) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.screen.clear() self.screen.refresh() def update_space(self): if self.x > 140: self.space = ' - ' elif self.x > 80: self.space = ' - ' else: self.space = ' - ' self.screen.refresh()
user="******", # your username passwd="root", # your password db="netease_music") # name of the data base cur = db.cursor() sql = 'INSERT INTO songs (song_name, artist_id, album_id, mp3_url, comment_thread_id, popularity, play_time, bitrate, song_id) VALUES \ ("%s", %s, %s, "%s", "%s", %s, %s, %s, %s)' % ( song_name, artist_id, album_id, mp3_url, comment_thread_id, popularity, play_time, bitrate, song_id) print sql cur.execute(sql) db.commit() db.close() return 0 joker = NetEase() user_info = {} local_account = '*****@*****.**' local_password = '******' # login_info = joker.login(local_account, local_password) # print login_info for i in range(30395352, 99999999): user_info = joker.user_playlist(i) print user_info if len(user_info) > 1: print 1111 # add_user(user_info) # try: # play_time = user_info[0]['bMusic']['playTime']/1000 # except IndexError:
# 初始化缓存 create_dir(Constant.conf_dir) create_dir(Constant.download_dir) create_dir(Constant.lyc_dir) create_dir(Constant.lyc_netease) create_dir(Constant.lyc_qqmusic) create_dir(Constant.download_dir) create_file(Constant.storage_path) create_file(Constant.log_path, default="") create_file(Constant.cookie_path, default="#LWP-Cookies-2.0\n") from api import NetEase, Parse from storage import Storage from hashlib import md5 api = NetEase() storage = Storage() storage.load() # 载入存储的信息 user = storage.database["user"] account = user["username"] md5pass = user["password"] userid = user["user_id"] username = user["nickname"] def request_api(func, *args): """需要登录功能的请求方式(private)""" result = func(*args) if result: return result
class Ui: def __init__(self): self.screen = curses.initscr() self.screen.timeout(100) # the screen refresh every 100ms # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) # term resize handling size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.lyric = "" self.now_lyric = "" self.tlyric = "" self.storage = Storage() self.config = Config() self.newversion = False def notify(self, summary, song, album, artist): if summary != "disable": cmd = "" body = "%s\nin %s by %s" % (song, album, artist) if platform.system() == "Darwin": content = escape_quote(summary + ': ' + body) cmd = '/usr/bin/osascript -e $\'display notification "' + content + '"\'' else: cmd = '/usr/bin/notify-send -a NetEase-MusicBox "%s" "%s"' % (summary, body) os.system(cmd) def build_playinfo(self, song_name, artist, album_name, quality, start, pause=False): curses.noecho() # refresh top 2 line self.screen.move(1, 1) self.screen.clrtoeol() self.screen.move(2, 1) self.screen.clrtoeol() if pause: self.screen.addstr(1, self.indented_startcol, '_ _ z Z Z ' + quality, curses.color_pair(3)) else: self.screen.addstr(1, self.indented_startcol, '♫ ♪ ♫ ♪ ' + quality, curses.color_pair(3)) self.screen.addstr(1, min(self.indented_startcol + 18, self.x - 1), song_name + self.space + artist + ' < ' + album_name + ' >', curses.color_pair(4)) # The following script doesn't work. It is intended to scroll the playinfo # Scrollstring works by determining how long since it is created, but # playinfo is created everytime the screen refreshes (every 500ms), unlike # the menu. Is there a workaround? # name = song_name + self.space + artist + ' < ' + album_name + ' >' # decides whether to scoll # if truelen(name) <= self.x - self.indented_startcol - 18: # self.screen.addstr(1, min(self.indented_startcol + 18, self.x-1), # name, # curses.color_pair(4)) # else: # name = scrollstring(name + ' ', start) # self.screen.addstr(1, min(self.indented_startcol + 18, self.x-1), # str(name), # curses.color_pair(4)) self.screen.refresh() def build_process_bar(self, now_playing, total_length, playing_flag, pause_flag, playing_mode): if (self.storage.database["player_info"]["idx"] >= len(self.storage.database["player_info"]["player_list"])): return curses.noecho() self.screen.move(3, 1) self.screen.clrtoeol() self.screen.move(4, 1) self.screen.clrtoeol() if not playing_flag: return if total_length <= 0: total_length = 1 if now_playing > total_length or now_playing <= 0: now_playing = 0 process = "[" for i in range(0, 33): if i < now_playing / total_length * 33: if (i + 1) > now_playing / total_length * 33: if not pause_flag: process += ">" continue process += "=" else: process += " " process += "] " now_minute = int(now_playing / 60) if now_minute > 9: now_minute = str(now_minute) else: now_minute = "0" + str(now_minute) now_second = int(now_playing - int(now_playing / 60) * 60) if now_second > 9: now_second = str(now_second) else: now_second = "0" + str(now_second) total_minute = int(total_length / 60) if total_minute > 9: total_minute = str(total_minute) else: total_minute = "0" + str(total_minute) total_second = int(total_length - int(total_length / 60) * 60) if total_second > 9: total_second = str(total_second) else: total_second = "0" + str(total_second) process += "(" + now_minute + ":" + now_second + "/" + total_minute + ":" + total_second + ")" if playing_mode == 0: process = "顺序播放 " + process elif playing_mode == 1: process = "顺序循环 " + process elif playing_mode == 2: process = "单曲循环 " + process elif playing_mode == 3: process = "随机播放 " + process elif playing_mode == 4: process = "随机循环 " + process else: pass self.screen.addstr(3, self.startcol - 2, process, curses.color_pair(1)) song = self.storage.database["songs"][ self.storage.database["player_info"]["player_list"][self.storage.database["player_info"]["idx"]] ] if 'lyric' not in song.keys() or len(song["lyric"]) <= 0: self.now_lyric = "[00:00.00]暂无歌词 ~>_<~ \n" else: key = now_minute + ":" + now_second for line in song["lyric"]: if key in line: if 'tlyric' not in song.keys() or len(song["tlyric"]) <= 0: self.now_lyric = line else: self.now_lyric = line for tline in song["tlyric"]: if key in tline and self.config.get_item("translation"): self.now_lyric = tline + " || " + self.now_lyric self.now_lyric = re.sub('\[.*?\]', "", self.now_lyric) self.screen.addstr(4, self.startcol - 2, str(self.now_lyric), curses.color_pair(3)) self.screen.refresh() def build_loading(self): self.screen.addstr(7, self.startcol, '享受高品质音乐,loading...', curses.color_pair(1)) self.screen.refresh() # start is the timestamp of this function being called def build_menu(self, datatype, title, datalist, offset, index, step, start): # keep playing info in line 1 curses.noecho() self.screen.move(5, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, title, curses.color_pair(1)) if len(datalist) == 0: self.screen.addstr(8, self.startcol, '这里什么都没有 -,-') else: if datatype == 'main': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'songs' or datatype == 'fmsongs': iter_range = min(len(datalist), offset + step) for i in range(offset, iter_range): # this item is focus if i == index: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) lead = '-> ' + str(i) + '. ' self.screen.addstr(i - offset + 8, self.indented_startcol, lead, curses.color_pair(2)) name = str(datalist[i]['song_name'] + self.space + datalist[i][ 'artist'] + ' < ' + datalist[i]['album_name'] + ' >') # the length decides whether to scoll if truelen(name) < self.x - self.startcol - 1: self.screen.addstr(i - offset + 8, self.indented_startcol + len(lead), name, curses.color_pair(2)) else: name = scrollstring(name + ' ', start) self.screen.addstr(i - offset + 8, self.indented_startcol + len(lead), str(name), curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, 0, ' ' * self.startcol) self.screen.addstr(i - offset + 8, self.startcol, str(str(i) + '. ' + datalist[i]['song_name'] + self.space + datalist[i][ 'artist'] + ' < ' + datalist[i]['album_name'] + ' >')[:int(self.x * 2)]) self.screen.addstr(iter_range - offset + 9, 0, ' ' * self.x) elif datatype == 'artists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + self.space + str( datalist[i]['alias']), curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['artists_name'] + self.space + datalist[i][ 'alias']) elif datatype == 'albums': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i][ 'artists_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['albums_name'] + self.space + datalist[i][ 'artists_name']) elif datatype == 'playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['title'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['title']) elif datatype == 'top_playlists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i]['creator_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]['playlists_name'] + self.space + datalist[i][ 'creator_name']) elif datatype == 'toplists': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'playlist_classes' or datatype == 'playlist_class_detail': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. ' + datalist[i]) elif datatype == 'djchannels': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 8, self.indented_startcol, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset + 8, self.startcol, str(i) + '. ' + datalist[i]['song_name']) elif datatype == 'search': self.screen.move(6, 1) self.screen.clrtobot() self.screen.timeout(-1) self.screen.addstr(8, self.startcol, '选择搜索类型:', curses.color_pair(1)) for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 10, self.indented_startcol, '-> ' + str(i) + '.' + datalist[i - 1], curses.color_pair(2)) else: self.screen.addstr(i - offset + 10, self.startcol, str(i) + '.' + datalist[i - 1]) self.screen.timeout(100) elif datatype == 'help': for i in range(offset, min(len(datalist), offset + step)): if i == index: self.screen.addstr(i - offset + 9, self.indented_startcol, '-> ' + str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][ 1] + ' ' + datalist[i][2], curses.color_pair(2)) else: self.screen.addstr(i - offset + 9, self.startcol, str(i) + '. \'' + (datalist[i][0].upper() + '\'').ljust(11) + datalist[i][ 1] + ' ' + datalist[i][2]) self.screen.addstr(20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存') self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~') self.screen.addstr(22, self.startcol, 'Build with love to music by omi') self.screen.refresh() def build_search(self, stype): self.screen.timeout(-1) netease = self.netease if stype == 'songs': song_name = self.get_param('搜索歌曲:') if song_name == '/return': return [] else: try: data = netease.search(song_name, stype=1) song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] # if search song result do not has mp3Url # send ids to get mp3Url else: for i in range(0, len(data['result']['songs'])): song_ids.append(data['result']['songs'][i]['id']) songs = netease.songs_detail(song_ids) return netease.dig_info(songs, 'songs') except: return [] elif stype == 'artists': artist_name = self.get_param('搜索艺术家:') if artist_name == '/return': return [] else: try: data = netease.search(artist_name, stype=100) if 'artists' in data['result']: artists = data['result']['artists'] return netease.dig_info(artists, 'artists') except: return [] elif stype == 'albums': albums_name = self.get_param('搜索专辑:') if albums_name == '/return': return [] else: try: data = netease.search(albums_name, stype=10) if 'albums' in data['result']: albums = data['result']['albums'] return netease.dig_info(albums, 'albums') except: return [] elif stype == 'search_playlist': search_playlist = self.get_param('搜索网易精选集:') if search_playlist == '/return': return [] else: try: data = netease.search(search_playlist, stype=1000) if 'playlists' in data['result']: playlists = data['result']['playlists'] return netease.dig_info(playlists, 'top_playlists') except: return [] return [] def build_login(self): self.build_login_bar() local_account = self.get_account() local_password = hashlib.md5(self.get_password()).hexdigest() login_info = self.netease.login(local_account, local_password) account = [local_account, local_password] if login_info['code'] != 200: x = self.build_login_error() if x == ord('1'): return self.build_login() else: return -1 else: return [login_info, account] def build_login_bar(self): curses.noecho() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, '请输入登录信息(支持手机登陆)', curses.color_pair(1)) self.screen.addstr(8, self.startcol, "账号:", curses.color_pair(1)) self.screen.addstr(9, self.startcol, "密码:", curses.color_pair(1)) self.screen.move(8, 24) self.screen.refresh() def build_login_error(self): self.screen.move(4, 1) self.screen.timeout(-1) # disable the screen timeout self.screen.clrtobot() self.screen.addstr(8, self.startcol, '艾玛,登录信息好像不对呢 (O_O)#', curses.color_pair(1)) self.screen.addstr(10, self.startcol, '[1] 再试一次') self.screen.addstr(11, self.startcol, '[2] 稍后再试') self.screen.addstr(14, self.startcol, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() self.screen.timeout(100) # restore the screen timeout return x def get_account(self): self.screen.timeout(-1) # disable the screen timeout curses.echo() account = self.screen.getstr(8, self.startcol + 6, 60) self.screen.timeout(100) # restore the screen timeout return account def get_password(self): self.screen.timeout(-1) # disable the screen timeout curses.noecho() password = self.screen.getstr(9, self.startcol + 6, 60) self.screen.timeout(100) # restore the screen timeout return password def get_param(self, prompt_string): # keep playing info in line 1 curses.echo() self.screen.move(4, 1) self.screen.clrtobot() self.screen.addstr(5, self.startcol, prompt_string, curses.color_pair(1)) self.screen.refresh() info = self.screen.getstr(10, self.startcol, 60) if info == '': return '/return' elif info.strip() is '': return self.get_param(prompt_string) else: return info def update_size(self): # get terminal size size = terminalsize.get_terminal_size() self.x = max(size[0], 10) self.y = max(size[1], 25) # update intendations curses.resizeterm(self.y, self.x) self.startcol = int(float(self.x) / 5) self.indented_startcol = max(self.startcol - 3, 0) self.update_space() self.screen.clear() self.screen.refresh() def update_space(self): if self.x > 140: self.space = " - " elif self.x > 80: self.space = " - " else: self.space = " - " self.screen.refresh()
def play_song_list(): play_id = request.args.get('play_id') song_list = NetEase.get_play_song_list(NetEase(),play_id) return render_template("song_list.html",song_list = song_list)
def singer(): singer_list = NetEase.top_artists(NetEase()) return render_template("singer.html",singer_list = singer_list)
def song_list(): singer_id = request.args.get('singer_id') song_list = NetEase.artists(NetEase(),singer_id) return render_template("song_list.html",song_list = song_list)
def index(): hot_music_list = NetEase.hot_song(NetEase()) return render_template("index.html",hot_music_list = hot_music_list)
def top_music_list(hot_id): hot_music_list = NetEase.hot_song_list(NetEase(),hot_id) return render_template("top_music_list.html",hot_music_list = hot_music_list)
''' from api import NetEase import time import gevent from gevent.threadpool import ThreadPool pool = ThreadPool(10) # 考虑到歌单最多10000首歌,故采用多个歌单 wait_song_list = [644264533, 644752348, 644765343, 644738922, 644776005, 644749639, 644756477, 644818427, 644835023, 644810557, 644806753, 644811524, 644800922, 644793786] # wait_song_list = [644810557, 644806753, 644811524, 644800922, 644793786] back_song_list = [583517654, 431743699] joker = NetEase() user_info = {} local_account = '*****@*****.**' local_password = '******' #local_account = '*****@*****.**' #local_password = '******' login_info = joker.login(local_account, local_password) print login_info def track_log(i): song_info = joker.song_info(i) print song_info if song_info: #print song_info try:
class Ui: def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) def build_playinfo(self, song_name, artist, album_name, pause=False): # refresh top 2 line self.screen.move(1,1) self.screen.clrtoeol() self.screen.move(2,1) self.screen.clrtoeol() if pause: self.screen.addstr(1, 6, '_ _ z Z Z', curses.color_pair(3)) else: self.screen.addstr(1, 6, '♫ ♪ ♫ ♪', curses.color_pair(3)) self.screen.addstr(1, 19, song_name + ' - ' + artist + ' < ' + album_name + ' >', curses.color_pair(4)) self.screen.refresh() def build_loading(self): self.screen.addstr(6, 19, '享受高品质音乐,loading...', curses.color_pair(1)) self.screen.refresh() def build_menu(self, datatype, title, datalist, offset, index, step): # keep playing info in line 1 self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(4, 19, title, curses.color_pair(1)) if len(datalist) == 0: self.screen.addstr(8, 19, '这里什么都没有 -,-') else: if datatype == 'main': for i in range( offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]) elif datatype == 'songs': for i in range(offset, min( len(datalist), offset+step) ): # this item is focus if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'] + ' - ' + datalist[i]['artist'] + ' < ' + datalist[i]['album_name'] + ' >', curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name'] + ' - ' + datalist[i]['artist'] + ' < ' + datalist[i]['album_name'] + ' >') elif datatype == 'artists': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + ' - ' + str(datalist[i]['alias']), curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['artists_name'] + ' - ' + datalist[i]['alias']) elif datatype == 'albums': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + ' - ' + datalist[i]['artists_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['albums_name'] + ' - ' + datalist[i]['artists_name']) elif datatype == 'playlists': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + ' - ' + datalist[i]['creator_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['playlists_name'] + ' - ' + datalist[i]['creator_name']) elif datatype == 'djchannels': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name']) elif datatype == 'help': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. \'' + datalist[i][0].upper() + '\' ' + datalist[i][1] + ' ' + datalist[i][2], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. \'' + datalist[i][0].upper() + '\' ' + datalist[i][1] + ' ' + datalist[i][2]) self.screen.addstr(20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存') self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~') self.screen.addstr(22, 19, 'Build with love to music by @vellow') self.screen.refresh() def build_search(self, stype): netease = self.netease if stype == 'songs': song_name = self.get_param('搜索歌曲:') try: data = netease.search(song_name, stype=1) song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] # if search song result do not has mp3Url # send ids to get mp3Url else: for i in range(0, len(data['result']['songs']) ): song_ids.append( data['result']['songs'][i]['id'] ) songs = netease.songs_detail(song_ids) return netease.dig_info(songs, 'songs') except: return [] elif stype == 'artists': artist_name = self.get_param('搜索艺术家:') try: data = netease.search(artist_name, stype=100) if 'artists' in data['result']: artists = data['result']['artists'] return netease.dig_info(artists, 'artists') except: return [] elif stype == 'albums': artist_name = self.get_param('搜索专辑:') try: data = netease.search(artist_name, stype=10) if 'albums' in data['result']: albums = data['result']['albums'] return netease.dig_info(albums, 'albums') except: return [] elif stype == 'playlists': artist_name = self.get_param('搜索网易精选集:') try: data = netease.search(artist_name, stype=1000) if 'playlists' in data['result']: playlists = data['result']['playlists'] return netease.dig_info(playlists, 'playlists') except: return [] return [] def build_search_menu(self): self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(8, 19, '选择搜索类型:', curses.color_pair(1)) self.screen.addstr(10,19, '[1] 歌曲') self.screen.addstr(11,19, '[2] 艺术家') self.screen.addstr(12,19, '[3] 专辑') self.screen.addstr(13,19, '[4] 网易精选集') self.screen.addstr(16,19, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() return x def build_login(self): info = self.get_param('请输入登录信息, e.g: [email protected] 123456') account = info.split(' ') if len(account) != 2: return self.build_login() login_info = self.netease.login(account[0], account[1]) if login_info['code'] != 200: x = self.build_login_error() if x == ord('1'): return self.build_login() else: return -1 else: return [login_info, account] def build_login_error(self): self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(8, 19, '艾玛,登录信息好像不对呢 (O_O)#', curses.color_pair(1)) self.screen.addstr(10,19, '[1] 再试一次') self.screen.addstr(11,19, '[2] 稍后再试') self.screen.addstr(14,19, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() return x def get_param(self, prompt_string): # keep playing info in line 1 self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(5, 19, prompt_string, curses.color_pair(1)) self.screen.refresh() info = self.screen.getstr(10, 19, 60) if info.strip() is '': return self.get_param(prompt_string) else: return info
class Ui: def __init__(self): self.screen = curses.initscr() # charactor break buffer curses.cbreak() self.screen.keypad(1) self.netease = NetEase() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) def build_playinfo(self, song_name, artist, album_name, pause=False): curses.noecho() # refresh top 2 line self.screen.move(1,1) self.screen.clrtoeol() self.screen.move(2,1) self.screen.clrtoeol() if pause: self.screen.addstr(1, 6, '_ _ z Z Z', curses.color_pair(3)) else: self.screen.addstr(1, 6, '♫ ♪ ♫ ♪', curses.color_pair(3)) self.screen.addstr(1, 19, song_name + ' - ' + artist + ' < ' + album_name + ' >', curses.color_pair(4)) self.screen.refresh() def build_loading(self): self.screen.addstr(6, 19, '享受高品质音乐,loading...', curses.color_pair(1)) self.screen.refresh() def build_menu(self, datatype, title, datalist, offset, index, step): # keep playing info in line 1 curses.noecho() self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(4, 19, title, curses.color_pair(1)) if len(datalist) == 0: self.screen.addstr(8, 19, '这里什么都没有 -,-') else: if datatype == 'main': for i in range( offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]) elif datatype == 'songs': for i in range(offset, min( len(datalist), offset+step) ): # this item is focus if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'] + ' - ' + datalist[i]['artist'] + ' < ' + datalist[i]['album_name'] + ' >', curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name'] + ' - ' + datalist[i]['artist'] + ' < ' + datalist[i]['album_name'] + ' >') elif datatype == 'artists': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['artists_name'] + ' - ' + str(datalist[i]['alias']), curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['artists_name'] + ' - ' + datalist[i]['alias']) elif datatype == 'albums': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['albums_name'] + ' - ' + datalist[i]['artists_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['albums_name'] + ' - ' + datalist[i]['artists_name']) elif datatype == 'playlists': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['title'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['title']) elif datatype == 'top_playlists': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['playlists_name'] + ' - ' + datalist[i]['creator_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['playlists_name'] + ' - ' + datalist[i]['creator_name']) elif datatype == 'playlist_classes' or datatype == 'playlist_class_detail': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]) elif datatype == 'djchannels': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. ' + datalist[i]['song_name'], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. ' + datalist[i]['song_name']) elif datatype == 'help': for i in range(offset, min( len(datalist), offset+step) ): if i == index: self.screen.addstr(i - offset +8, 16, '-> ' + str(i) + '. \'' + datalist[i][0].upper() + '\' ' + datalist[i][1] + ' ' + datalist[i][2], curses.color_pair(2)) else: self.screen.addstr(i - offset +8, 19, str(i) + '. \'' + datalist[i][0].upper() + '\' ' + datalist[i][1] + ' ' + datalist[i][2]) self.screen.addstr(20, 6, 'NetEase-MusicBox 基于Python,所有版权音乐来源于网易,本地不做任何保存') self.screen.addstr(21, 10, '按 [G] 到 Github 了解更多信息,帮助改进,或者Star表示支持~~') self.screen.addstr(22, 19, 'Build with love to music by omi') self.screen.refresh() def build_search(self, stype): netease = self.netease if stype == 'songs': song_name = self.get_param('搜索歌曲:') try: data = netease.search(song_name, stype=1) song_ids = [] if 'songs' in data['result']: if 'mp3Url' in data['result']['songs']: songs = data['result']['songs'] # if search song result do not has mp3Url # send ids to get mp3Url else: for i in range(0, len(data['result']['songs']) ): song_ids.append( data['result']['songs'][i]['id'] ) songs = netease.songs_detail(song_ids) return netease.dig_info(songs, 'songs') except: return [] elif stype == 'artists': artist_name = self.get_param('搜索艺术家:') try: data = netease.search(artist_name, stype=100) if 'artists' in data['result']: artists = data['result']['artists'] return netease.dig_info(artists, 'artists') except: return [] elif stype == 'albums': artist_name = self.get_param('搜索专辑:') try: data = netease.search(artist_name, stype=10) if 'albums' in data['result']: albums = data['result']['albums'] return netease.dig_info(albums, 'albums') except: return [] elif stype == 'search_playlist': artist_name = self.get_param('搜索网易精选集:') try: data = netease.search(artist_name, stype=1000) if 'playlists' in data['result']: playlists = data['result']['playlists'] return netease.dig_info(playlists, 'top_playlists') except: return [] return [] def build_search_menu(self): self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(8, 19, '选择搜索类型:', curses.color_pair(1)) self.screen.addstr(10,19, '[1] 歌曲') self.screen.addstr(11,19, '[2] 艺术家') self.screen.addstr(12,19, '[3] 专辑') self.screen.addstr(13,19, '[4] 网易精选集') self.screen.addstr(16,19, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() return x def build_login(self): curses.noecho() info = self.get_param('请输入登录信息, e.g: [email protected] 123456') account = info.split(' ') if len(account) != 2: return self.build_login() login_info = self.netease.login(account[0], account[1]) if login_info['code'] != 200: x = self.build_login_error() if x == ord('1'): return self.build_login() else: return -1 else: return [login_info, account] def build_login_error(self): self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(8, 19, '艾玛,登录信息好像不对呢 (O_O)#', curses.color_pair(1)) self.screen.addstr(10,19, '[1] 再试一次') self.screen.addstr(11,19, '[2] 稍后再试') self.screen.addstr(14,19, '请键入对应数字:', curses.color_pair(2)) self.screen.refresh() x = self.screen.getch() return x def get_param(self, prompt_string): # keep playing info in line 1 curses.echo() self.screen.move(4,1) self.screen.clrtobot() self.screen.addstr(5, 19, prompt_string, curses.color_pair(1)) self.screen.refresh() info = self.screen.getstr(10, 19, 60) if info.strip() is '': return self.get_param(prompt_string) else: return info
class Menu: def __init__(self): reload(sys) sys.setdefaultencoding('UTF-8') self.config = Config() self.datatype = 'main' self.title = '网易云音乐' self.datalist = [ '排行榜', '艺术家', '新碟上架', '精选歌单', '我的歌单', 'DJ节目', '每日推荐', '私人FM', '搜索', '帮助' ] self.offset = 0 self.index = 0 self.storage = Storage() self.storage.load() self.collection = self.storage.database['collections'][0] self.player = Player() self.cache = Cache() self.ui = Ui() self.netease = NetEase() self.screen = curses.initscr() self.screen.keypad(1) self.step = 10 self.stack = [] self.djstack = [] self.userid = self.storage.database["user"]["user_id"] self.username = self.storage.database["user"]["nickname"] self.resume_play = True self.at_playing_list = False signal.signal(signal.SIGWINCH, self.change_term) signal.signal(signal.SIGINT, self.send_kill) self.START = time.time() def change_term(self, signum, frame): self.ui.screen.clear() self.ui.screen.refresh() def send_kill(self, signum, fram): self.player.stop() self.cache.quit() self.storage.save() curses.endwin() sys.exit() def alert(self, version): latest = Menu().check_version() if latest != version: if platform.system() == 'Darwin': os.system( '/usr/bin/osascript -e \'display notification "MusicBox Update is available"sound name "/System/Library/Sounds/Ping.aiff"\'' ) time.sleep(0.5) os.system( '/usr/bin/osascript -e \'display notification "NetEase-MusicBox installed version:' + version + '\nNetEase-MusicBox latest version:' + latest + '"\'') else: os.system( '/usr/bin/notify-send "MusicBox Update is available"') def check_version(self): # 检查更新 tree = ET.ElementTree(ET.fromstring(str(self.netease.get_version()))) root = tree.getroot() return root[0][4][0][0].text def start_fork(self, version): pid = os.fork() if pid == 0: Menu().alert(version) else: Menu().start() def play_pause(self): if len(self.storage.database["player_info"]["player_list"]) == 0: return if self.player.pause_flag: self.player.resume() else: self.player.pause() time.sleep(0.1) def next_song(self): if len(self.storage.database["player_info"]["player_list"]) == 0: return self.player.next() time.sleep(0.1) def previous_song(self): if len(self.storage.database["player_info"]["player_list"]) == 0: return self.player.prev() time.sleep(0.1) def start(self): self.START = time.time() // 1 self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, self.index, self.step, self.START) self.ui.build_process_bar( self.player.process_location, self.player.process_length, self.player.playing_flag, self.player.pause_flag, self.storage.database['player_info']['playing_mode']) self.stack.append([ self.datatype, self.title, self.datalist, self.offset, self.index ]) if bind_global: keybinder.bind(self.config.get_item("global_play_pause"), self.play_pause) keybinder.bind(self.config.get_item("global_next"), self.next_song) keybinder.bind(self.config.get_item("global_previous"), self.previous_song) while True: datatype = self.datatype title = self.title datalist = self.datalist offset = self.offset idx = index = self.index step = self.step stack = self.stack djstack = self.djstack self.screen.timeout(500) key = self.screen.getch() if bind_global: keybinder.gtk.main_iteration(False) self.ui.screen.refresh() # term resize if key == -1: self.ui.update_size() self.player.update_size() # 退出 if key == ord('q'): break # 退出并清除用户信息 if key == ord('w'): self.storage.database['user'] = { "username": "", "password": "", "user_id": "", "nickname": "", } try: os.remove(self.storage.cookie_path) except: break break # 上移 elif key == ord('k'): self.index = carousel(offset, min(len(datalist), offset + step) - 1, idx - 1) self.START = time.time() # 下移 elif key == ord('j'): self.index = carousel(offset, min(len(datalist), offset + step) - 1, idx + 1) self.START = time.time() # 数字快捷键 elif ord('0') <= key <= ord('9'): if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help': continue idx = key - ord('0') self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, idx, self.step, self.START) self.ui.build_loading() self.dispatch_enter(idx) self.index = 0 self.offset = 0 # 向上翻页 elif key == ord('u'): if offset == 0: continue self.START = time.time() self.offset -= step # e.g. 23 - 10 = 13 --> 10 self.index = (index - step) // step * step # 向下翻页 elif key == ord('d'): if offset + step >= len(datalist): continue self.START = time.time() self.offset += step # e.g. 23 + 10 = 33 --> 30 self.index = (index + step) // step * step # 前进 elif key == ord('l') or key == 10: if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help': continue self.START = time.time() self.ui.build_loading() self.dispatch_enter(idx) self.index = 0 self.offset = 0 # 回退 elif key == ord('h'): # if not main menu if len(self.stack) == 1: continue self.START = time.time() up = stack.pop() self.datatype = up[0] self.title = up[1] self.datalist = up[2] self.offset = up[3] self.index = up[4] self.at_playing_list = False # 搜索 elif key == ord('f'): # 8 is the 'search' menu self.dispatch_enter(8) # 播放下一曲 elif key == ord(']'): self.next_song() # 播放上一曲 elif key == ord('['): self.previous_song() # 增加音量 elif key == ord('='): self.player.volume_up() # 减少音量 elif key == ord('-'): self.player.volume_down() # 随机播放 elif key == ord('?'): if len(self.storage.database["player_info"] ["player_list"]) == 0: continue self.player.shuffle() time.sleep(0.1) # 喜爱 elif key == ord(','): self.request_api(self.netease.fm_like, self.player.get_playing_id()) # 删除FM elif key == ord('.'): if self.datatype == 'fmsongs': if len(self.storage.database["player_info"] ["player_list"]) == 0: continue self.player.next() self.request_api(self.netease.fm_trash, self.player.get_playing_id()) time.sleep(0.1) # 下一FM elif key == ord('/'): if self.datatype == 'fmsongs': if len(self.storage.database["player_info"] ["player_list"]) == 0: continue self.player.next() time.sleep(0.1) # 播放、暂停 elif key == ord(' '): # If not open a new playing list, just play and pause. try: if self.datalist[idx]['song_id'] == self.player.playing_id: self.player.play_and_pause( self.storage.database['player_info']['idx']) time.sleep(0.1) continue except: pass # If change to a new playing list. Add playing list and play. if datatype == 'songs': self.resume_play = False self.player.new_player_list('songs', self.title, self.datalist, -1) self.player.end_callback = None self.player.play_and_pause(idx) self.at_playing_list = True elif datatype == 'djchannels': self.resume_play = False self.player.new_player_list('djchannels', self.title, self.datalist, -1) self.player.end_callback = None self.player.play_and_pause(idx) self.at_playing_list = True elif datatype == 'fmsongs': self.resume_play = False self.storage.database['player_info']['playing_mode'] = 0 self.player.new_player_list('fmsongs', self.title, self.datalist, -1) self.player.end_callback = self.fm_callback self.player.play_and_pause(idx) self.at_playing_list = True else: self.player.play_and_pause( self.storage.database['player_info']['idx']) time.sleep(0.1) # 加载当前播放列表 elif key == ord('p'): if len(self.storage.database['player_info'] ['player_list']) == 0: continue if not self.at_playing_list: self.stack.append([ self.datatype, self.title, self.datalist, self.offset, self.index ]) self.at_playing_list = True self.datatype = self.storage.database['player_info'][ 'player_list_type'] self.title = self.storage.database['player_info'][ 'player_list_title'] self.datalist = [] for i in self.storage.database['player_info']['player_list']: self.datalist.append(self.storage.database['songs'][i]) self.index = self.storage.database['player_info']['idx'] self.offset = self.storage.database['player_info'][ 'idx'] / self.step * self.step if self.resume_play: if self.datatype == "fmsongs": self.player.end_callback = self.fm_callback else: self.player.end_callback = None self.storage.database['player_info']['idx'] = -1 self.player.play_and_pause(self.index) self.resume_play = False # 播放模式切换 elif key == ord('P'): self.storage.database['player_info']['playing_mode'] = \ (self.storage.database['player_info']['playing_mode'] + 1) % 5 # 添加到打碟歌单 elif key == ord('a'): if datatype == 'songs' and len(datalist) != 0: self.djstack.append(datalist[idx]) elif datatype == 'artists': pass # 加载打碟歌单 elif key == ord('z'): self.stack.append([datatype, title, datalist, offset, index]) self.datatype = 'songs' self.title = '网易云音乐 > 打碟' self.datalist = self.djstack self.offset = 0 self.index = 0 # 添加到收藏歌曲 elif key == ord('s'): if (datatype == 'songs' or datatype == 'djchannels') and len(datalist) != 0: self.collection.append(datalist[idx]) # 加载收藏歌曲 elif key == ord('c'): self.stack.append([datatype, title, datalist, offset, index]) self.datatype = 'songs' self.title = '网易云音乐 > 收藏' self.datalist = self.collection self.offset = 0 self.index = 0 # 从当前列表移除 elif key == ord('r'): if (datatype == 'songs' or datatype == 'djchannels') and len(datalist) != 0: self.datalist.pop(idx) self.index = carousel( offset, min(len(datalist), offset + step) - 1, idx) # 当前项目下移 elif key == ord("J"): if datatype != 'main' and len( datalist) != 0 and idx + 1 != len(self.datalist): self.START = time.time() song = self.datalist.pop(idx) self.datalist.insert(idx + 1, song) self.index = idx + 1 # 翻页 if self.index >= offset + step: self.offset = offset + step # 当前项目上移 elif key == ord("K"): if datatype != 'main' and len(datalist) != 0 and idx != 0: self.START = time.time() song = self.datalist.pop(idx) self.datalist.insert(idx - 1, song) self.index = idx - 1 # 翻页 if self.index < offset: self.offset = offset - step elif key == ord('m'): if datatype != 'main': self.stack.append( [datatype, title, datalist, offset, index]) self.datatype = self.stack[0][0] self.title = self.stack[0][1] self.datalist = self.stack[0][2] self.offset = 0 self.index = 0 elif key == ord('g'): if datatype == 'help': webbrowser.open_new_tab( 'https://github.com/darknessomi/musicbox') self.ui.build_process_bar( self.player.process_location, self.player.process_length, self.player.playing_flag, self.player.pause_flag, self.storage.database['player_info']['playing_mode']) self.ui.build_menu(self.datatype, self.title, self.datalist, self.offset, self.index, self.step, self.START) self.player.stop() self.cache.quit() self.storage.save() curses.endwin() def dispatch_enter(self, idx): # The end of stack netease = self.netease datatype = self.datatype title = self.title datalist = self.datalist offset = self.offset index = self.index self.stack.append([datatype, title, datalist, offset, index]) if datatype == 'main': self.choice_channel(idx) # 该艺术家的热门歌曲 elif datatype == 'artists': artist_id = datalist[idx]['artist_id'] songs = netease.artists(artist_id) self.datatype = 'songs' self.datalist = netease.dig_info(songs, 'songs') self.title += ' > ' + datalist[idx]['artists_name'] # 该专辑包含的歌曲 elif datatype == 'albums': album_id = datalist[idx]['album_id'] songs = netease.album(album_id) self.datatype = 'songs' self.datalist = netease.dig_info(songs, 'songs') self.title += ' > ' + datalist[idx]['albums_name'] # 精选歌单选项 elif datatype == 'playlists': data = self.datalist[idx] self.datatype = data['datatype'] self.datalist = netease.dig_info(data['callback'](), self.datatype) self.title += ' > ' + data['title'] # 全站置顶歌单包含的歌曲 elif datatype == 'top_playlists': log.debug(datalist) playlist_id = datalist[idx]['playlist_id'] songs = netease.playlist_detail(playlist_id) self.datatype = 'songs' self.datalist = netease.dig_info(songs, 'songs') self.title += ' > ' + datalist[idx]['playlists_name'] # 分类精选 elif datatype == 'playlist_classes': # 分类名称 data = self.datalist[idx] self.datatype = 'playlist_class_detail' self.datalist = netease.dig_info(data, self.datatype) self.title += ' > ' + data log.debug(self.datalist) # 某一分类的详情 elif datatype == 'playlist_class_detail': # 子类别 data = self.datalist[idx] self.datatype = 'top_playlists' self.datalist = netease.dig_info(netease.top_playlists(data), self.datatype) log.debug(self.datalist) self.title += ' > ' + data # 歌曲榜单 elif datatype == 'toplists': songs = netease.top_songlist(idx) self.title += ' > ' + self.datalist[idx] self.datalist = netease.dig_info(songs, 'songs') self.datatype = 'songs' # 搜索菜单 elif datatype == 'search': ui = self.ui # no need to do stack.append, Otherwise there will be a bug when you input key 'h' to return # if idx in range(1, 5): # self.stack.append([self.datatype, self.title, self.datalist, self.offset, self.index]) self.index = 0 self.offset = 0 if idx == 0: # 搜索结果可以用top_playlists处理 self.datatype = 'top_playlists' self.datalist = ui.build_search('search_playlist') self.title = '精选歌单搜索列表' elif idx == 1: self.datatype = 'songs' self.datalist = ui.build_search('songs') self.title = '歌曲搜索列表' elif idx == 2: self.datatype = 'artists' self.datalist = ui.build_search('artists') self.title = '艺术家搜索列表' elif idx == 3: self.datatype = 'albums' self.datalist = ui.build_search('albums') self.title = '专辑搜索列表' def fm_callback(self): log.debug("FM CallBack.") data = self.get_new_fm() self.player.append_songs(data) if self.datatype == 'fmsongs': if len(self.storage.database['player_info']['player_list']) == 0: return self.datatype = self.storage.database['player_info'][ 'player_list_type'] self.title = self.storage.database['player_info'][ 'player_list_title'] self.datalist = [] for i in self.storage.database['player_info']['player_list']: self.datalist.append(self.storage.database['songs'][i]) self.index = self.storage.database['player_info']['idx'] self.offset = self.storage.database['player_info'][ 'idx'] / self.step * self.step def request_api(self, func, *args): if self.storage.database['user']['user_id'] != "": result = func(*args) if result != -1: return result log.debug("Re Login.") user_info = {} if self.storage.database['user']['username'] != "": user_info = self.netease.login( self.storage.database['user']['username'], self.storage.database['user']['password']) if self.storage.database['user'][ 'username'] == "" or user_info['code'] != 200: data = self.ui.build_login() # 取消登录 if data == -1: return -1 user_info = data[0] self.storage.database['user']['username'] = data[1][0] self.storage.database['user']['password'] = data[1][1] self.storage.database['user']['user_id'] = user_info['account'][ 'id'] self.storage.database['user']['nickname'] = user_info['profile'][ 'nickname'] self.userid = self.storage.database["user"]["user_id"] self.username = self.storage.database["user"]["nickname"] return func(*args) def get_new_fm(self): myplaylist = [] for count in range(0, 1): data = self.request_api(self.netease.personal_fm) if data == -1: break myplaylist += data time.sleep(0.2) return self.netease.dig_info(myplaylist, "fmsongs") def choice_channel(self, idx): # 排行榜 netease = self.netease if idx == 0: self.datalist = netease.return_toplists() self.title += ' > 排行榜' self.datatype = 'toplists' # 艺术家 elif idx == 1: artists = netease.top_artists() self.datalist = netease.dig_info(artists, 'artists') self.title += ' > 艺术家' self.datatype = 'artists' # 新碟上架 elif idx == 2: albums = netease.new_albums() self.datalist = netease.dig_info(albums, 'albums') self.title += ' > 新碟上架' self.datatype = 'albums' # 精选歌单 elif idx == 3: self.datalist = [{ 'title': '全站置顶', 'datatype': 'top_playlists', 'callback': netease.top_playlists }, { 'title': '分类精选', 'datatype': 'playlist_classes', 'callback': netease.playlist_classes }] self.title += ' > 精选歌单' self.datatype = 'playlists' # 我的歌单 elif idx == 4: myplaylist = self.request_api(self.netease.user_playlist, self.userid) if myplaylist == -1: return self.datatype = 'top_playlists' self.datalist = netease.dig_info(myplaylist, self.datatype) self.title += ' > ' + self.username + ' 的歌单' # DJ节目 elif idx == 5: self.datatype = 'djchannels' self.title += ' > DJ节目' self.datalist = netease.djchannels() # 每日推荐 elif idx == 6: self.datatype = 'songs' self.title += ' > 每日推荐' myplaylist = self.request_api(self.netease.recommend_playlist) if myplaylist == -1: return self.datalist = self.netease.dig_info(myplaylist, self.datatype) # 私人FM elif idx == 7: self.datatype = 'fmsongs' self.title += ' > 私人FM' self.datalist = self.get_new_fm() # 搜索 elif idx == 8: self.datatype = 'search' self.title += ' > 搜索' self.datalist = ['歌曲', '艺术家', '专辑', '网易精选集'] # 帮助 elif idx == 9: self.datatype = 'help' self.title += ' > 帮助' self.datalist = shortcut self.offset = 0 self.index = 0
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: betta ''' netease music api ''' from api import NetEase import json import _mysql import MySQLdb from time import sleep import time joker = NetEase() user_info = {} local_account = '*****@*****.**' local_password = '******' #login_info = joker.login(local_account, local_password) #print login_info def save2sql(conn, data, song_id): try: sql = ( "INSERT INTO netease_music_comments (content, song_id, liked_count, user_id, comment_id, send_time) " "VALUES (%s, %s, %s, %s, %s, %s)") time_tmp = time.localtime(data['time'] / 1000) cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time_tmp) sql_data = (data['content'], song_id, data['likedCount'],