Skip to content

Commit

Permalink
[Fix] false alarm in log and remove useless try catch (darknessomi#433)
Browse files Browse the repository at this point in the history
  • Loading branch information
kigawas authored Nov 7, 2016
1 parent a5fd199 commit a1b96ca
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 75 deletions.
3 changes: 1 addition & 2 deletions NEMbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@
import sys

from .menu import Menu

version = "0.2.3.5"


def start():
nembox_menu = Menu()
try:
nembox_menu.start_fork(version)
except (OSError, TypeError, ValueError):
except (OSError, TypeError, ValueError, KeyError):
# clean up terminal while failed
nembox_menu.screen.keypad(1)
curses.echo()
Expand Down
27 changes: 13 additions & 14 deletions NEMbox/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,14 @@ def __init__(self):
self.session.cookies = LWPCookieJar(self.storage.cookie_path)
try:
self.session.cookies.load()
self.file = open(self.storage.cookie_path, 'r')
cookie = self.file.read()
self.file.close()
pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
str = pattern.findall(cookie)
if str:
if str[0] < time.strftime('%Y-%m-%d',
time.localtime(time.time())):
cookie = ''
if os.path.isfile(self.storage.cookie_path):
self.file = open(self.storage.cookie_path, 'r')
cookie = self.file.read()
self.file.close()
expire_time = re.compile(r'\d{4}-\d{2}-\d{2}').findall(cookie)
if expire_time:
if expire_time[0] < time.strftime('%Y-%m-%d', time.localtime(time.time())):
self.storage.database['user'] = {
'username': '',
'password': '',
Expand All @@ -209,8 +209,9 @@ def httpRequest(self,
urlencoded=None,
callback=None,
timeout=None):
connection = json.loads(self.rawHttpRequest(
method, action, query, urlencoded, callback, timeout))
connection = json.loads(
self.rawHttpRequest(method, action, query, urlencoded, callback, timeout)
)
return connection

def rawHttpRequest(self,
Expand Down Expand Up @@ -593,8 +594,7 @@ def channel_detail(self, channelids, offset=0):
channelids[i])
try:
data = self.httpRequest('GET', action)
channel = self.dig_info(data['program']['mainSong'],
'channels')
channel = self.dig_info(data['program']['mainSong'], 'channels')
channels.append(channel)
except requests.exceptions.RequestException as e:
log.error(e)
Expand Down Expand Up @@ -709,5 +709,4 @@ def dig_info(self, data, dig_type):
print(geturl_new_api(ne.songs_detail([27902910])[0])) # MD 128k, fallback
print(ne.songs_detail_new_api([27902910])[0]['url'])
print(ne.songs_detail([405079776])[0]['mp3Url']) # old api
print(requests.get(ne.songs_detail([405079776])[0][
'mp3Url']).status_code) # 404
print(requests.get(ne.songs_detail([405079776])[0]['mp3Url']).status_code) # 404
4 changes: 2 additions & 2 deletions NEMbox/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,5 +219,5 @@ def get_item(self, name):
if name not in self.config.keys():
if name not in self.default_config.keys():
return None
return self.default_config[name]['value']
return self.config[name]['value']
return self.default_config[name].get('value')
return self.config[name].get('value')
3 changes: 1 addition & 2 deletions NEMbox/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ def getLogger(name):
fh = logging.FileHandler(FILE_NAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - %(name)s:%(lineno)s: %(message)s')
) # NOQA
'%(asctime)s - %(levelname)s - %(name)s:%(lineno)s: %(message)s')) # NOQA
log.addHandler(fh)

return log
63 changes: 25 additions & 38 deletions NEMbox/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
standard_library.install_aliases()

import curses
import locale
import threading
import sys
import os
import time
import signal
import webbrowser
import locale
import xml.etree.cElementTree as ET


Expand All @@ -37,6 +37,8 @@
from . import logger


locale.setlocale(locale.LC_ALL, '')

log = logger.getLogger(__name__)

try:
Expand All @@ -51,12 +53,9 @@
if os.path.isdir(Constant.conf_dir) is False:
os.mkdir(Constant.conf_dir)

locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()


# carousel x in [left, right]
def carousel(left, right, x):
# carousel x in [left, right]
if x > right:
return left
elif x < left:
Expand Down Expand Up @@ -156,12 +155,12 @@ def check_version(self):
# 检查更新 && 签到
try:
mobilesignin = self.netease.daily_signin(0)
if mobilesignin != -1 and mobilesignin['code'] != -2:
notify('Mobile signin success', 1)
if mobilesignin != -1 and mobilesignin['code'] not in (-2, 301):
notify('移动端签到成功', 1)
time.sleep(0.5)
pcsignin = self.netease.daily_signin(1)
if pcsignin != -1 and pcsignin['code'] != -2:
notify('PC signin success', 1)
if pcsignin != -1 and pcsignin['code'] not in (-2, 301):
notify('PC端签到成功', 1)
tree = ET.ElementTree(ET.fromstring(self.netease.get_version()))
root = tree.getroot()
return root[0][4][0][0].text
Expand Down Expand Up @@ -202,17 +201,15 @@ def previous_song(self):

def bind_keys(self):
if BINDABLE:
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)
keybinder.bind(self.config.get_item('global_play_pause'), self.play_pause) # noqa
keybinder.bind(self.config.get_item('global_next'), self.next_song) # noqa
keybinder.bind(self.config.get_item('global_previous'), self.previous_song) # noqa

def unbind_keys(self):
if BINDABLE:
keybinder.unbind(self.config.get_item('global_play_pause'))
keybinder.unbind(self.config.get_item('global_next'))
keybinder.unbind(self.config.get_item('global_previous'))
keybinder.unbind(self.config.get_item('global_play_pause')) # noqa
keybinder.unbind(self.config.get_item('global_next')) # noqa
keybinder.unbind(self.config.get_item('global_previous')) # noqa

def start(self):
self.START = time.time() // 1
Expand All @@ -222,12 +219,9 @@ def start(self):
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])
try:
self.bind_keys()
except KeyError as e:
log.warning(e)
self.stack.append([self.datatype, self.title, self.datalist, self.offset, self.index])

self.bind_keys() # deprecated keybinder
show_lyrics_new_process()
while True:
datatype = self.datatype
Expand All @@ -240,7 +234,7 @@ def start(self):
self.screen.timeout(500)
key = self.screen.getch()
if BINDABLE:
keybinder.gtk.main_iteration(False)
keybinder.gtk.main_iteration(False) # noqa
self.ui.screen.refresh()

# term resize
Expand All @@ -250,10 +244,7 @@ def start(self):

# 退出
if key == ord('q'):
try:
self.unbind_keys()
except KeyError as e:
log.warning(e)
self.unbind_keys()
break

# 退出并清除用户信息
Expand Down Expand Up @@ -488,7 +479,7 @@ def start(self):
self.title = '网易云音乐 > 专辑 > %s' % album_name
for i in range(len(self.datalist)):
if self.datalist[i]['song_id'] == song_id:
self.offset = i - i%step
self.offset = i - i % step
self.index = i
break

Expand Down Expand Up @@ -795,25 +786,22 @@ def request_api(self, func, *args):
result = func(*args)
if result != -1:
return result
log.debug('Re Login.')
notify('You need to log in')
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:
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.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)
Expand Down Expand Up @@ -868,8 +856,7 @@ def choice_channel(self, idx):

# 我的歌单
elif idx == 4:
myplaylist = self.request_api(self.netease.user_playlist,
self.userid)
myplaylist = self.request_api(self.netease.user_playlist, self.userid)
if myplaylist == -1:
return
self.datatype = 'top_playlists'
Expand Down
20 changes: 7 additions & 13 deletions NEMbox/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,14 +357,13 @@ def next_idx(self):
playinglist_len = len(self.info['playing_list'])
# When you regenerate playing list
# you should keep previous song same.
try:
self._swap_song()
except Exception as e:
log.error(e)
self._swap_song()

self.info['ridx'] += 1
# Out of border
if self.info['playing_mode'] == 4:
self.info['ridx'] %= playinglist_len

if self.info['ridx'] >= playinglist_len:
self.info['idx'] = playlist_len
else:
Expand Down Expand Up @@ -446,23 +445,18 @@ def volume_down(self):
self.popen_handler.stdin.flush()

def update_size(self):
try:
self.ui.update_size()
self.ui.update_size()
if self.songs and self.info['player_list']:
item = self.songs[self.info['player_list'][self.info['idx']]]
if self.playing_flag:
self.ui.build_playinfo(item['song_name'], item['artist'],
item['album_name'], item['quality'],
time.time())
if self.pause_flag:
self.ui.build_playinfo(item['song_name'],
item['artist'],
item['album_name'],
item['quality'],
self.ui.build_playinfo(item['song_name'], item['artist'],
item['album_name'], item['quality'],
time.time(),
pause=True)
except Exception as e:
log.error(e)
pass

def cacheSong1time(self, song_id, song_name, artist, song_url):
def cacheExit(song_id, path):
Expand Down
4 changes: 0 additions & 4 deletions NEMbox/scrollstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
from future import standard_library
standard_library.install_aliases()
from time import time
import locale

locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()


class scrollstring(object):
Expand Down

0 comments on commit a1b96ca

Please sign in to comment.