Ejemplo n.º 1
0
def urlopen(_url, use_cache=True, retries=RETRIES):
    # set host port from 81 to 80, to fix image problem
    url = _url.replace(':81', '')
    if use_cache and ldb_imported:
        key = hash_byte(url)
        try:
            content = ldb_get(key)
            if content and len(content) > 10:
                try:
                    timestamp = int(content[:10].decode())
                    if (time.time() - timestamp) < CACHE_TIMEOUT:
                        return content[10:]
                except (ValueError, UnicodeDecodeError):
                    logger.debug(traceback.format_exc())
        except KeyError:
            logger.debug(traceback.format_exc())
    for i in range(retries):
        try:
            req = request.urlopen(url, timeout=TIMEOUT)
            req_content = req.read()
            if use_cache and ldb_imported:
                ldb_put(key, str(int(time.time())).encode() + req_content)
            return req_content
        except URLError:
            logger.warn(traceback.format_exc())
            logger.warn('Net.urlopen, url: %s' % url)
    return None
Ejemplo n.º 2
0
 def init_notify(self):
     try:
         self.notify = Notify.Notification.new(Config.APPNAME, '',
                                               Config.NAME)
     except Exception:
         logger.warn('App.init_notify: %s' % traceback.format_exc())
         self.notify = None
Ejemplo n.º 3
0
def urlopen(_url, use_cache=True, retries=RETRIES):
    # set host port from 81 to 80, to fix image problem
    url = _url.replace(':81', '')
    if use_cache and ldb_imported:
        key = hash_byte(url)
        try:
            content = ldb_get(key)
            if content and len(content) > 10:
                try:
                    timestamp = int(content[:10].decode())
                    if (time.time() - timestamp) < CACHE_TIMEOUT:
                        return content[10:]
                except (ValueError, UnicodeDecodeError):
                    logger.debug(traceback.format_exc())
        except KeyError:
            logger.debug(traceback.format_exc())
    for i in range(retries):
        try:
            req = request.urlopen(url, timeout=TIMEOUT)
            req_content = req.read()
            if use_cache and ldb_imported:
                ldb_put(key, str(int(time.time())).encode() + req_content)
            return req_content
        except URLError:
            logger.warn(traceback.format_exc())
            logger.warn('Net.urlopen, url: %s' % url)
    return None
Ejemplo n.º 4
0
 def init_notify(self):
     try:
         self.notify = Notify.Notification.new(Config.APPNAME, '',
                                               Config.NAME)
     except Exception:
         logger.warn('App.init_notify: %s' % traceback.format_exc())
         self.notify = None
Ejemplo n.º 5
0
 def _on_get_themes(nodes, error):
     if not nodes:
         logger.warn('_on_get_themes(): %s, %s' % (nodes, error))
         return
     urls = []
     tree_iters = []
     for node in nodes:
         tree_iter = self.liststore_main.append([
             Config.ANONYMOUS_PIXBUF,
             Widgets.unescape(node['name']),
             int(node['nid']),
             Widgets.unescape(node['info']),
             Widgets.set_tooltip(node['name'], node['info']),
         ])
         urls.append(node['pic'])
         tree_iters.append(tree_iter)
     self.liststore_main.timestamp = time.time()
     Net.async_call(Net.update_liststore_images, self.liststore_main, 0,
                    tree_iters, urls)
Ejemplo n.º 6
0
 def _on_get_themes(nodes, error):
     if not nodes:
         logger.warn('_on_get_themes(): %s, %s' % (nodes, error))
         return
     urls = []
     tree_iters = []
     for node in nodes:
         tree_iter = self.liststore_main.append([
             self.app.theme['anonymous'],
             Widgets.unescape(node['name']),
             int(node['nid']),
             Widgets.unescape(node['info']),
             Widgets.set_tooltip(node['name'], node['info']),
             ])
         urls.append(node['pic'])
         tree_iters.append(tree_iter)
     self.liststore_main.timestamp = time.time()
     Net.async_call(Net.update_liststore_images, self.liststore_main, 0,
                    tree_iters, urls)
Ejemplo n.º 7
0
    def set_lrc(self, lrc_txt):
        self.update_background(self.lrc_default_background)
        self.old_line_num = 1
        self.old_line_iter = None
        self.old_timestamp = -5
        if not lrc_txt:
            self.lrc_buf.set_text(_('No lrc available'))
            self.lrc_obj = None
            return
        self.lrc_obj = lrc_parser(lrc_txt)
        if not self.lrc_obj:
            logger.warn('set_lrc(): failed to parse lrc.')
            self.lrc_buf.set_text(_('No lrc available'))
            return
        lrc_content = [l[1] for l in self.lrc_obj]

        self.lrc_buf.remove_all_tags(self.lrc_buf.get_start_iter(),
                                     self.lrc_buf.get_end_iter())
        self.lrc_buf.set_text('\n'.join(lrc_content))
        self.lrc_window.get_vadjustment().set_value(0)
Ejemplo n.º 8
0
    def set_lrc(self, lrc_txt):
        self.update_background(self.lrc_default_background)
        self.old_line_num = 1
        self.old_line_iter = None
        self.old_timestamp = -5
        if not lrc_txt:
            self.lrc_buf.set_text(_('No lyrics available'))
            self.lrc_obj = None
            self.app.osdlrc.set_lrc(self.lrc_obj)
            return
        self.lrc_obj = parse_lrc(lrc_txt)
        self.app.osdlrc.set_lrc(self.lrc_obj)
        if not self.lrc_obj:
            logger.warn('set_lrc(): failed to parse lrc.')
            self.lrc_buf.set_text(_('No lyrics available'))
            return
        lrc_content = [l[1] for l in self.lrc_obj]

        self.lrc_buf.remove_all_tags(self.lrc_buf.get_start_iter(),
                                     self.lrc_buf.get_end_iter())
        self.lrc_buf.set_text('\n'.join(lrc_content))
        self.lrc_window.get_vadjustment().set_value(0)
Ejemplo n.º 9
0
import traceback

from gi.repository import GdkPixbuf
from gi.repository import Gtk

from kuwo import Config
_ = Config._
from kuwo import Net
from kuwo import Widgets
from kuwo.log import logger

try:
    import html2text
    html2text_imported = True
except ImportError:
    logger.warn(traceback.format_exc())
    html2text_imported = False


class InfoLabel(Gtk.Label):
    def __init__(self, grid, pref, left, top):
        super().__init__()
        self.props.xalign = 0
        self.props.use_markup = True
        grid.attach(self, left, top, 1, 1)
        self.pref = pref

    def set(self, info, key):
        if info and key in info:
            self.set_label('<b>{0} :</b> {1}'.format(self.pref, info[key]))
        else:
Ejemplo n.º 10
0
    def _download_song(self, song, use_mv):
        cached, song_link, song_path = get_song_link(song, self.app.conf,
                                                     use_mv=use_mv)
        # temp file to store data
        tmp_song_path = '{0}-{1}.part'.format(song_path, int(time.time()))

        # check song already cached 
        if cached:
            self.emit('can-play', song_path)
            self.emit('downloaded', song_path)
            return

        # this song has no link to download
        if not song_link:
            logger.debug('download_song(): %s.' % song)
            self.emit('network-error', song_link)
            return

        if use_mv:
            chunk_to_play = CHUNK_MV_TO_PLAY
        else:
            chunk_to_play = CHUNK_TO_PLAY

        for retried in range(RETRIES):
            try:
                req = request.urlopen(song_link, timeout=TIMEOUT)
                received_size = 0
                can_play_emited = False
                content_length = int(req.headers.get('Content-Length'))
                fh = open(tmp_song_path, 'wb')

                while True:
                    if self.force_quit:
                        if not fh.closed:
                            fh.close()
                        if os.path.exists(song_path):
                            os.remove(song_path)
                        return
                    chunk = req.read(CHUNK)
                    received_size += len(chunk)
                    percent = received_size / content_length
                    if int(percent * 100) % 5 == 0:
                        self.emit('chunk-received', percent)
                    # this signal only emit once.
                    if ((received_size > chunk_to_play or percent > 0.4) and
                            not can_play_emited):
                        self.emit('can-play', tmp_song_path)
                        can_play_emited = True
                    if not chunk:
                        break
                    fh.write(chunk)

                fh.close()
                # download successfully
                if received_size == content_length:
                    os.rename(tmp_song_path, song_path)
                    self.emit('downloaded', song_path)
                    Utils.iconvtag(song_path, song)
                    return
                else:
                    logger.warn('Net.received_size: %s, content_length: %s' %
                                (received_size, content_length))
                    self.emit('network-error', song_link)
                # remove temp file
                if os.path.exists(tmp_song_path):
                    os.remove(tmp_song_path)
                break

            except URLError:
                logger.error(traceback.format_exc())
            except FileNotFoundError:
                logger.error(traceback.format_exc())
                self.emit('disk-error', song_path)
                if os.path.exists(tmp_song_path):
                    os.remove(tmp_song_path)
                return

        if os.path.exists(tmp_song_path):
            os.remove(tmp_song_path)
        self.emit('network-error', song_link)
Ejemplo n.º 11
0
 def on_playbin_error(self, playbin, error_msg):
     logger.warn('Player.on_playbin_error(): %s.' % error_msg)
     self.app.toast('Player Error: %s' % error_msg)
     self.stop_player()
Ejemplo n.º 12
0
 def on_playbin_error(self, playbin, error_msg):
     logger.warn('Player.on_playbin_error(): %s.' % error_msg)
     self.load_next()
Ejemplo n.º 13
0
 def _on_list_received(imgs, error=None):
     if error or not imgs or len(imgs) < 10:
         logger.warn('get_recommend_lists(): %s, %s' % (imgs, error))
         self.recommend_imgs = None
     else:
         self.recommend_imgs = imgs.splitlines()
Ejemplo n.º 14
0
# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html

import traceback

from gi.repository import GLib

from kuwo.log import logger
from kuwo import Config
ShortcutMode = Config.ShortcutMode

try:
    from keybinder.keybinder_gtk import KeybinderGtk
    keybinder_imported = True
except ImportError:
    logger.warn(traceback.format_exc())
    keybinder_imported = False
    logger.warn('No python3-keybinder module found.')


class Shortcut:
    def __init__(self, player):
        self.player = player

        self.callbacks = {
            'VolumeUp': self.volume_up,
            'VolumeDown': self.volume_down,
            'Mute': lambda *args: player.toggle_mute_cb(),
            'Previous': lambda *args: player.load_prev_cb(),
            'Next': lambda *args: player.load_next_cb(),
            'Pause': lambda *args: player.play_pause_cb(),
Ejemplo n.º 15
0
 def t_error(token):
     logger.warn('LrcParser.parser_lex.t_error: %s', token.value)
Ejemplo n.º 16
0
 def _on_list_received(imgs, error=None):
     if error or not imgs or len(imgs) < 10:
         logger.warn('get_recommend_lists(): %s, %s' % (imgs, error))
         self.recommend_imgs = None
     else:
         self.recommend_imgs = imgs.splitlines()
Ejemplo n.º 17
0
import traceback

from gi.repository import GdkPixbuf
from gi.repository import Gtk

from kuwo import Config
_ = Config._
from kuwo import Net
from kuwo import Widgets
from kuwo.log import logger

try:
    import html2text
    html2text_imported = True
except ImportError:
    logger.warn(traceback.format_exc())
    html2text_imported = False


class InfoLabel(Gtk.Label):
    def __init__(self, grid, pref, left, top):
        super().__init__()
        self.props.xalign = 0
        self.props.use_markup = True
        grid.attach(self, left, top, 1, 1)
        self.pref = pref

    def set(self, info, key):
        if info and key in info:
            self.set_label('<b>{0} :</b> {1}'.format(self.pref, info[key]))
        else:
Ejemplo n.º 18
0
 def get_mute(self):
     try:
         return self.playbin.get_property('mute')
     except TypeError:
         logger.warn(traceback.format_exc())
         return False
Ejemplo n.º 19
0
# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html

import traceback

from gi.repository import GLib

from kuwo.log import logger
from kuwo import Config
ShortcutMode = Config.ShortcutMode

try:
    from keybinder.keybinder_gtk import KeybinderGtk
    keybinder_imported = True
except ImportError:
    logger.warn(traceback.format_exc())
    keybinder_imported = False
    logger.warn('No python3-keybinder module found.')


class Shortcut:
    def __init__(self, player):
        self.player = player

        self.callbacks = {
            'VolumeUp': self.volume_up,
            'VolumeDown': self.volume_down,
            'Mute': lambda *args: player.toggle_mute_cb(),
            'Previous': lambda *args: player.load_prev_cb(),
            'Next': lambda *args: player.load_next_cb(),
            'Pause': lambda *args: player.play_pause_cb(),
Ejemplo n.º 20
0
import traceback

from gi.repository import GdkPixbuf
from gi.repository import Gtk

from kuwo import Config
_ = Config._
from kuwo import Net
from kuwo import Widgets
from kuwo.log import logger

try:
    import html2text
    html2text_imported = True
except ImportError:
    logger.warn(traceback.exec())
    html2text_imported = False


class InfoLabel(Gtk.Label):
    def __init__(self, grid, pref, left, top):
        super().__init__()
        self.props.xalign = 0
        self.props.use_markup = True
        grid.attach(self, left, top, 1, 1)
        self.pref = pref

    def set(self, info, key):
        if info and key in info:
            self.set_label('<b>{0} :</b> {1}'.format(self.pref, info[key]))
        else:
Ejemplo n.º 21
0
 def on_network_error():
     logger.warn('Playlist.on_network_error: %s, %s' %
                 (song_link, error))
     self.stop_caching_daemon()
     Widgets.network_error(self.app.window,
                           _('Failed to cache song'))
Ejemplo n.º 22
0
from urllib import parse
import subprocess
import traceback
import zlib

from kuwo.log import logger

mutagenx_imported = False
if sys.version_info.major >= 3 and sys.version_info.minor >= 3:
    try:
        from mutagen.mp3 import MP3
        from mutagen.easyid3 import EasyID3
        from mutagen.apev2 import APEv2File
        mutagenx_imported = True
    except ImportError:
        logger.warn('module `mutagen` was not found!')
else:
    logger.warn('Python3 < 3.3, `mutagen` is not supported')


def decode_lrc_content(lrc, is_lrcx=False):
    '''lrc currently is bytes. '''
    if lrc[:10] != b'tp=content':
        return None
    index = lrc.index(b'\r\n\r\n')
    lrc_bytes = lrc[index+4:]
    str_lrc = zlib.decompress(lrc_bytes)
    if not is_lrcx:
        return str_lrc.decode('gb18030')
    str_bytes = base64.decodebytes(str_lrc)
    return xor_bytes(str_bytes).decode('gb18030')
Ejemplo n.º 23
0
 def get_mute(self):
     try:
         return self.playbin.get_property('mute')
     except TypeError:
         logger.warn(traceback.format_exc())
         return False
Ejemplo n.º 24
0
 def on_disk_error():
     logger.warn('Playlist.on_disk_error: %s, %s' %
                 (song_path, error))
     self.stop_caching_daemon()
     Widgets.filesystem_error(self.app.window, song_path)
Ejemplo n.º 25
0
 def t_error(token):
     logger.warn('LrcParser.parser_lex.t_error: %s', token.value)
Ejemplo n.º 26
0
    def _download_song(self, song, use_mv):
        cached, song_link, song_path = get_song_link(song,
                                                     self.app.conf,
                                                     use_mv=use_mv)
        # temp file to store data
        tmp_song_path = '{0}-{1}.part'.format(song_path, int(time.time()))

        # check song already cached
        if cached:
            self.emit('can-play', song_path)
            self.emit('downloaded', song_path)
            return

        # this song has no link to download
        if not song_link:
            logger.debug('download_song(): %s.' % song)
            self.emit('network-error', song_link)
            return

        if use_mv:
            chunk_to_play = CHUNK_MV_TO_PLAY
        else:
            chunk_to_play = CHUNK_TO_PLAY

        for retried in range(RETRIES):
            try:
                req = request.urlopen(song_link, timeout=TIMEOUT)
                received_size = 0
                can_play_emited = False
                content_length = int(req.headers.get('Content-Length'))
                fh = open(tmp_song_path, 'wb')

                while True:
                    if self.force_quit:
                        if not fh.closed:
                            fh.close()
                        if os.path.exists(song_path):
                            os.remove(song_path)
                        return
                    chunk = req.read(CHUNK)
                    received_size += len(chunk)
                    percent = received_size / content_length
                    if int(percent * 100) % 5 == 0:
                        self.emit('chunk-received', percent)
                    # this signal only emit once.
                    if ((received_size > chunk_to_play or percent > 0.4)
                            and not can_play_emited):
                        self.emit('can-play', tmp_song_path)
                        can_play_emited = True
                    if not chunk:
                        break
                    fh.write(chunk)

                fh.close()
                # download successfully
                if received_size == content_length:
                    os.rename(tmp_song_path, song_path)
                    self.emit('downloaded', song_path)
                    Utils.iconvtag(song_path, song)
                    return
                else:
                    logger.warn('Net.received_size: %s, content_length: %s' %
                                (received_size, content_length))
                    self.emit('network-error', song_link)
                # remove temp file
                if os.path.exists(tmp_song_path):
                    os.remove(tmp_song_path)
                break

            except URLError:
                logger.error(traceback.format_exc())
            except FileNotFoundError:
                logger.error(traceback.format_exc())
                self.emit('disk-error', song_path)
                if os.path.exists(tmp_song_path):
                    os.remove(tmp_song_path)
                return

        if os.path.exists(tmp_song_path):
            os.remove(tmp_song_path)
        self.emit('network-error', song_link)
Ejemplo n.º 27
0
 def on_playbin_error(self, playbin, error_msg):
     logger.warn('Player.on_playbin_error(): %s.' % error_msg)
     self.app.toast('Player Error: %s' % error_msg)
     self.stop_player()
Ejemplo n.º 28
0
 def on_network_error():
     logger.warn('Playlist.on_network_error: %s, %s' %
                 (song_link, error))
     self.stop_caching_daemon()
     Widgets.network_error(self.app.window,
                           _('Failed to cache song'))
Ejemplo n.º 29
0
 def on_disk_error():
     logger.warn('Playlist.on_disk_error: %s, %s' %
                 (song_path, error))
     self.stop_caching_daemon()
     Widgets.filesystem_error(self.app.window, song_path)