code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
'''
Created on Mar 14, 2010
@author: ivan
'''
from foobnix.window.window_controller import WindowController
from foobnix.player.player_controller import PlayerController
from foobnix.playlist.playlist_controller import PlaylistCntr
from foobnix.player.player_widgets_cntr import PlayerWidgetsCntl
from foobnix.directory.directory_controller import DirectoryCntr
from foobnix.tryicon.tryicon_controller import TrayIcon
from foobnix.application.app_load_exit_controller import OnLoadExitAppCntr
from foobnix.application.app_configuration_controller import AppConfigurationCntrl
from foobnix.preferences.pref_controller import PrefController
from foobnix.radio.radio_controller import RadioListCntr
from foobnix.online.online_controller import OnlineListCntr
from foobnix.directory.virtuallist_controller import VirturalLIstCntr
class AppController():
def __init__(self, v):
playerCntr = PlayerController()
playlistCntr = PlaylistCntr(v.playlist, playerCntr)
virtualListCntr = VirturalLIstCntr()
radioListCntr = RadioListCntr(v.gxMain, playerCntr)
playerWidgets = PlayerWidgetsCntl(v.gxMain, playerCntr)
playerCntr.registerWidgets(playerWidgets)
playerCntr.registerPlaylistCntr(playlistCntr)
directoryCntr = DirectoryCntr(v.gxMain, playlistCntr, radioListCntr, virtualListCntr)
playlistCntr.registerDirectoryCntr(directoryCntr)
appConfCntr = AppConfigurationCntrl(v.gxMain, directoryCntr)
onlineCntr = OnlineListCntr(v.gxMain, playerCntr, directoryCntr, playerWidgets)
playerCntr.registerOnlineCntr(onlineCntr)
prefCntr = PrefController(v.gxPref)
windowController = WindowController(v.gxMain,v.gxAbout, prefCntr)
playerCntr.registerWindowController(windowController)
trayIcon = TrayIcon(v.gxTryIcon, windowController, playerCntr,playerWidgets)
playerCntr.registerTrayIcon(trayIcon)
loadExit = OnLoadExitAppCntr(playlistCntr, playerWidgets, playerCntr, directoryCntr, appConfCntr, radioListCntr, virtualListCntr)
windowController.registerOnExitCnrt(loadExit)
pass #end of class
| Python |
'''
Created on Mar 14, 2010
@author: ivan
'''
import gtk.glade
import gettext
class AppView():
gladeMain = "foobnix/glade/foobnix.glade"
gladePref = "foobnix/glade/preferences.glade"
def __init__(self):
self.gxMain = self.glade_XML(self.gladeMain, "foobnixWindow")
self.gxTryIcon = self.glade_XML(self.gladeMain, "popUpWindow")
self.gxPref = self.glade_XML(self.gladePref, "window")
self.gxAbout = self.glade_XML(self.gladeMain, "aboutdialog")
self.playlist = self.gxMain.get_widget("playlist_treeview")
def glade_XML(self, main, widget):
domain = "foobnix"
try:
return gtk.glade.XML(main, widget,domain)
except:
try:
return gtk.glade.XML("/usr/local/lib/python2.6/dist-packages/" + main, widget,domain)
except:
return gtk.glade.XML("/usr/lib/python2.5/site-packages/" + main, widget, domain)
| Python |
'''
Created on Mar 14, 2010
@author: ivan
'''
from foobnix.util.confguration import FConfiguration
class AppConfigurationCntrl():
def __init__(self, gxMain, directoryCntr):
self.directoryCntr = directoryCntr
self.folderChoser = gxMain.get_widget("music_dir_filechooserbutton")
self.folderChoser.connect("current-folder-changed", self.onChangeMusicFolder)
self.vk_entry_label = gxMain.get_widget("vk_entry_login")
self.vk_entry_passw = gxMain.get_widget("vk_entry_password")
self.lfm_entry_label = gxMain.get_widget("lfm_entry_login")
self.lfm_entry_passw = gxMain.get_widget("lfm_entry_password")
""" online music folder path """
self.online_dir = gxMain.get_widget("online_dir_filechooserbutton")
self.online_dir.connect("current-folder-changed", self.onChangeOnline)
self.online_dir.set_current_folder(FConfiguration().onlineMusicPath)
self.online_dir.set_sensitive(FConfiguration().is_save_online)
""" is save online music checkbox """
self.save_online = gxMain.get_widget("save_online_checkbutton")
self.save_online.connect("clicked", self.on_save_online)
self.save_online.set_active(FConfiguration().is_save_online)
self.by_first = gxMain.get_widget("radiobutton_by_first")
self.by_popularity = gxMain.get_widget("radiobutton_by_popularity")
self.by_time = gxMain.get_widget("radiobutton_by_time")
"""Random button"""
self.randomCheckButton = gxMain.get_widget("random_checkbutton")
self.randomCheckButton.set_active(FConfiguration().isRandom)
self.randomCheckButton.connect("clicked", self.onRandomClicked)
"""Repeat button"""
self.repeatCheckButton = gxMain.get_widget("repeat_checkbutton")
self.repeatCheckButton.set_active(FConfiguration().isRepeat)
self.repeatCheckButton.connect("clicked", self.onRepeatClicked)
"""Play on Start"""
self.playOnStartCheckButton = gxMain.get_widget("playonstart_checkbutton")
self.playOnStartCheckButton.set_active(FConfiguration().isPlayOnStart)
self.playOnStartCheckButton.connect("clicked", self.onPlayOnStartClicked)
def onPlayOnStartClicked(self, *args):
FConfiguration().isPlayOnStart = self.playOnStartCheckButton.get_active()
def onRepeatClicked(self, *args):
FConfiguration().isRepeat = self.repeatCheckButton.get_active()
def onRandomClicked(self, *args):
FConfiguration().isRandom = self.randomCheckButton.get_active()
def on_save_online(self, *args):
value = self.save_online.get_active()
if value:
self.online_dir.set_sensitive(True)
else:
self.online_dir.set_sensitive(False)
FConfiguration().is_save_online = value
def onChangeOnline(self, *args):
path = self.online_dir.get_filename()
print "Change music online folder", path
FConfiguration().onlineMusicPath = path
""" Vkontatke"""
def setVkLoginPass(self, login, passwrod):
self.vk_entry_label.set_text(login)
self.vk_entry_passw.set_text(passwrod)
def getVkLogin(self): return self.vk_entry_label.get_text()
def getVkPassword(self): return self.vk_entry_passw.get_text()
""" Last.FM"""
def setLfmLoginPass(self, value, passwrod):
self.lfm_entry_label.set_text(value)
self.lfm_entry_passw.set_text(passwrod)
def getLfmLogin(self): return self.lfm_entry_label.get_text()
def getLfmPassword(self): return self.lfm_entry_passw.get_text()
def onChangeMusicFolder(self, path):
self.musicFolder = self.folderChoser.get_filename()
print "Change music folder", self.musicFolder
self.directoryCntr.updateDirectoryByPath(self.musicFolder)
def setMusicFolder(self, path):
print "Set Folder", path
self.folderChoser.set_current_folder(path)
def getMusicFolder(self):
return self.folderChoser.get_filename()
| Python |
'''
Created on Mar 14, 2010
@author: ivan
'''
from foobnix.util.confguration import FConfiguration
class OnLoadExitAppCntr():
def __init__(self, playlistCntr, playerWidgets, playerCntr, directoryCntr, appConfCntr, radioListCntr, virtualListCntr):
self.directoryCntr = directoryCntr
self.playlistCntr = playlistCntr
self.playerWidgets = playerWidgets
self.playerCntr = playerCntr
self.appConfCntr = appConfCntr
self.radioListCntr = radioListCntr
self.virtualListCntr = virtualListCntr
self.onStart()
def onStart(self):
print "Init configs"
print FConfiguration().playlistState
if FConfiguration().playlistState:
self.playlistCntr.setState(FConfiguration().playlistState)
if FConfiguration().virtualListState:
self.directoryCntr.setState(FConfiguration().virtualListState)
if FConfiguration().volumeValue:
self.playerWidgets.volume.set_value(FConfiguration().volumeValue)
self.playerCntr.setVolume(FConfiguration().volumeValue / 100)
if FConfiguration().hpanelPostition:
self.playerWidgets.hpanel.set_position(FConfiguration().hpanelPostition)
if FConfiguration().vpanelPostition:
self.playerWidgets.vpanel.set_position(FConfiguration().vpanelPostition)
if FConfiguration().mediaLibraryPath:
self.appConfCntr.setMusicFolder(FConfiguration().mediaLibraryPath)
if FConfiguration().radiolistState:
self.radioListCntr.setState(FConfiguration().radiolistState)
self.appConfCntr.setVkLoginPass(FConfiguration().vk_login, FConfiguration().vk_password)
self.appConfCntr.setLfmLoginPass(FConfiguration().lfm_login, FConfiguration().lfm_password)
if FConfiguration().isPlayOnStart:
self.playerCntr.next()
def onExit(self):
print "Save configs"
FConfiguration().playlistState = self.playlistCntr.getState()
FConfiguration().virtualListState = self.directoryCntr.getState()
FConfiguration().radiolistState = self.radioListCntr.getState()
FConfiguration().volumeValue = self.playerWidgets.volume.get_value()
FConfiguration().vpanelPostition = self.playerWidgets.vpanel.get_position()
FConfiguration().hpanelPostition = self.playerWidgets.hpanel.get_position()
FConfiguration().mediaLibraryPath = self.appConfCntr.getMusicFolder()
FConfiguration().vk_login = self.appConfCntr.getVkLogin()
FConfiguration().vk_password = self.appConfCntr.getVkPassword()
FConfiguration().lfm_login = self.appConfCntr.getLfmLogin()
FConfiguration().lfm_password = self.appConfCntr.getLfmPassword()
FConfiguration().save()
| Python |
'''
Created on Mar 13, 2010
@author: ivan
'''
import gtk
import os.path
class TrayIcon:
def __init__(self, gxTryIcon, windowController, playerController, playerWidgets):
self.windowController = windowController
self.playerController = playerController
self.playerWidgets = playerWidgets
self.icon = gtk.StatusIcon()
self.icon.set_tooltip("Foobnix music playerEngine")
iconPath = "/usr/local/share/pixmaps/foobnix.png"
if os.path.exists(iconPath):
self.icon.set_from_file(iconPath)
else:
self.icon.set_from_stock("gtk-media-play")
self.connect()
self.popup = gxTryIcon.get_widget("popUpWindow")
self.text1 = gxTryIcon.get_widget("text1")
self.text2 = gxTryIcon.get_widget("text2")
signalsPopup = {
"on_close_clicked" :self.quitApp,
"on_play_clicked" :self.onPlayButton,
"on_pause_clicked" :self.onPauseButton,
"on_next_clicked" :self.onPlayNextButton,
"on_prev_clicked" :self.onPlayPrevButton,
"on_cancel_clicked": self.closePopUP
}
gxTryIcon.signal_autoconnect(signalsPopup)
self.isVisible = True
def connect(self):
self.icon.connect("activate", self.onLeftMouseClick)
self.icon.connect("popup-menu", self.onRightMouseClick)
try:
self.icon.connect("scroll-event", self.onScrollUpDown)
except:
pass
def setText1(self, text):
self.text1.set_text(text)
def setText2(self, text):
self.text2.set_text(text)
def quitApp(self, *a):
self.windowController.onDestroy()
def onPlayButton(self, *a):
self.playerController.playState()
def onPauseButton(self, *a):
self.playerController.pauseState()
def onPlayNextButton(self, *a):
self.playerController.next()
def onPlayPrevButton(self, *a):
self.playerController.prev()
def closePopUP(self, *a):
self.popup.hide()
def onLeftMouseClick(self, *a):
if self.isVisible:
self.windowController.hide()
else:
self.windowController.show()
self.isVisible = not self.isVisible
def onRightMouseClick(self, *args):
self.popup.show()
def onScrollUpDown(self, w, event):
volume = self.playerController.getVolume()
if event.direction == gtk.gdk.SCROLL_UP: #@UndefinedVariable
print "Volume UP"
self.playerController.setVolume(volume + 0.05)
else:
print "Volume Down"
self.playerController.setVolume(volume - 0.05)
self.playerWidgets.volume.set_value(volume * 100)
| Python |
'''
Created on Mar 13, 2010
@author: ivan
'''
import gtk
from foobnix.util.confguration import VERSION
class WindowController():
def __init__(self, gxMain, gxAbout, prefCntr):
self.decorate(gxMain)
self.prefCntr = prefCntr
self.window = gxMain.get_widget("foobnixWindow")
self.window.maximize()
#self.window.connect("destroy", self.onDestroy)
self.window.connect("delete-event", self.hide)
self.window.set_title("Foobnix "+VERSION)
signalsPopup = {
"on_gtk-preferences_activate" :self.showPref,
"on_file_quit_activate":self.onDestroy,
"on_menu_about_activate":self.showAbout
}
gxMain.signal_autoconnect(signalsPopup)
self.about = gxAbout.get_widget("aboutdialog")
self.about.connect("delete-event", self.hideAbout)
def showAbout(self, *args):
self.about.show()
def hideAbout(self, *args):
self.about.hide()
return True
def showPref(self, *args):
self.prefCntr.show()
def setTitle(self, text):
self.window.set_title(text)
def registerOnExitCnrt(self, onExitCnrt):
self.onExitCnrt = onExitCnrt
def show(self):
self.window.show()
def hide(self, *args):
self.window.hide()
return True
def onDestroy(self, *a):
print "Destroy"
self.onExitCnrt.onExit()
gtk.main_quit()
def decorate(self, gx):
rc_st = '''
style "menubar-style" {
GtkMenuBar::shadow_type = none
GtkMenuBar::internal-padding = 0
}
class "GtkMenuBar" style "menubar-style"
'''
gtk.rc_parse_string(rc_st)
menuBar = gx.get_widget("menubar3")
labelColor = gx.get_widget("label31")
bgColor = labelColor.get_style().bg[gtk.STATE_NORMAL]
txtColor = labelColor.get_style().fg[gtk.STATE_NORMAL]
menuBar.modify_bg(gtk.STATE_NORMAL, bgColor)
items = menuBar.get_children()
#Set god style for main menu
for item in items:
current = item.get_children()[0]
current.modify_fg(gtk.STATE_NORMAL, txtColor)
| Python |
#!/usr/bin/env python
import os, glob, shutil
from distutils.core import setup, Extension
from foobnix.util.confguration import VERSION
def capture(cmd):
return os.popen(cmd).read().strip()
def removeall(path):
if not os.path.isdir(path):
return
files = os.listdir(path)
for x in files:
fullpath = os.path.join(path, x)
if os.path.isfile(fullpath):
f = os.remove
rmgeneric(fullpath, f)
elif os.path.isdir(fullpath):
removeall(fullpath)
f = os.rmdir
rmgeneric(fullpath, f)
def rmgeneric(path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
pass
# Create mo files:
if not os.path.exists("mo/"):
os.mkdir("mo/")
for lang in ('ru', 'uk'):
pofile = "po/" + lang + ".po"
mofile = "mo/" + lang + "/foobnix.mo"
if not os.path.exists("mo/" + lang + "/"):
os.mkdir("mo/" + lang + "/")
print "generating", mofile
os.system("msgfmt %s -o %s" % (pofile, mofile))
# Copy script "foobnix" file to foobnix dir:
shutil.copyfile("foobnix.py", "foobnix/foobnix")
versionfile = file("foobnix/version.py", "wt")
versionfile.write("""
# generated by setup.py
VERSION = %r
""" % VERSION)
versionfile.close()
setup(name='foobnix',
version=VERSION,
description='GTK+ client for the Music Player Daemon (MPD).',
author='Ivan Ivanenko',
author_email='ivan.ivanenko@gmail.com',
url='www.foobnix.com',
classifiers=[
'Development Status :: Beta',
'Environment :: X11 Applications',
'Intended Audience :: End Users/Desktop',
'License :: GNU General Public License (GPL)',
'Operating System :: Linux',
'Programming Language :: Python',
'Topic :: Multimedia :: Sound :: Players',
],
packages=[
"foobnix",
"foobnix.application",
"foobnix.directory",
"foobnix.glade",
"foobnix.lyric",
"foobnix.model",
"foobnix.online",
"foobnix.online.google",
"foobnix.player",
"foobnix.playlist",
"foobnix.preferences",
"foobnix.radio",
"foobnix.tryicon",
"foobnix.util",
"foobnix.window",
],
package_data={'foobnix': ['glade/*.glade', 'glade/*.png']},
#package_dir={"src/foobnix": "foobnix/"},
scripts=['foobnix/foobnix'],
data_files=[('share/foobnix', ['README', 'CHANGELOG', 'TODO', 'TRANSLATORS']),
('share/applications', ['foobnix.desktop']),
('share/pixmaps', glob.glob('foobnix/pixmaps/*')),
('share/man/man1', ['foobnix.1']),
('/usr/share/locale/uk/LC_MESSAGES', ['mo/uk/foobnix.mo']),
('/usr/share/locale/ru/LC_MESSAGES', ['mo/ru/foobnix.mo'])
]
)
# Cleanup (remove /build, /mo, and *.pyc files:
print "Cleaning up..."
try:
removeall("build/")
os.rmdir("build/")
pass
except:
pass
try:
removeall("mo/")
os.rmdir("mo/")
except:
pass
try:
for f in os.listdir("."):
if os.path.isfile(f):
if os.path.splitext(os.path.basename(f))[1] == ".pyc":
os.remove(f)
except:
pass
try:
os.remove("foobnix/foobnix")
except:
pass
try:
os.remove("foobnix/version.py")
except:
pass
try:
os.remove(os.getenv("HOME") + "/foobnix_conf.pkl")
except:
pass
| Python |
#!/usr/bin/env python
'''
Created on Mar 10, 2010
@author: ivan
'''
import os
import gtk
import gettext
from foobnix.application.app_view import AppView
from foobnix.application.app_controller import AppController
class App():
def __init__(self):
v = AppView()
AppController(v)
if __name__ == "__main__":
APP_NAME = "foobnix"
gettext.install(APP_NAME, unicode=True)
gettext.textdomain(APP_NAME)
gtk.glade.textdomain(APP_NAME)
app = App()
gtk.gdk.threads_init() #@UndefinedVariable
gtk.main()
print _("Success")
| Python |
# -*- coding: utf-8 -*-
# lyricwiki.py
#
# Copyright 2009 Amr Hassan <amr.hassan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import simplejson, urllib, os, hashlib, time
def _download(args):
"""
Downloads the json response and returns it
"""
base = "http://lyrics.wikia.com/api.php?"
str_args = {}
for key in args:
str_args[key] = args[key].encode("utf-8")
args = urllib.urlencode(str_args)
return urllib.urlopen(base + args).read()
def _get_page_titles(artist, title):
"""
Returns a list of available page titles
"""
args = {"action": "query",
"list": "search",
"srsearch": artist + " " + title,
"format": "json",
}
titles = ["%s:%s" % (artist, title), "%s:%s" % (artist.title(), title.title())]
content = simplejson.loads(_download(args))
for t in content["query"]["search"]:
titles.append(t["title"])
return titles
def _get_lyrics(artist, title):
for page_title in _get_page_titles(artist, title):
args = {"action": "query",
"prop": "revisions",
"rvprop": "content",
"titles": page_title,
"format": "json",
}
revisions = simplejson.loads(_download(args))["query"]["pages"].popitem()[1]
if not "revisions" in revisions:
continue
content = revisions["revisions"][0]["*"]
if content.startswith("#Redirect"):
n_title = content[content.find("[[") + 2:content.rfind("]]")]
return _get_lyrics(*n_title.split(":"))
if "<lyrics>" in content:
return content[content.find("<lyrics>") + len("<lyrics>") : content.find("</lyrics>")].strip()
elif "<lyric>" in content:
return content[content.find("<lyric>") + len("<lyric>") : content.find("</lyric>")].strip()
def get_lyrics(artist, title, cache_dir=None):
"""
Get lyrics by artist and title
set cache_dir to a valid (existing) directory
to enable caching.
"""
path = None
if cache_dir and os.path.exists(cache_dir):
digest = hashlib.sha1(artist.lower().encode("utf-8") + title.lower().encode("utf-8")).hexdigest()
path = os.path.join(cache_dir, digest)
if os.path.exists(path):
fp = open(path)
return simplejson.load(fp)["lyrics"].strip()
lyrics = _get_lyrics(artist, title)
if path and lyrics:
fp = open(path, "w")
simplejson.dump({"time": time.time(), "artist": artist, "title": title,
"source": "lyricwiki", "lyrics": lyrics }, fp, indent=4)
fp.close()
return lyrics
| Python |
'''
Created on Mar 21, 2010
@author: ivan
'''
import time
import thread
class DemoThread:
def __init__(self):
self.result = 0
self.playerThreadId = thread.start_new_thread(self.calc, (10,))
print "RESULT", self.result
time.sleep(3)
print "RESULT", self.result
def calc(self,num):
print num
for i in xrange(num):
self.result += i
time.sleep(0.1)
demo = DemoThread()
| Python |
#!/usr/bin/env python
import sys, os, glob, shutil
from distutils.core import setup
from foobnix.util.configuration import VERSION, FOOBNIX_TMP, FOOBNIX_TMP_RADIO
root_dir = ''
for a in sys.argv[1:]:
if a.find('--root') == 0:
root_dir = a[7:]
print "RADIO", FOOBNIX_TMP, FOOBNIX_TMP_RADIO
if not os.path.exists(os.path.dirname(root_dir) + FOOBNIX_TMP):
os.mkdir(os.path.dirname(root_dir) + FOOBNIX_TMP)
if not os.path.exists(os.path.dirname(root_dir) + FOOBNIX_TMP_RADIO):
os.mkdir(os.path.dirname(root_dir) + FOOBNIX_TMP_RADIO)
def capture(cmd):
return os.popen(cmd).read().strip()
def removeall(path):
if not os.path.isdir(path):
return
files = os.listdir(path)
for x in files:
fullpath = os.path.join(path, x)
if os.path.isfile(fullpath):
f = os.remove
rmgeneric(fullpath, f)
elif os.path.isdir(fullpath):
removeall(fullpath)
f = os.rmdir
rmgeneric(fullpath, f)
def rmgeneric(path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
pass
# Create mo files:
if not os.path.exists("mo/"):
os.mkdir("mo/")
for lang in ('ru', 'uk', 'he'):
pofile = "po/" + lang + ".po"
mofile = "mo/" + lang + "/foobnix.mo"
if not os.path.exists("mo/" + lang + "/"):
os.mkdir("mo/" + lang + "/")
print "generating", mofile
os.system("msgfmt %s -o %s" % (pofile, mofile))
# Copy script "foobnix" file to foobnix dir:
shutil.copyfile("foobnix.py", "foobnix/foobnix")
versionfile = file("foobnix/version.py", "wt")
versionfile.write("""
# generated by setup.py
VERSION = %r
""" % VERSION)
versionfile.close()
setup(name='foobnix',
version=VERSION,
description='GTK+ client for the Music Player Daemon (MPD).',
author='Ivan Ivanenko',
author_email='ivan.ivanenko@gmail.com',
url='www.foobnix.com',
classifiers=[
'Development Status :: Beta',
'Environment :: X11 Applications',
'Intended Audience :: End Users/Desktop',
'License :: GNU General Public License (GPL)',
'Operating System :: Linux',
'Programming Language :: Python',
'Topic :: Multimedia :: Sound :: Players',
],
packages=[
"foobnix",
"foobnix.application",
"foobnix.base",
"foobnix.cue",
"foobnix.directory",
"foobnix.eq",
"foobnix.glade",
"foobnix.helpers",
"foobnix.lyric",
"foobnix.model",
"foobnix.online",
"foobnix.online.google",
"foobnix.online.integration",
"foobnix.player",
"foobnix.playlist",
"foobnix.preferences",
"foobnix.preferences.configs",
"foobnix.radio",
"foobnix.regui",
"foobnix.regui.model",
"foobnix.thirdparty",
"foobnix.trayicon",
"foobnix.util",
"foobnix.window"
],
package_data={'foobnix': ['glade/*.glade', 'glade/*.png']},
#package_dir={"src/foobnix": "foobnix/"},
scripts=['foobnix/foobnix'],
data_files=[('share/foobnix', ['README']),
(FOOBNIX_TMP, ['version']),
('/usr/share/applications', ['foobnix.desktop']),
('/usr/share/pixmaps', glob.glob('foobnix/pixmaps/*')),
(FOOBNIX_TMP_RADIO, glob.glob('radio/*')),
('share/man/man1', ['foobnix.1']),
('/usr/share/locale/uk/LC_MESSAGES', ['mo/uk/foobnix.mo']),
('/usr/share/locale/he/LC_MESSAGES', ['mo/he/foobnix.mo']),
('/usr/share/locale/ru/LC_MESSAGES', ['mo/ru/foobnix.mo'])
]
)
# Cleanup (remove /build, /mo, and *.pyc files:
print "Cleaning up..."
try:
removeall("build/")
os.rmdir("build/")
pass
except:
pass
try:
removeall("mo/")
os.rmdir("mo/")
except:
pass
try:
for f in os.listdir("."):
if os.path.isfile(f):
if os.path.splitext(os.path.basename(f))[1] == ".pyc":
os.remove(f)
except:
pass
try:
os.remove("foobnix/foobnix")
except:
pass
try:
os.remove("foobnix/version.py")
except:
pass
| Python |
#!/usr/bin/env python
'''
Created on Mar 10, 2010
@author: ivan
'''
import gobject
import gtk
from foobnix.util.dbus_utils import DBusManager, getFoobnixDBusInterface
import sys
import time
import os
import thread
class Foobnix():
def __init__(self):
from foobnix.application.app_view import AppView
from foobnix.application.app_controller import AppController
import foobnix.util.localization
self.dbus = DBusManager(self)
self.app = AppController(AppView())
def start(self):
gobject.threads_init()
gtk.gdk.threads_enter()
gtk.main()
def play_args(self, args):
arg_list = eval(args)
print "fobonix play",
for i in arg_list:
print i
self.app.play_arguments(arg_list)
init_time = time.time()
iface = getFoobnixDBusInterface()
if not iface:
print "start server"
foobnix = Foobnix()
print "******Foobnix run in", time.time() - init_time, " seconds******"
foobnix.start()
else:
print "start client"
if sys.argv:
iface.interactive_play_args(str(sys.argv))
| Python |
'''
Created on 7 2010
@author: ivan
'''
from __future__ import with_statement
from foobnix.model.entity import CommonBean
import os
from foobnix.util.time_utils import normilize_time
from foobnix.util import LOG, file_utils
import chardet
import re
from foobnix.util.image_util import get_image_by_path
'''
Created on 4
@author: ivan
'''
TITLE = "TITLE"
PERFORMER = "PERFORMER"
FILE = "FILE"
INDEX = "INDEX"
class CueTrack():
def __init__(self, title, performer, index, path):
self.title = title
self.performer = performer
self.index = index
self.duration = 0
self.path = path
def __str__(self):
return "Track: " + self.title + " " + self.performer + " " + self.index
def get_start_time_str(self):
return self.index[len("INDEX 01") + 1:]
def get_start_time_sec(self):
time = self.get_start_time_str()
times = re.findall("([0-9]{1,2}):", time)
if not times or len(times) < 2:
return 0
min = times[0]
sec = times[1]
starts = int(min) * 60 + int(sec)
return starts
class CueFile():
def __init__(self):
self.title = None
self.performer = None
self.file = ""
self.image = None
self.tracks = []
def append_track(self, track):
self.tracks.append(track)
def __str__(self):
if self.title:
LOG.info("Title", self.title)
if self.performer:
LOG.info("Performer", self.performer)
if self.file:
LOG.info("File", self.file)
return "CUEFILE: " + self.title + " " + self.performer + " " + self.file
class CueReader():
def __init__(self, cue_file):
self.cue_file = cue_file
self.is_valid = True
def get_line_value(self, str):
first = str.find('"') or str.find("'")
end = str.find('"', first + 1) or str.find("'", first + 1)
return str[first + 1:end]
def normalize(self, cue_file):
duration_tracks = []
tracks = cue_file.tracks
for i in xrange(len(tracks) - 1):
track = tracks[i]
next_track = tracks[i + 1]
duration = next_track.get_start_time_sec() - track. get_start_time_sec()
track.duration = duration
if not track.path:
track.path = cue_file.file
duration_tracks.append(track)
cue_file.tracks = duration_tracks
return cue_file
def get_common_beans(self):
beans = []
cue = self.parse()
for i, track in enumerate(cue.tracks):
bean = CommonBean(name=track.performer + " - " + track.title, path=track.path, type=CommonBean.TYPE_MUSIC_FILE)
bean.aritst = track.performer
bean.tracknumber = i + 1
bean.title = track.title
bean.text = bean.name
bean.start_sec = track.get_start_time_sec()
bean.duration_sec = track.duration
bean.time = normilize_time(track.duration)
bean.parent = cue.performer + " - " + cue.title
bean.image = cue.image
beans.append(bean)
return beans
def is_cue_valid(self):
self.parse()
LOG.info("CUE VALID", self.cue_file, self.is_valid)
return self.is_valid
"""detect file encoding"""
def code_detecter(self, filename):
with open(filename) as codefile:
data = codefile.read()
return chardet.detect(data)['encoding']
def parse(self):
file = open(self.cue_file, "r")
code = self.code_detecter(self.cue_file);
LOG.debug("File encoding is", code)
is_title = True
cue_file = CueFile()
title = ""
performer = ""
index = "00:00:00"
full_file = None
cue_file.image = get_image_by_path(self.cue_file)
self.files_count = 0
for line in file:
try:
line = unicode(line, code)
except:
LOG.error("File encoding is too strange", code)
pass
line = str(line).strip()
if not line:
continue
if line.startswith(TITLE):
title = self.get_line_value(line)
if is_title:
cue_file.title = title
if line.startswith(PERFORMER):
performer = self.get_line_value(line)
if is_title:
cue_file.performer = performer
if line.startswith(FILE):
self.files_count += 1
if self.files_count > 1:
self.is_valid = False
return cue_file
file = self.get_line_value(line)
dir = os.path.dirname(self.cue_file)
full_file = os.path.join(dir, file)
LOG.debug("CUE source", full_file)
exists = os.path.exists(full_file)
"""if there no source cue file"""
if not exists:
"""try to find other source"""
ext = file_utils.get_file_extenstion(full_file)
nor = full_file[:-len(ext)]
LOG.info("Normilized path", nor)
if os.path.exists(nor + ".ape"):
full_file = nor + ".ape"
elif os.path.exists(nor + ".flac"):
full_file = nor + ".flac"
elif os.path.exists(nor + ".wav"):
full_file = nor + ".wav"
elif os.path.exists(nor + ".mp3"):
full_file = nor + ".mp3"
else:
self.is_valid = False
return cue_file
if is_title:
cue_file.file = full_file
if line.startswith(INDEX):
index = self.get_line_value(line)
if line.startswith("TRACK") and line.find("AUDIO"):
if not is_title:
cue_track = CueTrack(title, performer, index, full_file)
cue_file.append_track(cue_track)
is_title = False
return self.normalize(cue_file)
| Python |
'''
Created on Aug 26, 2010
@author: ivan
'''
import gtk
class Popup():
def __init__(self):
self.menu = gtk.Menu()
def get_menu(self):
return self.menu
def add_item(self, text, gtk_stock, func, arg=None):
item = gtk.ImageMenuItem(text)
img = gtk.image_new_from_stock(gtk_stock, gtk.ICON_SIZE_MENU)
item.set_image(img)
if arg:
item.connect("activate", lambda * a: func(arg))
else:
item.connect("activate", lambda * a: func())
self.menu.add(item)
def show(self, event):
self.menu.show_all()
self.menu.popup(None, None, None, event.button, event.time)
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
import gtk
def responseToDialog(entry, dialog, response):
dialog.response(response)
def one_line_dialog(dialog_title, text=None):
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK,
None)
dialog.set_title(dialog_title)
dialog.set_markup(dialog_title)
entry = gtk.Entry()
if text:
entry.set_text(text)
dialog.vbox.pack_end(entry, True, True, 0)
dialog.show_all()
dialog.run()
dialog.destroy()
return entry.get_text()
def info_dialog_with_link(title, version, link):
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK,
None)
dialog.set_title(title)
dialog.set_markup(title)
dialog.format_secondary_markup("<b>" + version + "</b>")
link = gtk.LinkButton(link, link)
link.show()
dialog.vbox.pack_end(link, True, True, 0)
dialog.show_all()
dialog.run()
dialog.destroy()
def show_entry_dialog(title, description):
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_OK,
None)
dialog.set_markup(title)
entry = gtk.Entry()
entry.connect("activate", responseToDialog, dialog, gtk.RESPONSE_OK)
hbox = gtk.HBox()
hbox.pack_start(gtk.Label("Value:"), False, 5, 5)
hbox.pack_end(entry)
dialog.format_secondary_markup(description)
dialog.vbox.pack_end(hbox, True, True, 0)
dialog.show_all()
dialog.run()
text = entry.get_text()
dialog.destroy()
return text
def show_login_password_error_dialog(title, description, login, password):
dialog = gtk.MessageDialog(
None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
title)
dialog.set_markup(title)
dialog.format_secondary_markup(description)
login_entry = gtk.Entry()
login_entry.set_text(login)
login_entry.show()
password_entry = gtk.Entry()
password_entry.set_text(password)
password_entry.set_visibility(False)
password_entry.set_invisible_char("*")
password_entry.show()
hbox = gtk.VBox()
hbox.pack_start(login_entry, False, False, 0)
hbox.pack_start(password_entry, False, False, 0)
dialog.vbox.pack_start(hbox, True, True, 0)
dialog.show_all()
dialog.run()
login_text = login_entry.get_text()
password_text = password_entry.get_text()
dialog.destroy()
return [login_text, password_text]
if __name__ == '__main__':
info_dialog_with_link("New version avaliable", "foobnix 0.2.1-8", "http://www.foobnix.com/?page=download")
gtk.main()
| Python |
'''
Created on Sep 28, 2010
@author: ivan
'''
import gtk
import urllib
from foobnix.util import LOG
class CoverImage(gtk.Image):
def __init__(self):
gtk.Image.__init__(self)
self.size = 150;
self.set_no_image()
def set_no_image(self):
image_name = "blank-disc-cut.jpg"
try:
pix = gtk.gdk.pixbuf_new_from_file("/usr/local/share/pixmaps/" + image_name) #@UndefinedVariable
except:
try:
pix = gtk.gdk.pixbuf_new_from_file("/usr/share/pixmaps/" + image_name) #@UndefinedVariable
except:
pix = gtk.gdk.pixbuf_new_from_file("foobnix/pixmaps/" + image_name) #@UndefinedVariable
pix = pix.scale_simple(self.size, self.size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.set_from_pixbuf(pix)
def set_image_from_url(self, url):
if not url:
LOG.warn("set_image_from_url URL is empty")
return None
image = self._create_pbuf_image_from_url(url)
image_pix_buf = image.scale_simple(self.size, self.size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.set_from_pixbuf(image_pix_buf)
def set_image_from_path(self, path):
pixbuf = gtk.gdk.pixbuf_new_from_file(path) #@UndefinedVariable
scaled_buf = pixbuf.scale_simple(self.size, self.size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.set_from_pixbuf(scaled_buf)
def _create_pbuf_image_from_url(self, url_to_image):
f = urllib.urlopen(url_to_image)
data = f.read()
pbl = gtk.gdk.PixbufLoader() #@UndefinedVariable
pbl.write(data)
pbuf = pbl.get_pixbuf()
pbl.close()
return pbuf | Python |
'''
Created on Sep 27, 2010
@author: ivan
'''
import gtk
from foobnix.util import LOG
class MyToolbar(gtk.Toolbar):
def __init__(self):
gtk.Toolbar.__init__(self)
self.show()
self.set_style(gtk.TOOLBAR_ICONS)
self.set_show_arrow(False)
self.set_icon_size(gtk.ICON_SIZE_SMALL_TOOLBAR)
self.i = 0
def add_button(self, tooltip, gtk_stock, func, param):
button = gtk.ToolButton(gtk_stock)
button.show()
button.set_tooltip_text(tooltip)
LOG.debug("Button-Controls-Clicked", tooltip, gtk_stock, func, param)
if param:
button.connect("clicked", lambda * a: func(param))
else:
button.connect("clicked", lambda * a: func())
self.insert(button, self.i)
self.i += 1
def add_separator(self):
sep = gtk.SeparatorToolItem()
sep.show()
self.insert(sep, self.i)
self.i += 1
class ToolbarSeparator(MyToolbar):
def __init__(self):
MyToolbar.__init__(self)
self.add_separator()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 30 авг. 2010
@author: ivan
'''
import gtk
def tab_close_button(func=None, arg=None):
"""button"""
button = gtk.Button()
button.set_relief(gtk.RELIEF_NONE)
img = gtk.image_new_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU)
button.set_image(img)
if func:
button.connect("event", func, arg)
button.show()
return button
def tab_close_label(func=None, arg=None, angel=0):
"""label"""
symbol = "×"
label = gtk.Label(symbol)
label.show()
label.set_angle(angel)
event = gtk.EventBox()
event.show()
event.add(label)
event.connect("enter-notify-event", lambda w, e:w.get_child().set_markup("<u>" + symbol + "</u>"))
event.connect("leave-notify-event", lambda w, e:w.get_child().set_markup(symbol))
if func:
event.connect("event", func, arg)
event.show()
return event
| Python |
'''
Created on Sep 23, 2010
@author: ivan
'''
class OneActiveToggledButton():
def __init__(self, buttons):
for button in buttons:
button.connect("toggled", self.one_button_selected, buttons)
def one_button_selected(self, clicked_button, buttons):
# so, the button becomes checked. Uncheck all other buttons
for button in buttons:
if button != clicked_button:
button.set_active(False)
if all([not button.get_active() for button in buttons]):
clicked_button.set_active(True)
# if the button should become unchecked, then do nothing
if not clicked_button.get_active():
return
| Python |
'''
Created on Sep 23, 2010
@author: ivan
'''
import gtk
class ScrolledTreeView(gtk.TreeView):
def __init__(self, policy_horizontal, policy_vertical):
gtk.TreeView.__init__(self)
scrool = gtk.ScrolledWindow()
scrool.set_policy(policy_horizontal, policy_vertical)
scrool.add_with_viewport(self)
scrool.show_all()
| Python |
'''
Created on Mar 16, 2010
@author: ivan
'''
from foobnix.util import LOG
'''
Created on Mar 11, 2010
@author: ivan
'''
import gtk
from foobnix.model.entity import CommonBean
class RadioListModel:
POS_ICON = 0
POS_TRACK_NUMBER = 1
POS_NAME = 2
POS_PATH = 3
POS_COLOR = 4
POS_INDEX = 5
def __init__(self, widget):
self.widget = widget
self.current_list_model = gtk.ListStore(str, str, str, str, str, int)
cellpb = gtk.CellRendererPixbuf()
cellpb.set_property('cell-background', 'yellow')
iconColumn = gtk.TreeViewColumn(_('Icon'), cellpb, stock_id=0, cell_background=4)
numbetColumn = gtk.TreeViewColumn(_('N'), gtk.CellRendererText(), text=1, background=4)
descriptionColumn = gtk.TreeViewColumn(_('Music List'), gtk.CellRendererText(), text=2, background=4)
widget.append_column(iconColumn)
widget.append_column(numbetColumn)
widget.append_column(descriptionColumn)
widget.set_model(self.current_list_model)
def get_size(self):
return len(self.current_list_model)
def getBeenByPosition(self, position):
bean = CommonBean()
bean.icon = self.current_list_model[position][ self.POS_ICON]
bean.tracknumber = self.current_list_model[position][ self.POS_TRACK_NUMBER]
bean.name = self.current_list_model[position][ self.POS_NAME]
bean.path = self.current_list_model[position][ self.POS_PATH]
bean.color = self.current_list_model[position][ self.POS_COLOR]
bean.index = self.current_list_model[position][ self.POS_INDEX]
return bean
def get_selected_bean(self):
LOG.info(self.widget)
selection = self.widget.get_selection()
LOG.info(selection)
model, selected = selection.get_selected()
LOG.info(model, selected)
if selected:
bean = CommonBean()
bean.icon = model.get_value(selected, self.POS_ICON)
bean.tracknumber = model.get_value(selected, self.POS_TRACK_NUMBER)
bean.name = model.get_value(selected, self.POS_NAME)
bean.path = model.get_value(selected, self.POS_PATH)
bean.color = model.get_value(selected, self.POS_COLOR)
bean.index = model.get_value(selected, self.POS_INDEX)
return bean
def clear(self):
self.current_list_model.clear()
def append(self, playlistBean):
self.current_list_model.append([playlistBean.icon, playlistBean.tracknumber, playlistBean.name, playlistBean.path, playlistBean.color, playlistBean.index])
def __del__(self, *a):
LOG.info("del")
| Python |
'''
Created on 15 2010
@author: ivan
'''
from __future__ import with_statement
import os
from foobnix.util import LOG
from foobnix.util.configuration import FOOBNIX_TMP_RADIO
FOOBNIX_DIR = (os.getenv("HOME") or os.getenv('USERPROFILE')) + "/.foobnix"
FOOBNIX_DIR_RADIO = FOOBNIX_TMP_RADIO
EXTENSION = ".fpl"
class FPL():
def __init__(self, name, urls_dict):
self.name = name;
self.urls_dict = urls_dict;
def __str__(self):
return self.name + "radios" + str(self.lines_dict)
class RadioFolder():
def __init__(self):
self.results = []
"""get list of foobnix playlist files in the directory"""
def get_radio_list(self):
if not os.path.isdir(FOOBNIX_DIR_RADIO):
LOG.warn("Not a folder ", FOOBNIX_DIR_RADIO)
return None
result = []
"""read directory files by extestion and size > 0 """
for item in os.listdir(FOOBNIX_DIR_RADIO):
path = os.path.join(FOOBNIX_DIR_RADIO, item)
if item.endswith(EXTENSION) and os.path.isfile(path) and os.path.getsize(path) > 0:
LOG.info("Find radio station playlist", item)
result.append(item)
return result
"""parser playlist by name"""
def parse_play_list(self, list_name):
path = os.path.join(FOOBNIX_DIR_RADIO, list_name)
if not os.path.isfile(path):
LOG.warn("Not a file ", path)
return None
dict = {}
"""get name and stations"""
with open(path) as file:
for line in file:
if line or not line.startswith("#") and "=" in line:
name_end = line.find("=")
name = line[:name_end].strip()
stations = line[name_end + 1:].split(",")
if stations:
good_stations = []
for url in stations:
good_url = url.strip()
if good_url and (good_url.startswith("http://") or good_url.startswith("file://")):
if not good_url.endswith("wma"):
if not good_url.endswith("asx"):
if not good_url.endswith("ram"):
good_stations.append(good_url)
dict[name] = good_stations
return dict
def get_radio_FPLs(self):
if self.results:
LOG.info("Folder with radio already read")
return self.results
names = self.get_radio_list()
if not names:
return []
results = []
for play_name in names:
content = self.parse_play_list(play_name)
LOG.info("Create FPL", play_name)
play_name = play_name[:-len(EXTENSION)]
results.append(FPL(play_name, content))
return results
| Python |
'''
Created on Jul 16, 2010
@author: ivan
'''
import urllib2
site = "http://www.screamer-radio.com/"
site_full = site + "directory/browsegenre/51/"
def load_urls_name_page():
connect = urllib2.urlopen(site_full)
data = connect.read()
file = open("SKY.FM.fpl", "w")
for line in data.split("\n"):
if line.find("sky.fm") > 0:
url = line[line.find('<td><a href="')+len('<td><a href="')+1:line.find('/">')]
name = line[line.find('sky.fm -')+len('sky.fm -')+1:line.find('</a></td>')]
LOG.info(name, url
urls = get_urls(site + url)
file.write(name.strip() + " = " + urls + "\n");
file.close()
def get_urls(path):
connect = urllib2.urlopen(path)
data = connect.read()
result = ""
for line in data.split("\n"):
if line.find(") http://") >0:
result = result + line[line.find(') ') +2:line.find("<br />")]+", "
return result[:-2]
load_urls_name_page()
#LOG.info(get_urls("http://www.screamer-radio.com/directory/show/3825/") | Python |
'''
Created on Sep 10, 2010
@author: ivan
'''
import urllib2
from foobnix.util.plsparser import get_radio_source
def load_urls_name_page():
file = open("XIPH_ORG.fpl", "w")
for i in xrange(7):
print "begin"
connect = urllib2.urlopen("http://dir.xiph.org/by_format/MP3?search=mp3&page=" + str(i))
data = connect.read()
print "end"
name = ""
link = ""
description = ""
genre = ""
genres = []
for line in data.split("\n"):
if line.find("('/stream/website');") >= 0:
if name:
link = get_radio_source(link);
if link:
all = name + " (" + description + ") " + ", ".join(genres) + "=" + link + "\n"
all = all.replace("'", "")
all = all.replace("&", "&")
print all
file.write(all)
genres = []
name = line[line.find("('/stream/website');") + len("('/stream/website');") + 2:line.find("</a>")]
#print "RADIO:- "+name.replace("'","'")
"""href="/listen/1003756/listen.m3u">M3U</a>"""
if line.find("M3U</a>") >= 0:
link = line[line.find('href="/listen/') + len('href="'):line.find('title="') - 2]
link = "http://dir.xiph.org/" + link
#print link
"""<p class="stream-description">Jazz, Soul und Blues rund um die Uhr</p>"""
if line.find('stream-description">') >= 0:
description = line[line.find('stream-description">') + len("stream-description'>"):line.find("</p>")]
#print "description:- "+description.replace("'","'")
"""<a title="Music radios" href="/by_genre/Music">Music</a>"""
if line.find(' href="/by_genre/') >= 0 and line.find("dir.xiph.org") < 0:
genre = line[line.find('>') + len('href="/by_genre/') + 4:line.find('</a>')]
if genre.find('" title') > 0:
genre = genre[:genre.find('" title')]
#print "genre:- "+genre
genres.append(genre)
file.close();
load_urls_name_page()
| Python |
# -*- coding: utf-8 -*-
'''
Created on Jul 16, 2010
@author: ivan
'''
import urllib2
import re
site = "http://guzei.com/online_radio/?search=france"
def load_urls_name_page():
file = open("GUZEI.COM.fpl", "w")
for j in xrange(33):
j = j + 1;
site ="http://guzei.com/online_radio/?p="+str(j);
connect = urllib2.urlopen(site)
data = connect.read()
result = {}
for line in data.split("\n"):
#LOG.info(line
reg_all = "([^{</}]*)"
all = '<a href="./listen.php\?online_radio_id=([0-9]*)" target="guzei_online" title="'+reg_all+'"><span class="name">'+reg_all+'</span></a>'
all1 ='<a href="./listen.php\?online_radio_id=([0-9]*)" target="guzei_online">'+reg_all+'</a>'
links = re.findall(all, line, re.IGNORECASE | re.UNICODE)
links1 = re.findall(all1, line, re.IGNORECASE | re.UNICODE)
if links:
i = 0
for line in links:
id = line[0]
name = line[2] +" - "+ str(links1[i][1])
i+=1
url = get_ulr_by_id(id)
res = name + " = " + url
LOG.info(j
LOG.info(res
file.write(res + "\n")
file.close()
def get_ulr_by_id(id):
url = "http://guzei.com/online_radio/listen.php?online_radio_id="+id
connect = urllib2.urlopen(url)
data = connect.read()
for line in data.split("\n"):
cr = 'Прямая ссылка на поток:'
if line.find(cr) >= 0:
link = line[line.find(cr)+len(cr):line.find('</p>')]
link = link.strip()
return link
#LOG.info(get_ulr_by_id("5369")
load_urls_name_page() | Python |
'''
Created on Jul 16, 2010
@author: ivan
'''
| Python |
'''
Created on 16 2010
@author: ivan
'''
import urllib2
site = "http://di.fm"
def load_urls_name_page():
connect = urllib2.urlopen(site)
data = connect.read()
result = {}
file = open("DI_FM.fpl", "w")
for line in data.split("\n"):
pre = '<td><a href="http://listen.di.fm/public3/'
if line.find(pre) > 0:
el = "<td><a href=\""
url = line[line.find(el) + len(el) :line.find("\" rel")]
LOG.info(url
name = url[url.rfind("/") + 1:]
name = name[:-4]
LOG.info(
file.write(name + " = " + url + "\n")
file.close()
load_urls_name_page()
| Python |
'''
Created on 16 2010
@author: ivan
'''
import urllib2
site = "http://myradio.ua/"
def load_urls_name_page():
connect = urllib2.urlopen(site)
data = connect.read()
result = {}
file = open("MYRADIO_UA.fpl", "w")
for line in data.split("\n"):
line = line.decode("cp1251")
pre = "<a href=\"chanel/";
start = line.find(pre)
end = line.find("</a>", start + 10)
if start > 0 and end > 0:
url = line[line.find("<a href=\"") + len(" < a href"):line.find(">", start)].replace('"', '')
name = line[line.find(">", start) + 1:line.find("</a>")]
result[url.strip()] = name
urls = get_radio_ulr(url.strip()).split(",")
line = name.strip() + " = " + urls[1] + ", " + urls[0]
file.write(line + "\n");
LOG.info(line
if url.strip() == "chanel/eurovision":
file.close();
return result
def get_radio_ulr(chanel):
connect = urllib2.urlopen(site + chanel)
data = connect.read()
result = ""
for line in data.rsplit("\n"):
"""<img class="roll" src="http://img.myradio.com.ua/img/center/big_listen_icons/winamp_low_out.jpg">"""
if line.find('<img class="roll" src="') > 0 and line.find('.m3u') and line.find("window") < 0 :
pre = '<div class="but"><a href="'
index_pre = line.find(pre)
url = line[index_pre + len(pre): line.find('.m3u', index_pre)]
url = site + url + ".m3u"
result = result + url + ", "
return result[:-2]
LOG.info( load_urls_name_page()
| Python |
'''
Created on Mar 16, 2010
@author: ivan
'''
from foobnix.radio.radio_model import RadioListModel
from foobnix.util.plsparser import getStationPath, getPlsName, get_content
from foobnix.model.entity import CommonBean
from foobnix.util.mouse_utils import is_double_click
import urllib2
from foobnix.util import LOG
class RadioListCntr():
def __init__(self, gxMain, playerCntr):
self.widget = gxMain.get_widget("radio_list_treeview")
addButton = gxMain.get_widget("add_radio_toolbutton")
removeButton = gxMain.get_widget("remove_radio_toolbuton")
self.urlText = gxMain.get_widget("radio_url_entry")
self.widget.connect("button-press-event", self.onPlaySong)
addButton.connect("clicked", self.onAddRadio)
removeButton.connect("clicked", self.onRemoveRadio)
self.current_list_model = RadioListModel(self.widget)
self.playerCntr = playerCntr
self.widget.connect("button-press-event", self.onPlaySong)
self.entityBeans = []
self.index = self.current_list_model.get_size();
def onAddRadio(self, *args):
urlStation = self.urlText.get_text()
if urlStation:
nameDef = urlStation
if urlStation.endswith(".pls"):
getUrl = getStationPath(urlStation)
if getUrl:
urlStation = getUrl
nameDef = getPlsName(nameDef) + " [" + urlStation + " ]"
LOG.info(nameDef)
elif urlStation.endswith(".m3u"):
content = get_content(urlStation)
for line in content.rsplit():
if not line.startswith("#"):
urlStation = line
nameDef = line
break
entity = CommonBean(name=nameDef, path=urlStation, type=CommonBean.TYPE_RADIO_URL, index=self.index + 1);
self.entityBeans.append(entity)
self.repopulate(self.entityBeans, (self.current_list_model.get_size()))
self.urlText.set_text("")
pass
def onRemoveRadio(self, *args):
model, iter = self.widget.get_selection().get_selected()
if iter:
playlistBean = self.current_list_model.get_selected_bean()
for i, entity in enumerate(self.entityBeans):
if entity.path == playlistBean.path:
self.index = 0
del self.entityBeans[i]
model.remove(iter)
def getState(self):
return [self.entityBeans, self.index]
def setState(self, state):
self.entityBeans = state[0]
self.index = state[1]
if self.entityBeans and self.index < len(self.entityBeans):
self.repopulate(self.entityBeans, self.index);
self.playerCntr.playSong(self.entityBeans[self.index])
def clear(self):
self.current_list_model.clear()
def onPlaySong(self, w, e):
if is_double_click(e):
LOG.info(w, e)
playlistBean = self.current_list_model.get_selected_bean()
playlistBean.type = CommonBean.TYPE_RADIO_URL
#self.repopulate(self.entityBeans, playlistBean.index);
self.index = playlistBean.index
if not playlistBean.path.startswith("http"):
return None
LOG.info(playlistBean.path)
remotefile = urllib2.urlopen(playlistBean.path)
LOG.info("INFO", remotefile)
if not remotefile.info() or remotefile.info()["Content-Type"].find("text") == -1:
self.playerCntr.playSong(playlistBean)
else:
LOG.error("Can't play html page")
return None
def getNextSong(self):
self.index += 1
if self.index >= len(self.entityBeans):
self.index = 0
playlistBean = self.current_list_model.getBeenByPosition(self.index)
self.repopulate(self.entityBeans, playlistBean.index);
return playlistBean
def getPrevSong(self):
self.index -= 1
if self.index < 0:
self.index = len(self.entityBeans) - 1
playlistBean = self.current_list_model.getBeenByPosition(self.index)
self.repopulate(self.entityBeans, playlistBean.index);
return playlistBean
def setPlaylist(self, entityBeans):
self.entityBeans = entityBeans
index = 0
if entityBeans:
self.playerCntr.playSong(entityBeans[index])
self.repopulate(entityBeans, index);
def repopulate(self, entityBeans, index):
self.current_list_model.clear()
for i in range(len(entityBeans)):
songBean = entityBeans[i]
songBean.color = self.getBackgroundColour(i)
songBean.name = songBean.getPlayListDescription()
songBean.index = i
if i == index:
songBean.setIconPlaying()
self.current_list_model.append(songBean)
else:
songBean.setIconNone()
self.current_list_model.append(songBean)
def getBackgroundColour(self, i):
if i % 2 :
return "#F2F2F2"
else:
return "#FFFFE5"
| Python |
#!/usr/bin/env python
# example packbox.py
import gtk
from foobnix.preferences.configs.music_library import MusicLibraryConfig
from foobnix.util.configuration import FConfiguration, get_version
from foobnix.preferences.configs.save_online import SaveOnlineConfig
from foobnix.preferences.configs.last_fm import LastFmConfig
from foobnix.preferences.configs.vk_conf import VkontakteConfig
from foobnix.preferences.configs.tabs import TabsConfig
from foobnix.preferences.configs.info_panel_conf import InfoPagenConfig
from foobnix.preferences.configs.network_conf import NetworkConfig
from foobnix.preferences.configs.notification_conf import NotificationConfig
from foobnix.preferences.configs.tray_icon import TrayIconConfig
from foobnix.preferences.configs.hotkey_conf import HotKeysConfig
import thread
import os
from foobnix.regui.state import LoadSave
from foobnix.regui.model.signal import FControl
from foobnix.util.fc import FC
class PreferencesWindow(FControl, LoadSave):
configs = []
POS_NAME = 0
def __init__(self, controls):
FControl.__init__(self, controls)
self.configs.append(MusicLibraryConfig(controls))
self.configs.append(SaveOnlineConfig(controls))
self.configs.append(TabsConfig(controls))
self.configs.append(LastFmConfig(controls))
self.configs.append(VkontakteConfig(controls))
self.configs.append(InfoPagenConfig(controls))
self.configs.append(TrayIconConfig(controls))
self.configs.append(NetworkConfig(controls))
self.configs.append(NotificationConfig(controls))
self.configs.append(HotKeysConfig(controls))
#self.configs.append(CategoryInfoConfig())
self.label = None
mainVBox = gtk.VBox(False, 0)
self.window = self.craete_window()
paned = gtk.HPaned()
paned.set_position(200)
paned.show()
paned.add1(self.create_left_menu())
cbox = gtk.VBox(False, 0)
cbox.show()
for plugin in self.configs:
cbox.pack_start(plugin.widget, False, True, 0)
cbox.show()
self.container = self.create_container(cbox)
paned.add2(self.container)
mainVBox.pack_start(paned, True, True, 0)
mainVBox.pack_start(self.create_save_cancel_buttons(), False, False, 0)
mainVBox.show()
self.window.add(mainVBox)
#self.show()
self.populate_config_category(self.configs[0].name)
self.on_load()
def show(self):
self.on_load()
self.window.show()
def hide(self):
print "hide preferences"
self.window.hide()
#TEMP
#gtk.main_quit()
return True
def on_load(self):
for plugin in self.configs:
plugin.on_load()
def on_save(self):
for plugin in self.configs:
plugin.on_save()
FC().save()
self.hide()
def craete_window(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("delete-event", lambda * a: self.hide())
window.connect("destroy", lambda * a: self.hide())
window.set_border_width(10)
window.set_title("Foobnix " + get_version() + " - " + _ ("Preferences"))
window.set_resizable(False)
window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
window.set_size_request(800, 500)
return window
def create_left_menu(self):
model = gtk.ListStore(str)
for plugin in self.configs:
model.append([plugin.name])
treeview = gtk.TreeView()
column_name = gtk.TreeViewColumn(_("Categories"), gtk.CellRendererText(), text=self.POS_NAME)
treeview.append_column(column_name)
treeview.set_model(model)
treeview.connect("cursor-changed", self.on_change_category)
treeview.show()
return treeview
def populate_config_category(self, name):
for plugin in self.configs:
if plugin.name == name:
plugin.show()
self.update_label(name)
else:
plugin.hide()
def on_change_category(self, w):
selection = w.get_selection()
model, selected = selection.get_selected()
if selected:
name = model.get_value(selected, self.POS_NAME)
self.populate_config_category(name)
def create_save_cancel_buttons(self):
box = gtk.HBox(False, 0)
box.show()
button_restore = gtk.Button(_("Restore Defaults"))
button_restore.connect("clicked", lambda * a:self.restore_defaults())
button_restore.show()
button_save = gtk.Button(_("Save"))
button_save.set_size_request(100, -1)
button_save.connect("clicked", lambda * a:self.on_save())
button_save.show()
button_cancel = gtk.Button(_("Cancel"))
button_cancel.set_size_request(100, -1)
button_cancel.connect("clicked", lambda * a:self.hide())
button_cancel.show()
empty = gtk.Label("")
empty.show()
box.pack_start(button_restore, False, True, 0)
box.pack_start(empty, True, True, 0)
box.pack_start(button_save, False, True, 0)
box.pack_start(button_cancel, False, True, 0)
return box
def restore_defaults(self):
print "restore defaults"
gtk.main_quit()
FConfiguration().remove_cfg_file()
thread.start_new_thread(os.system, ("foobnix",))
def update_label(self, title):
self.label.set_markup('<b><i><span size="x-large" >' + title + '</span></i></b>');
def create_container(self, widget):
box = gtk.VBox(False, 0)
box.show()
self.label = gtk.Label()
self.label.show()
separator = gtk.HSeparator()
separator.show()
box.pack_start(self.label, False, True, 0)
box.pack_start(separator, False, True, 0)
box.pack_start(widget, False, True, 0)
return box
def main():
gtk.main()
return 0
if __name__ == "__main__":
w = PreferencesWindow(None, None)
w.show()
main()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
import gtk
from foobnix.preferences.config_plugin import ConfigPlugin
from foobnix.util.configuration import FConfiguration
class LastFmConfig(ConfigPlugin):
name = _("Last FM")
def __init__(self, controls):
print "Create try icon conf"
box = gtk.VBox(False, 0)
box.hide()
"""LOGIN"""
lbox = gtk.HBox(False, 0)
lbox.show()
login = gtk.Label(_("Login"))
login.set_size_request(150, -1)
login.show()
self.login_text = gtk.Entry()
self.login_text.show()
lbox.pack_start(login, False, False, 0)
lbox.pack_start(self.login_text, False, True, 0)
"""PASSWORD"""
pbox = gtk.HBox(False, 0)
pbox.show()
password = gtk.Label(_("Password"))
password.set_size_request(150, -1)
password.show()
self.password_text = gtk.Entry()
self.password_text.set_visibility(False)
self.password_text.set_invisible_char("*")
self.password_text.show()
self.music_srobbler = gtk.CheckButton(label=_("Enable Music Srobbler"), use_underline=True)
self.music_srobbler.show()
self.radio_srobbler = gtk.CheckButton(label=_("Enable Radio Srobbler"), use_underline=True)
self.radio_srobbler.show()
pbox.pack_start(password, False, False, 0)
pbox.pack_start(self.password_text, False, True, 0)
box.pack_start(lbox, False, True, 0)
box.pack_start(pbox, False, True, 0)
box.pack_start(self.music_srobbler, False, True, 0)
box.pack_start(self.radio_srobbler, False, True, 0)
self.widget = box
def on_load(self):
self.login_text.set_text(FConfiguration().lfm_login)
self.password_text.set_text(FConfiguration().lfm_password)
self.music_srobbler.set_active(FConfiguration().enable_music_srobbler)
self.radio_srobbler.set_active(FConfiguration().enable_radio_srobbler)
def on_save(self):
if FConfiguration().lfm_login != self.login_text.get_text() or FConfiguration().lfm_password != self.password_text.get_text():
FConfiguration().cookie = None
FConfiguration().lfm_login = self.login_text.get_text()
FConfiguration().lfm_password = self.password_text.get_text()
FConfiguration().enable_music_srobbler = self.music_srobbler.get_active()
FConfiguration().enable_radio_srobbler = self.radio_srobbler.get_active()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 3 сент. 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.util.configuration import FConfiguration
class NotificationConfig(ConfigPlugin):
name = _("Notifications")
def __init__(self,controls):
print "Create notificatino conf"
box = gtk.VBox(False, 0)
box.hide()
self.check_new_version = gtk.CheckButton(label=_("Check for new version on start"), use_underline=True)
self.check_new_version.show()
box.pack_start(self.check_new_version, False, True, 0)
self.widget = box
def on_load(self):
self.check_new_version.set_active(FConfiguration().check_new_version)
def on_save(self):
FConfiguration().check_new_version = self.check_new_version.get_active()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
from foobnix.util.configuration import FConfiguration
from foobnix.preferences.configs.last_fm import LastFmConfig
class VkontakteConfig(LastFmConfig):
name = _("Vkontakte")
def __init__(self, controls):
LastFmConfig.__init__(self, controls)
def on_load(self):
self.login_text.set_text(FConfiguration().vk_login)
self.password_text.set_text(FConfiguration().vk_password)
def on_save(self):
if FConfiguration().vk_login != self.login_text.get_text() or FConfiguration().vk_password != self.password_text.get_text():
FConfiguration().cookie = None
FConfiguration().vk_login = self.login_text.get_text()
FConfiguration().vk_password = self.password_text.get_text()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 1 сент. 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.util.configuration import FConfiguration
from foobnix.util.proxy_connect import set_proxy_settings
import time
import urllib2
from foobnix.util import LOG
class NetworkConfig(ConfigPlugin):
name = _("Network Settings")
def __init__(self, controls):
box = gtk.VBox(False, 0)
box.hide()
self.enable_proxy = gtk.CheckButton(label=_("Enable HTTP proxy"), use_underline=True)
self.enable_proxy.connect("clicked", self.on_enable_http_proxy)
self.enable_proxy.show()
self.frame = gtk.Frame(label=_("Settings"))
self.frame.set_border_width(0)
self.frame.show()
all = gtk.VBox(False, 0)
all.show()
"""URL"""
proxy_box = gtk.HBox(False, 0)
proxy_box.show()
proxy_lable = gtk.Label(_("Server"))
proxy_lable.set_size_request(150, -1)
proxy_lable.show()
self.proxy_server = gtk.Entry()
self.proxy_server.show()
require = gtk.Label(_("example: 66.42.182.178:3128"))
require.show()
proxy_box.pack_start(proxy_lable, False, False, 0)
proxy_box.pack_start(self.proxy_server, False, True, 0)
proxy_box.pack_start(require, False, True, 0)
"""LOGIN"""
lbox = gtk.HBox(False, 0)
lbox.show()
login = gtk.Label(_("Login"))
login.set_size_request(150, -1)
login.show()
self.login_text = gtk.Entry()
self.login_text.show()
lbox.pack_start(login, False, False, 0)
lbox.pack_start(self.login_text, False, True, 0)
"""PASSWORD"""
pbox = gtk.HBox(False, 0)
pbox.show()
password = gtk.Label(_("Password"))
password.set_size_request(150, -1)
password.show()
self.password_text = gtk.Entry()
self.password_text.set_visibility(False)
self.password_text.set_invisible_char("*")
self.password_text.show()
pbox.pack_start(password, False, False, 0)
pbox.pack_start(self.password_text, False, True, 0)
"""check"""
check = gtk.HBox(False, 0)
check.show()
self.vk_test = gtk.Entry()
self.vk_test.set_text("http://vkontakte.ru")
self.vk_test.show()
self.test_button = gtk.Button(_("Check Connection"))
self.test_button.set_size_request(150, -1)
self.test_button.connect("clicked", self.text_connection)
self.test_button.show()
self.result = gtk.Label(_("Result:"))
self.result.show()
check.pack_start(self.test_button, False, True, 0)
check.pack_start(self.vk_test, False, False, 0)
check.pack_start(self.result, False, True, 0)
"""global"""
all.pack_start(proxy_box, False, False, 0)
all.pack_start(lbox, False, False, 0)
all.pack_start(pbox, False, False, 0)
all.pack_start(check, False, False, 0)
self.frame.add(all)
frame_box = gtk.HBox(False, 0)
frame_box.set_border_width(5)
frame_box.show()
box.pack_start(self.enable_proxy, False, True, 0)
box.pack_start(self.frame, False, True, 0)
self.widget = box
def text_connection(self, *a):
self.on_save()
set_proxy_settings()
init = time.time()
try:
f = urllib2.urlopen(self.vk_test.get_text())
f.read()
f.close()
except Exception, e:
LOG.error(e)
self.result.set_text(str(e))
return None
seconds = time.time() - init
self.result.set_text(_("Result:") + _(" OK in seconds: ") + str(seconds))
def on_enable_http_proxy(self, *a):
if self.enable_proxy.get_active():
self.frame.set_sensitive(True)
FConfiguration().proxy_enable = True
else:
self.frame.set_sensitive(False)
FConfiguration().proxy_enable = False
def on_load(self):
self.enable_proxy.set_active(FConfiguration().proxy_enable)
self.frame.set_sensitive(FConfiguration().proxy_enable)
if self.enable_proxy.get_active():
FConfiguration().cookie = None
if FConfiguration().proxy_url:
self.proxy_server.set_text(FConfiguration().proxy_url)
if FConfiguration().proxy_user:
self.login_text.set_text(FConfiguration().proxy_user)
if FConfiguration().proxy_password:
self.password_text.set_text(FConfiguration().proxy_password)
def on_save(self):
if self.proxy_server.get_text():
FConfiguration().proxy_url = self.proxy_server.get_text()
else:
FConfiguration().proxy_url = None
if self.login_text.get_text():
FConfiguration().proxy_user = self.login_text.get_text()
else:
FConfiguration().proxy_user = None
if self.password_text.get_text():
FConfiguration().proxy_password = self.password_text.get_text()
else:
FConfiguration().proxy_password = None
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
import gtk
from foobnix.preferences.config_plugin import ConfigPlugin
class CategoryInfoConfig(ConfigPlugin):
name = "Category Info"
def __init__(self):
print "Craete Category info conf"
box = gtk.VBox(False, 0)
box.hide()
similar_arists = gtk.CheckButton(label="Show Similar Artists", use_underline=True)
similar_arists.show()
similar_song = gtk.CheckButton(label="Show Similar Songs", use_underline=True)
similar_song.show()
similar_tags = gtk.CheckButton(label="Show Similar Tags", use_underline=True)
similar_tags.show()
box.pack_start(similar_arists, False, True, 0)
box.pack_start(similar_song, False, True, 0)
box.pack_start(similar_tags, False, True, 0)
self.widget = box
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.base.base_list_controller import BaseListController
from foobnix.helpers.dialog_entry import show_entry_dialog
import foobnix.util.localization
from foobnix.util import LOG
from foobnix.util.fc import FC
from foobnix.regui.model.signal import FControl
class MusicLibraryConfig(ConfigPlugin, FControl):
name = _("Music Library")
enable = True
def __init__(self, controls):
FControl.__init__(self, controls)
box = gtk.VBox(False, 0)
box.hide()
self.child_button = gtk.CheckButton(label=_("Get music from child folders"), use_underline=True)
self.child_button.show()
box.pack_start(self.dirs(), False, True, 0)
box.pack_start(self.child_button, False, True, 0)
box.pack_start(self.formats(), False, True, 0)
self.widget = box
def dirs(self):
frame = gtk.Frame(label=_("Music dirs"))
frame.set_border_width(0)
frame.show()
frame_box = gtk.HBox(False, 0)
frame_box.set_border_width(5)
frame_box.show()
dir_tree = gtk.TreeView()
dir_tree.show()
self.tree_controller = BaseListController(dir_tree)
self.tree_controller.set_title(_("Path"))
"""reload button"""
reload_button = gtk.Button(_("Reload"))
reload_button.show()
"""buttons"""
button_box = gtk.VBox(False, 0)
button_box.show()
bt_add = gtk.Button(_("Add"))
bt_add.connect("clicked", self.add_dir)
bt_add.set_size_request(80, -1)
bt_add.show()
bt_remove = gtk.Button(_("Remove"))
bt_remove.connect("clicked", self.remove_dir)
bt_remove.set_size_request(80, -1)
bt_remove.show()
empty = gtk.Label("")
empty.show()
bt_reload = gtk.Button(label=_("Reload"))
bt_reload.connect("clicked", self.reload_dir)
bt_reload.set_size_request(80, -1)
bt_reload.show()
button_box.pack_start(bt_add, False, False, 0)
button_box.pack_start(bt_remove, False, False, 0)
button_box.pack_start(empty, True, True, 0)
button_box.pack_start(bt_reload, False, False, 0)
scrool_tree = gtk.ScrolledWindow()
scrool_tree.set_size_request(-1, 170)
scrool_tree.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scrool_tree.add_with_viewport(dir_tree)
scrool_tree.show()
frame_box.pack_start(scrool_tree, True, True, 0)
frame_box.pack_start(button_box, False, False, 0)
frame.add(frame_box)
return frame
def reload_dir(self, *a):
FC().music_paths = self.tree_controller.get_all_items()
self.controls.update_music_tree()
def on_load(self):
self.tree_controller.clear()
for path in FC().music_paths:
self.tree_controller.add_item(path)
self.files_controller.clear()
for ext in FC().support_formats:
self.files_controller.add_item(ext)
def on_save(self):
FC().music_paths = self.tree_controller.get_all_items()
FC().support_formats = self.files_controller.get_all_items()
def add_dir(self, *a):
chooser = gtk.FileChooserDialog(title=_("Choose directory with music"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
chooser.set_select_multiple(True)
if FC().last_music_path:
chooser.set_current_folder(FC().last_music_path)
response = chooser.run()
if response == gtk.RESPONSE_OK:
paths = chooser.get_filenames()
path = paths[0]
FC().last_music_path = path[:path.rfind("/")]
for path in paths:
if path not in self.tree_controller.get_all_items():
self.tree_controller.add_item(path)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
print "add folder(s)"
def remove_dir(self, *a):
self.tree_controller.remove_selected()
def formats(self):
frame = gtk.Frame(label=_("File Types"))
frame.set_border_width(0)
frame.show()
frame_box = gtk.HBox(False, 0)
frame_box.set_border_width(5)
frame_box.show()
dir_tree = gtk.TreeView()
dir_tree.show()
self.files_controller = BaseListController(dir_tree)
self.files_controller.set_title(_("Extension"))
"""buttons"""
button_box = gtk.VBox(False, 0)
button_box.show()
bt_add = gtk.Button(_("Add"))
bt_add.connect("clicked", self.on_add_file)
bt_add.set_size_request(80, -1)
bt_add.show()
bt_remove = gtk.Button(_("Remove"))
bt_remove.connect("clicked", lambda * a:self.files_controller.remove_selected())
bt_remove.set_size_request(80, -1)
bt_remove.show()
button_box.pack_start(bt_add, False, False, 0)
button_box.pack_start(bt_remove, False, False, 0)
scrool_tree = gtk.ScrolledWindow()
scrool_tree.set_size_request(-1, 160)
scrool_tree.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scrool_tree.add_with_viewport(dir_tree)
scrool_tree.show()
frame_box.pack_start(scrool_tree, True, True, 0)
frame_box.pack_start(button_box, False, False, 0)
frame.add(frame_box)
return frame
def on_add_file(self, *a):
val = show_entry_dialog(_("Please add audio extension"), _("Extension should be like '.mp3'"))
if val and val.find(".") >= 0 and len(val) <= 5 and val not in self.files_controller.get_all_items():
self.files_controller.add_item(val)
else:
LOG.info("Can't add your value", val)
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.util.configuration import FConfiguration
from foobnix.helpers.my_widgets import tab_close_label, tab_close_button
class TabsConfig(ConfigPlugin):
name = _("Tabs")
def __init__(self, controls):
print "Create try icon conf"
box = gtk.VBox(False, 0)
box.hide()
"""count"""
cbox = gtk.HBox(False, 0)
cbox.show()
tab_label = gtk.Label(_("Count of tabs"))
tab_label.set_size_request(150, -1)
tab_label.show()
adjustment = gtk.Adjustment(value=1, lower=1, upper=20, step_incr=1, page_incr=10, page_size=0)
self.tabs_count = gtk.SpinButton(adjustment)
self.tabs_count.connect("value-changed", self.on_chage_count_tabs)
self.tabs_count.show()
cbox.pack_start(tab_label, False, False, 0)
cbox.pack_start(self.tabs_count, False, True, 0)
"""len"""
lbox = gtk.HBox(False, 0)
lbox.show()
tab_label = gtk.Label(_("Max length of tab"))
tab_label.set_size_request(150, -1)
tab_label.show()
adjustment = gtk.Adjustment(value=0, lower=0, upper=300, step_incr=1, page_incr=10, page_size=0)
self.tab_len = gtk.SpinButton(adjustment)
self.tab_len.connect("value-changed", self.on_chage_len_tab)
self.tab_len.show()
lbox.pack_start(tab_label, False, False, 0)
lbox.pack_start(self.tab_len, False, True, 0)
"""position"""
pbox = gtk.HBox(False, 0)
pbox.show()
label = gtk.Label(_("Tab position"))
label.set_size_request(150, -1)
label.show()
self.radio_tab_left = gtk.RadioButton(None, _("Left"))
self.radio_tab_left.connect("toggled", self.on_chage_tab_position)
self.radio_tab_left.show()
self.radio_tab_top = gtk.RadioButton(self.radio_tab_left, _("Top"))
self.radio_tab_top.connect("toggled", self.on_chage_tab_position)
self.radio_tab_top.show()
self.radio_tab_no = gtk.RadioButton(self.radio_tab_left, _("No Tabs"))
self.radio_tab_no.connect("toggled", self.on_chage_tab_position)
self.radio_tab_no.show()
pbox.pack_start(label, False, False, 0)
pbox.pack_start(self.radio_tab_left, False, False, 0)
pbox.pack_start(self.radio_tab_top, False, True, 0)
pbox.pack_start(self.radio_tab_no, False, True, 0)
"""closed type """
close_label_box = gtk.HBox(False, 0)
close_label_box.show()
close_label = gtk.Label(_("Close tab sign"))
close_label.show()
self.radio_tab_label = gtk.RadioButton(None, None)
self.radio_tab_label.connect("toggled", self.on_chage_tab_position)
self.radio_tab_label.show()
self.radio_tab_button = gtk.RadioButton(self.radio_tab_label, None)
self.radio_tab_button.connect("toggled", self.on_chage_tab_position)
self.radio_tab_button.show()
close_label_box.pack_start(close_label, False, False, 0)
close_label_box.pack_start(self.radio_tab_label, False, False, 0)
close_label_box.pack_start(tab_close_label(), False, False, 0)
close_label_box.pack_start(self.radio_tab_button, False, True, 0)
close_label_box.pack_start(tab_close_button(), False, False, 0)
"""global pack"""
box.pack_start(cbox, False, True, 0)
box.pack_start(lbox, False, True, 0)
box.pack_start(pbox, False, True, 0)
box.pack_start(close_label_box, False, True, 0)
self.widget = box
def on_chage_tab_position(self, *args):
if self.radio_tab_left.get_active():
self.online_controller.set_tab_left()
elif self.radio_tab_top.get_active():
self.online_controller.set_tab_top()
elif self.radio_tab_no.get_active():
self.online_controller.set_tab_no()
def on_chage_count_tabs(self, w):
val = w.get_value_as_int()
FConfiguration().count_of_tabs = val
def on_chage_len_tab(self, w):
val = w.get_value_as_int()
FConfiguration().len_of_tab = val
def on_load(self):
self.tabs_count.set_value(FConfiguration().count_of_tabs)
self.tab_len.set_value(FConfiguration().len_of_tab)
if FConfiguration().tab_position == "left":
self.radio_tab_left.set_active(True)
elif FConfiguration().tab_position == "top":
self.radio_tab_top.set_active(True)
elif FConfiguration().tab_position == "no":
self.radio_tab_no.set_active(True)
if FConfiguration().tab_close_element == "label":
self.radio_tab_label.set_active(True)
elif FConfiguration().tab_close_element == "button":
self.radio_tab_button.set_active(True)
def on_save(self):
FConfiguration().count_of_tabs = self.tabs_count.get_value_as_int()
FConfiguration().len_of_tab = self.tab_len.get_value_as_int()
if self.radio_tab_label.get_active():
FConfiguration().tab_close_element = "label"
elif self.radio_tab_button.get_active():
FConfiguration().tab_close_element = "button"
| Python |
'''
Created on Sep 7, 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.helpers.menu import Popup
from foobnix.util.configuration import FConfiguration
import keybinder
import os
from foobnix.util import LOG
import thread
from foobnix.util.mouse_utils import is_double_left_click
class HotKeysConfig(ConfigPlugin):
name = _("Global Hotkeys")
def __init__(self, controls):
print "Create try icon conf"
box = gtk.VBox(False, 0)
box.hide()
self.tree_widget = gtk.TreeView()
self.tree_widget.connect("button-press-event", self.on_populate_click)
self.tree_widget.show()
self.model = gtk.ListStore(str,str)
self.title = None
self.column1 = gtk.TreeViewColumn(_("Action"), gtk.CellRendererText(), text=0)
self.column2 = gtk.TreeViewColumn(_("Hotkey"), gtk.CellRendererText(), text=1)
self.tree_widget.append_column(self.column1)
self.tree_widget.append_column(self.column2)
self.tree_widget.set_model(self.model)
hbox = gtk.HBox(False, 0)
hbox.show()
add_button = gtk.Button(_("Add"))
add_button.set_size_request(80, -1)
add_button.connect("clicked", self.on_add_row)
add_button.show()
remove_button = gtk.Button(_("Remove"))
remove_button.connect("clicked", self.on_remove_row)
remove_button.set_size_request(80, -1)
remove_button.show()
hbox.pack_start(add_button, False, True, 0)
hbox.pack_start(remove_button, False, True, 0)
hotbox = gtk.HBox(False, 0)
hotbox.show()
self.action_text = gtk.Entry()
self.action_text.set_size_request(150, -1)
self.action_text.connect("button-press-event", self.on_mouse_click)
self.action_text.show()
self.hotkey_text = gtk.Entry()
self.hotkey_text.set_editable(False)
self.hotkey_text.connect("key-press-event", self.on_key_press)
#self.hotkey_text.connect("key-release-event", self.on_key_release)
self.hotkey_text.set_size_request(150, -1)
self.hotkey_text.show()
hotbox.pack_start(self.action_text, False, True, 0)
hotbox.pack_start(self.hotkey_text, False, True, 0)
box.pack_start(self.tree_widget, False, True, 0)
box.pack_start(hotbox, False, True, 0)
box.pack_start(hbox, False, True, 0)
self.widget = box
def set_action_text(self, text):
self.action_text.set_text("foobnix " + text)
def set_hotkey_text(self, text):
self.hotkey_text.set_text(text)
def on_add_row(self, *args):
command = self.action_text.get_text()
hotkey = self.hotkey_text.get_text()
if command and hotkey:
if command not in self.get_all_items():
self.model.append([command, hotkey])
self.add_key_binder(command, hotkey);
self.action_text.set_text("")
self.hotkey_text.set_text("")
def on_remove_row(self, *args):
selection = self.tree_widget.get_selection()
model, selected = selection.get_selected()
model.remove(selected)
keystring = self.model.get_value(selected, 1)
try:
keybinder.unbind(keystring)
except:
pass
def on_populate_click(self,w,event):
if is_double_left_click(event):
selection = self.tree_widget.get_selection()
model, selected = selection.get_selected()
command = self.model.get_value(selected, 0)
keystring = self.model.get_value(selected, 1)
self.action_text.set_text(command)
self.hotkey_text.set_text(keystring)
def on_mouse_click(self,w, event):
menu = Popup()
menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.set_action_text, "--play")
menu.add_item(_("Pause"), gtk.STOCK_MEDIA_PAUSE, self.set_action_text, "--pause")
menu.add_item(_("Stop"), gtk.STOCK_MEDIA_STOP, self.set_action_text, "--stop")
menu.add_item(_("Next song"), gtk.STOCK_MEDIA_NEXT, self.set_action_text, "--next")
menu.add_item(_("Previous song"), gtk.STOCK_MEDIA_PREVIOUS, self.set_action_text, "--prev")
menu.add_item(_("Voulume up"), gtk.STOCK_GO_UP, self.set_action_text, "--volume-up")
menu.add_item(_("Voulume down"), gtk.STOCK_GO_DOWN, self.set_action_text, "--volume-down")
menu.add_item(_("Show-Hide"), gtk.STOCK_FULLSCREEN, self.set_action_text, "--show-hide")
menu.show(event)
def on_load(self):
items = FConfiguration().action_hotkey
self.model.clear()
for key in items:
command = key
hotkey = items[key]
self.model.append([command,hotkey])
self.bind_all(items)
def add_key_binder(self, command, hotkey):
try:
keybinder.bind(hotkey, self.activate_hot_key, command)
except Exception, e:
print hotkey, e
def activate_hot_key(self, command):
LOG.debug("Run command: "+command)
thread.start_new_thread(os.system,(command,))
def on_save(self):
FConfiguration().action_hotkey = self.get_all_items()
self.bind_all(self.get_all_items())
def unbind_all(self):
print "unbin all"
items = self.get_all_items()
for keystring in items:
try:
keybinder.unbind(items[keystring])
except:
pass
def bind_all(self,items):
for key in items:
command = key
hotkey = items[key]
self.add_key_binder(command, hotkey);
def get_all_items(self):
items = {}
for item in self.model:
action = item[0]
hotkey = item[1]
items[action]=hotkey
return items
def on_key_press(self,w,event):
self.unbind_all()
keyname = gtk.gdk.keyval_name(event.keyval)
print "Key %s (%d) was pressed" % (keyname, event.keyval), event.state
if event.state & gtk.gdk.CONTROL_MASK:
self.set_hotkey_text("<Control>"+keyname)
elif event.state & gtk.gdk.SHIFT_MASK :
self.set_hotkey_text("<Shift>"+keyname)
elif event.state & gtk.gdk.SUPER_MASK:
self.set_hotkey_text("<SUPER>"+keyname)
elif event.state & (gtk.gdk.MOD1_MASK | gtk.gdk.MOD2_MASK):
self.set_hotkey_text("<Alt>"+keyname)
else:
self.set_hotkey_text(keyname)
def on_key_release(self,w,event):
keyname = gtk.gdk.keyval_name(event.keyval)
print "Key release %s (%d) was pressed" % (keyname, event.keyval) | Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
import gtk
from foobnix.preferences.config_plugin import ConfigPlugin
from foobnix.util.configuration import FConfiguration
from foobnix.util import LOG
class SaveOnlineConfig(ConfigPlugin):
name = _("Online Music")
def __init__(self, controls):
print "Create try icon conf"
box = gtk.VBox(False, 0)
box.hide()
hbox = gtk.HBox(False, 0)
hbox.show()
self.is_save = gtk.CheckButton(label=_("Save online music"), use_underline=True)
self.is_save.connect("clicked", self.on_save_online)
self.is_save.show()
self.online_dir = gtk.FileChooserButton("set place")
self.online_dir.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
self.online_dir.connect("current-folder-changed", self.on_change_folder)
self.online_dir.show()
hbox.pack_start(self.is_save, False, True, 0)
hbox.pack_start(self.online_dir, True, True, 0)
box.pack_start(hbox, False, True, 0)
self.widget = box
def on_save_online(self, *a):
value = self.is_save.get_active()
if value:
self.online_dir.set_sensitive(True)
else:
self.online_dir.set_sensitive(False)
FConfiguration().is_save_online = value
def on_change_folder(self, *a):
path = self.online_dir.get_filename()
FConfiguration().onlineMusicPath = path
LOG.info("Change music online folder", path)
def on_load(self):
self.is_save.set_active(FConfiguration().is_save_online)
self.online_dir.set_current_folder(FConfiguration().onlineMusicPath)
self.online_dir.set_sensitive(FConfiguration().is_save_online)
| Python |
#-*- coding: utf-8 -*-
'''
Created on 29 авг. 2010
@author: ivan
'''
from foobnix.preferences.config_plugin import ConfigPlugin
import gtk
from foobnix.util.configuration import FConfiguration
class InfoPagenConfig(ConfigPlugin):
name = _("Info panel")
def __init__(self, controls):
print "Create try icon conf"
box = gtk.VBox(False, 0)
box.hide()
"""count"""
cbox = gtk.HBox(False, 0)
cbox.show()
tab_label = gtk.Label(_("Disc cover size"))
tab_label.show()
adjustment = gtk.Adjustment(value=1, lower=100, upper=500, step_incr=20, page_incr=50, page_size=0)
self.image_size_spin = gtk.SpinButton(adjustment)
self.image_size_spin.show()
cbox.pack_start(tab_label, False, False, 0)
cbox.pack_start(self.image_size_spin, False, True, 0)
"""lyric panel size"""
lbox = gtk.HBox(False, 0)
lbox.show()
lyric_label = gtk.Label(_("Lyric panel size"))
lyric_label.show()
adjustment = gtk.Adjustment(value=1, lower=100, upper=500, step_incr=20, page_incr=50, page_size=0)
self.lyric_size_spin = gtk.SpinButton(adjustment)
self.lyric_size_spin.show()
lbox.pack_start(lyric_label, False, False, 0)
lbox.pack_start(self.lyric_size_spin, False, True, 0)
box.pack_start(cbox, False, True, 0)
box.pack_start(lbox, False, True, 0)
self.widget = box
def on_load(self):
self.image_size_spin.set_value(FConfiguration().info_panel_image_size)
self.lyric_size_spin.set_value(FConfiguration().lyric_panel_image_size)
def on_save(self):
FConfiguration().lyric_panel_image_size = self.lyric_size_spin.get_value_as_int()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
import gtk
from foobnix.preferences.config_plugin import ConfigPlugin
from foobnix.util import const
from foobnix.util.configuration import FConfiguration
class TrayIconConfig(ConfigPlugin):
name = _("Tray Icon")
def __init__(self, controls):
print "Create tray icon conf"
box = gtk.VBox(False, 0)
box.hide()
self.tray_icon_button = gtk.CheckButton(label=_("Show tray icon"), use_underline=True)
self.tray_icon_button.connect("clicked", self.on_show_tray_icon)
self.tray_icon_button.show()
self.close_button = gtk.RadioButton(None, label=_("On close window - close player"))
self.close_button.show()
self.hide_button = gtk.RadioButton(self.close_button, label=_("On close window - hide player"))
self.hide_button.connect("toggled", self.on_show_tray_icon)
self.hide_button.show()
self.minimize_button = gtk.RadioButton(self.close_button, label=_("On close window - minimize player"))
self.minimize_button.show()
"""close on leave popup"""
self.tray_icon_auto_hide = gtk.CheckButton(label=_("Automatic hide tray icon popup on mouse leave"), use_underline=True)
self.tray_icon_auto_hide.show()
box.pack_start(self.tray_icon_button, False, True, 0)
box.pack_start(self.close_button, False, True, 0)
box.pack_start(self.hide_button, False, True, 0)
box.pack_start(self.minimize_button, False, True, 0)
box.pack_start(self.tray_icon_auto_hide, False, True, 0)
self.widget = box
def on_show_tray_icon(self, *args):
print "action" , self.tray_icon_button.get_active()
if not self.tray_icon_button.get_active():
self.hide_button.set_sensitive(False)
if self.hide_button.get_active():
self.minimize_button.set_active(True)
self.tray_icon.hide()
else:
self.tray_icon.show()
self.hide_button.set_sensitive(True)
def on_load(self):
self.tray_icon_button.set_active(FConfiguration().show_tray_icon)
self.tray_icon_auto_hide.set_active(FConfiguration().tray_icon_auto_hide)
if FConfiguration().on_close_window == const.ON_CLOSE_CLOSE:
self.close_button.set_active(True)
elif FConfiguration().on_close_window == const.ON_CLOSE_HIDE:
self.hide_button.set_active(True)
elif FConfiguration().on_close_window == const.ON_CLOSE_MINIMIZE:
self.minimize_button.set_active(True)
def on_save(self):
FConfiguration().show_tray_icon = self.tray_icon_button.get_active()
FConfiguration().tray_icon_auto_hide = self.tray_icon_auto_hide.get_active()
if self.close_button.get_active():
FConfiguration().on_close_window = const.ON_CLOSE_CLOSE
elif self.hide_button.get_active():
FConfiguration().on_close_window = const.ON_CLOSE_HIDE
elif self.minimize_button.get_active():
FConfiguration().on_close_window = const.ON_CLOSE_MINIMIZE
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
class ConfigPlugin():
name = 'undefined'
widget = None
enable = False
def show(self):
self.widget.show()
def hide(self):
self.widget.hide()
def on_load(self):
pass
def on_save(self):
pass
| Python |
#!/usr/bin/env python
# example packbox.py
import gtk
from foobnix.preferences.configs.music_library import MusicLibraryConfig
from foobnix.util.configuration import FConfiguration, get_version
from foobnix.preferences.configs.save_online import SaveOnlineConfig
from foobnix.preferences.configs.last_fm import LastFmConfig
from foobnix.preferences.configs.vk_conf import VkontakteConfig
from foobnix.preferences.configs.tabs import TabsConfig
from foobnix.preferences.configs.info_panel_conf import InfoPagenConfig
from foobnix.preferences.configs.network_conf import NetworkConfig
from foobnix.preferences.configs.notification_conf import NotificationConfig
from foobnix.preferences.configs.tray_icon import TrayIconConfig
from foobnix.preferences.configs.hotkey_conf import HotKeysConfig
import thread
import os
from foobnix.regui.state import LoadSave
from foobnix.regui.model.signal import FControl
from foobnix.util.fc import FC
class PreferencesWindow(FControl, LoadSave):
configs = []
POS_NAME = 0
def __init__(self, controls):
FControl.__init__(self, controls)
self.configs.append(MusicLibraryConfig(controls))
self.configs.append(SaveOnlineConfig(controls))
self.configs.append(TabsConfig(controls))
self.configs.append(LastFmConfig(controls))
self.configs.append(VkontakteConfig(controls))
self.configs.append(InfoPagenConfig(controls))
self.configs.append(TrayIconConfig(controls))
self.configs.append(NetworkConfig(controls))
self.configs.append(NotificationConfig(controls))
self.configs.append(HotKeysConfig(controls))
#self.configs.append(CategoryInfoConfig())
self.label = None
mainVBox = gtk.VBox(False, 0)
self.window = self.craete_window()
paned = gtk.HPaned()
paned.set_position(200)
paned.show()
paned.add1(self.create_left_menu())
cbox = gtk.VBox(False, 0)
cbox.show()
for plugin in self.configs:
cbox.pack_start(plugin.widget, False, True, 0)
cbox.show()
self.container = self.create_container(cbox)
paned.add2(self.container)
mainVBox.pack_start(paned, True, True, 0)
mainVBox.pack_start(self.create_save_cancel_buttons(), False, False, 0)
mainVBox.show()
self.window.add(mainVBox)
#self.show()
self.populate_config_category(self.configs[0].name)
self.on_load()
def show(self):
self.on_load()
self.window.show()
def hide(self):
print "hide preferences"
self.window.hide()
#TEMP
#gtk.main_quit()
return True
def on_load(self):
for plugin in self.configs:
plugin.on_load()
def on_save(self):
for plugin in self.configs:
plugin.on_save()
FC().save()
self.hide()
def craete_window(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("delete-event", lambda * a: self.hide())
window.connect("destroy", lambda * a: self.hide())
window.set_border_width(10)
window.set_title("Foobnix " + get_version() + " - " + _ ("Preferences"))
window.set_resizable(False)
window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
window.set_size_request(800, 500)
return window
def create_left_menu(self):
model = gtk.ListStore(str)
for plugin in self.configs:
model.append([plugin.name])
treeview = gtk.TreeView()
column_name = gtk.TreeViewColumn(_("Categories"), gtk.CellRendererText(), text=self.POS_NAME)
treeview.append_column(column_name)
treeview.set_model(model)
treeview.connect("cursor-changed", self.on_change_category)
treeview.show()
return treeview
def populate_config_category(self, name):
for plugin in self.configs:
if plugin.name == name:
plugin.show()
self.update_label(name)
else:
plugin.hide()
def on_change_category(self, w):
selection = w.get_selection()
model, selected = selection.get_selected()
if selected:
name = model.get_value(selected, self.POS_NAME)
self.populate_config_category(name)
def create_save_cancel_buttons(self):
box = gtk.HBox(False, 0)
box.show()
button_restore = gtk.Button(_("Restore Defaults"))
button_restore.connect("clicked", lambda * a:self.restore_defaults())
button_restore.show()
button_save = gtk.Button(_("Save"))
button_save.set_size_request(100, -1)
button_save.connect("clicked", lambda * a:self.on_save())
button_save.show()
button_cancel = gtk.Button(_("Cancel"))
button_cancel.set_size_request(100, -1)
button_cancel.connect("clicked", lambda * a:self.hide())
button_cancel.show()
empty = gtk.Label("")
empty.show()
box.pack_start(button_restore, False, True, 0)
box.pack_start(empty, True, True, 0)
box.pack_start(button_save, False, True, 0)
box.pack_start(button_cancel, False, True, 0)
return box
def restore_defaults(self):
print "restore defaults"
gtk.main_quit()
FConfiguration().remove_cfg_file()
thread.start_new_thread(os.system, ("foobnix",))
def update_label(self, title):
self.label.set_markup('<b><i><span size="x-large" >' + title + '</span></i></b>');
def create_container(self, widget):
box = gtk.VBox(False, 0)
box.show()
self.label = gtk.Label()
self.label.show()
separator = gtk.HSeparator()
separator.show()
box.pack_start(self.label, False, True, 0)
box.pack_start(separator, False, True, 0)
box.pack_start(widget, False, True, 0)
return box
def main():
gtk.main()
return 0
if __name__ == "__main__":
w = PreferencesWindow(None, None)
w.show()
main()
| Python |
'''
Created on 01.06.2010
@author: ivan
'''
from foobnix.online.google.search import GoogleSearch
import time
from foobnix.util import LOG
def googleHelp(query):
LOG.info("Not Found, wait for results from google ...")
results = []
ask = query.encode('utf-8')
LOG.info(ask)
gs = GoogleSearch(ask, True, True)
LOG.info(gs)
gs.results_per_page = 10
results = gs.get_results()
LOG.info(results)
for res in results:
result = res.title.encode('utf8')
time.sleep(0.05)
results.append(str(result))
#LOG.info(googleHelp("madoonna 1")
def search():
LOG.info("Begin")
gs = GoogleSearch("quick and dirty")
gs.results_per_page = 5
results = gs.get_results()
LOG.info(results)
for res in results:
LOG.info(res.title.encode("utf8"))
LOG.info(res.desc.encode("utf8"))
LOG.info(res.url.encode("utf8"))
search()
| Python |
'''
Created on Jun 10, 2010
@author: ivan
'''
from foobnix.util.configuration import FConfiguration
from foobnix.util import LOG
import os
import urllib
import thread
from foobnix.online.song_resource import update_song_path
from mutagen.id3 import ID3NoHeaderError, ID3, TIT2, COMM, TPE1, TENC, TDRC, \
TALB
def dowload_song_thread(song):
thread.start_new_thread(download_song, (song,))
def save_song_thread(songs):
thread.start_new_thread(save_song, (songs,))
#save_song(songs)
def save_as_song_thread(songs, path):
LOG.debug("Begin download songs list", songs)
thread.start_new_thread(save_as_song, (songs, path,))
def save_song(songs):
for song in songs:
update_song_path(song)
file = get_file_store_path(song)
LOG.debug("Download song start", file)
if not os.path.exists(file + ".tmp") and song.path:
LOG.debug("Song PATH", song.path)
urllib.urlretrieve(song.path, file + ".tmp")
os.rename(file + ".tmp", file)
update_id3_tags(song, file)
LOG.debug("Download song finished", file)
else:
LOG.debug("Found file already dowloaded", file)
def save_as_song(songs, path):
for song in songs:
update_song_path(song)
if song.name.endswith(".mp3"):
file = path + "/" + song.name
else:
file = path + "/" + song.name + ".mp3"
LOG.debug("Download song start", file)
if not os.path.exists(file + ".tmp") and song.path:
urllib.urlretrieve(song.path, file + ".tmp")
os.rename(file + ".tmp", file)
update_id3_tags(song, file)
LOG.debug("Download song finished", file)
else:
LOG.debug("Found file already dowloaded", file)
def update_id3_tags(song, path):
if os.path.exists(str(path)):
LOG.debug("Begin update", path)
#audio = EasyID3(str(path))
try:
tags = ID3(path)
except ID3NoHeaderError:
LOG.info("Adding ID3 header;")
tags = ID3()
tags["TIT2"] = TIT2(encoding=3, text=song.getTitle())
tags["COMM"] = COMM(encoding=3, lang="eng", desc='desc', text='Grab by www.foobnix.com')
tags["TENC"] = TENC(encoding=3, text='www.foobnix.com')
tags["TPE1"] = TPE1(encoding=3, text=song.getArtist())
tags["TDRC"] = TDRC(encoding=3, text=song.year)
tags["TALB"] = TALB(encoding=3, text=song.album)
try:
tags.save(path)
except:
LOG.error("Tags can't be updated")
pass
LOG.debug("ID3 TAGS updated")
else:
LOG.error("ID3 FILE not found", path)
"""Dowload song proccess"""
def download_song(song):
if not FConfiguration().is_save_online:
LOG.debug("Saving (Caching) not enable")
return None
save_song([song])
pass
"""Determine file place"""
def get_file_store_path(song):
dir = FConfiguration().onlineMusicPath
if song.getArtist():
dir = dir + "/" + song.getArtist()
make_dirs(dir)
song = dir + "/" + song.name + ".mp3"
return song
def make_dirs(path):
if not os.path.isdir(path):
os.makedirs(path)
| Python |
# -*- coding: utf-8 -*-
#TODO: This file is under heavy refactoring, don't touch anything you think is wrong
'''
Created on Mar 16, 2010
@author: ivan
'''
import os
import gtk
from gobject import GObject #@UnresolvedImport
from foobnix.directory.directory_controller import DirectoryCntr
from foobnix.model.entity import CommonBean
from foobnix.online.information_controller import InformationController
from foobnix.online.online_model import OnlineListModel
from foobnix.online.search_panel import SearchPanel
from foobnix.player.player_controller import PlayerController
from foobnix.util import LOG, const
from foobnix.util.configuration import FConfiguration
from foobnix.util.mouse_utils import is_double_click, is_rigth_click, \
is_left_click
from foobnix.online.google_utils import google_search_resutls
from foobnix.online.dowload_util import get_file_store_path, \
save_as_song_thread, save_song_thread
from foobnix.helpers.my_widgets import tab_close_button, tab_close_label
from foobnix.online.song_resource import update_song_path
from foobnix.cue.cue_reader import CueReader
from foobnix.helpers.menu import Popup
from foobnix.util.file_utils import get_file_extenstion
import urllib
TARGET_TYPE_URI_LIST = 80
dnd_list = [ ('text/uri-list', 0, TARGET_TYPE_URI_LIST) ]
class OnlineListCntr(GObject):
def __init__(self, gxMain, playerCntr, last_fm_connector):
self.gx_main = gxMain
self.directoryCntr = None
self.playerCntr = playerCntr
self.current_list_model = None
self.last_fm_connector = last_fm_connector
self.search_panel = SearchPanel(gxMain, last_fm_connector)
self.count = 0
self.index = 0
self.online_notebook = gxMain.get_widget("online_notebook")
shuffle_menu = gxMain.get_widget("shuffle_menu")
shuffle_menu.connect("activate", self.shuffle)
self.online_notebook.connect('drag-data-received', self.on_drag_data_received)
self.online_notebook.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
dnd_list, gtk.gdk.ACTION_MOVE | gtk.gdk.ACTION_COPY)
add_file_menu = gxMain.get_widget("add-file")
add_file_menu.connect("activate", self.on_add_file)
add_folder_menu = gxMain.get_widget("add-folder")
add_folder_menu.connect("activate", self.on_add_folder)
self.tab_labes = []
self.tab_vboxes = []
self.tab_hboxes = []
self.default_angel = 90
self.last_notebook_page = ""
self.last_notebook_beans = []
def get_file_path_from_dnd_dropped_uri(self, uri):
# get the path to file
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
path = urllib.url2pathname(path) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL
return path
def on_drag_data_received(self, widget, context, x, y, selection, target_type, timestamp):
TARGET_TYPE_URI_LIST = 80
dnd_list = [ ('text/uri-list', 0, TARGET_TYPE_URI_LIST) ]
if target_type == TARGET_TYPE_URI_LIST:
uri = selection.data.strip('\r\n\x00')
print 'uri', uri
uri_splitted = uri.split() # we may have more than one file dropped
paths = []
for uri in uri_splitted:
path = self.get_file_path_from_dnd_dropped_uri(uri)
paths.append(path)
self.on_play_argumens(paths)
def on_play_argumens(self, args):
if not args:
print "no args"
return None
dirs = []
files = []
for arg in args:
LOG.info("Arguments", arg)
if os.path.isdir(arg):
dirs.append(arg)
elif os.path.isfile(arg) and get_file_extenstion(arg) in FConfiguration().supportTypes:
files.append(arg)
if dirs:
self.populate_from_dirs(dirs)
else:
self.populate_from_files(files)
def update_label_angel(self, angle):
for label in self.tab_labes:
label.set_angle(angle)
def set_tab_left(self):
LOG.info("Set tabs Left")
self.online_notebook.set_tab_pos(gtk.POS_LEFT)
self.update_label_angel(90)
self.default_angel = 90
self.online_notebook.set_show_tabs(True)
FConfiguration().tab_position = "left"
for box in self.tab_hboxes:
box.hide()
for box in self.tab_vboxes:
box.show()
def set_tab_top(self):
LOG.info("Set tabs top")
self.online_notebook.set_tab_pos(gtk.POS_TOP)
self.update_label_angel(0)
self.default_angel = 0
self.online_notebook.set_show_tabs(True)
FConfiguration().tab_position = "top"
for box in self.tab_hboxes:
box.show()
for box in self.tab_vboxes:
box.hide()
def set_tab_no(self):
LOG.info("Set tabs no")
self.online_notebook.set_show_tabs(False)
FConfiguration().tab_position = "no"
for box in self.tab_hboxes:
box.hide()
for box in self.tab_vboxes:
box.hide()
def on_add_file(self, *a):
chooser = gtk.FileChooserDialog(title=_("Choose file to open"), action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
chooser.set_select_multiple(True)
if FConfiguration().last_dir:
chooser.set_current_folder(FConfiguration().last_dir)
response = chooser.run()
if response == gtk.RESPONSE_OK:
paths = chooser.get_filenames()
self.populate_from_files(paths)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
print "add file"
def populate_from_files(self, paths):
if not paths:
return None
path = paths[0]
list = paths[0].split("/")
FConfiguration().last_dir = path[:path.rfind("/")]
self.append_notebook_page(list[len(list) - 2])
beans = []
for path in paths:
bean = self.directoryCntr.get_common_bean_by_file(path)
beans.append(bean)
if beans:
self.append_and_play(beans)
else:
self.append([self.SearchCriteriaBeen(_("Nothing found to play in the file(s)") + paths[0])])
def populate_from_dirs(self, paths):
if not paths :
return None
path = paths[0]
list = path.split("/")
FConfiguration().last_dir = path[:path.rfind("/")]
self.append_notebook_page(list[len(list) - 1])
all_beans = []
for path in paths:
if path == "/":
LOG.info("Skip root folder")
continue;
beans = self.directoryCntr.get_common_beans_by_folder(path)
for bean in beans:
all_beans.append(bean)
if all_beans:
self.append_and_play(all_beans)
else:
self.append([self.SearchCriteriaBeen(_("Nothing found to play in the folder(s)") + paths[0])])
def on_add_folder(self, *a):
chooser = gtk.FileChooserDialog(title=_("Choose directory with music"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
chooser.set_select_multiple(True)
if FConfiguration().last_dir:
chooser.set_current_folder(FConfiguration().last_dir)
response = chooser.run()
if response == gtk.RESPONSE_OK:
paths = chooser.get_filenames()
self.populate_from_dirs(paths)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
print "add folder"
def register_directory_cntr(self, directoryCntr):
self.directoryCntr = directoryCntr
self.info = InformationController(self.gx_main, self.playerCntr, directoryCntr, self.search_panel, self, self.last_fm_connector)
def none(self, *a):
return False
def create_notebook_tab(self):
treeview = gtk.TreeView()
treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
treeview.set_rubber_banding(True)
treeview.set_reorderable(True)
model = OnlineListModel(treeview)
self.current_list_model = model
treeview.connect("drag-end", self.on_drag_end)
treeview.connect("button-press-event", self.onPlaySong, model)
treeview.connect("key-press-event", self.on_song_key_press, model)
treeview.show()
window = gtk.ScrolledWindow()
window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
window.add_with_viewport(treeview)
window.show()
return window
def append_notebook_page(self, name):
self.last_notebook_page = name
LOG.info("append new tab")
if name and len(name) > FConfiguration().len_of_tab:
name = name[:FConfiguration().len_of_tab]
tab_content = self.create_notebook_tab()
def label():
"""label"""
label = gtk.Label(name + " ")
label.show()
label.set_angle(self.default_angel)
self.tab_labes.append(label)
#event = gtk.EventBox()
#event.show()
#event.add(label)
#return event
return label
def button():
print "ELEMENT", FConfiguration().tab_close_element
if FConfiguration().tab_close_element == "button":
return tab_close_button(func=self.on_delete_tab, arg=tab_content)
else:
return tab_close_label(func=self.on_delete_tab, arg=tab_content, angel=self.default_angel)
"""container Vertical Tab"""
vbox = gtk.VBox(False, 0)
if self.default_angel == 90:
vbox.show()
vbox.pack_start(button(), False, False, 0)
vbox.pack_start(label(), False, False, 0)
self.tab_vboxes.append(vbox)
"""container Horizontal Tab"""
hbox = gtk.HBox(False, 0)
if self.default_angel == 0:
hbox.show()
hbox.pack_start(label(), False, False, 0)
hbox.pack_start(button(), False, False, 0)
self.tab_hboxes.append(hbox)
#hbox.set_size_request(-1, 16)
"""container BOTH"""
both = gtk.HBox(False, 0)
both.show()
both.pack_start(vbox, False, False, 0)
both.pack_start(hbox, False, False, 0)
"""append tab"""
self.online_notebook.prepend_page(tab_content, both)
self.online_notebook.set_current_page(0)
if self.online_notebook.get_n_pages() > FConfiguration().count_of_tabs:
self.online_notebook.remove_page(self.online_notebook.get_n_pages() - 1)
def on_tab_click(self, w, e):
print w, e
""" double left or whell pressed"""
if is_left_click(e):
LOG.info("Close Current TAB")
self.delete_tab()
if is_rigth_click(e):
menu = Popup()
menu.add_item(_("Close"), gtk.STOCK_DELETE, self.delete_tab, None)
menu.show(e)
def on_delete_tab(self, widget, event, child):
if event.type == gtk.gdk.BUTTON_PRESS:
print "Button press event", child
n = self.online_notebook.page_num(child)
#self.online_notebook.set_current_page(n)
self.delete_tab(n)
# self.delete_tab(tab_num)
def delete_tab(self, page=None):
if not page:
LOG.info("Remove current page")
page = self.online_notebook.get_current_page()
self.online_notebook.remove_page(page)
def add_selected_to_playlist(self):
selected = self.current_list_model.get_selected_bean()
LOG.info("SELECTED", selected)
self.directoryCntr.set_active_view(DirectoryCntr.VIEW_VIRTUAL_LISTS)
if selected.type == CommonBean.TYPE_MUSIC_URL:
selected.parent = None
self.directoryCntr.append_virtual([selected])
elif selected.type in [CommonBean.TYPE_FOLDER, CommonBean.TYPE_GOOGLE_HELP, CommonBean.TYPE_RADIO_URL]:
selected.type = CommonBean.TYPE_FOLDER
results = []
for i in xrange(self.current_list_model.get_size()):
searchBean = self.current_list_model.getBeenByPosition(i)
#LOG.info("Search", searchBean
if str(searchBean.name) == str(selected.name):
searchBean.parent = None
results.append(searchBean)
elif str(searchBean.parent) == str(selected.name):
results.append(searchBean)
else:
LOG.info(str(searchBean.parent) + " != " + str(selected.name))
self.directoryCntr.append_virtual(results)
LOG.info("drug")
def on_drag_end(self, *ars):
self.add_selected_to_playlist()
def show_searching(self, sender, query):
self.append_notebook_page(query)
self.append([self.SearchingCriteriaBean(query)])
pass
def show_results(self, sender, query, beans, criteria=True):
#time.sleep(0.1)
#self.online_notebook.remove_page(0)
#self.append([self.SearchingCriteriaBean(query)])
self.append_notebook_page(query)
#self.append_notebook_page(query)
#time.sleep(0.1)
#self.current_list_model.clear()
LOG.debug("Showing search results")
if beans:
if criteria:
self.append([self.SearchCriteriaBeen(query)])
self.append(beans)
else:
LOG.debug("Nothing found get try google suggests")
self.google_suggests(query)
def google_suggests(self, query):
self.append([self.TextBeen(query + _(" not found on last.fm, wait for google suggests ..."))])
suggests = google_search_resutls(query, 15)
if suggests:
for line in suggests:
self.append([self.TextBeen(line, color="YELLOW", type=CommonBean.TYPE_GOOGLE_HELP)])
else :
self.append([self.TextBeen(_("Google not found suggests"))])
def TextBeen(self, query, color="RED", type=CommonBean.TYPE_FOLDER):
return CommonBean(name=query, path=None, color=color, type=type)
def SearchCriteriaBeen(self, name):
return CommonBean(name=name, path=None, color="#4DCC33", type=CommonBean.TYPE_FOLDER)
def SearchingCriteriaBean(self, name):
return CommonBean(name=_("Searching: ") + name + _(" ... please wait a second"), path=None, color="GREEN", type=CommonBean.TYPE_FOLDER)
def _populate_model(self, beans):
normilized = self.current_list_model.get_all_beans()
"""first add cue files"""
#for i in xrange(len(beans)):
# beans[i].tracknumber = i + 1
for bean in beans:
LOG.info("append", bean, bean.path)
if bean.path and bean.path.lower().endswith(".cue"):
cues = CueReader(bean.path).get_common_beans()
for cue in cues:
self.current_list_model.append(cue)
normilized.append(cue)
"""end big file to the end"""
for bean in beans:
bean.getMp3TagsName()
#if id3:
#bean.id3, bean.name, bean.info = bean.name, id3, id3.info
if not bean.path or (bean.path and not bean.path.lower().endswith(".cue")):
self.current_list_model.append(bean)
normilized.append(bean)
self.last_notebook_beans = normilized
return normilized
def append(self, beans):
self._populate_model(beans)
self.current_list_model.repopulate(-1)
def append_and_play(self, beans, index=0):
if not index:
index = 0
beans = self._populate_model(beans)
if not beans:
return None
self.index = index
self.current_list_model.repopulate(self.index)
song = beans[self.index]
LOG.info("PLAY", song)
self.playerCntr.playSong(song)
def on_play_selected(self, similar_songs_model):
playlistBean = similar_songs_model.get_selected_bean()
self.index = similar_songs_model.get_selected_index()
if not playlistBean:
return None
LOG.info("play", playlistBean)
LOG.info("type", playlistBean.type)
if playlistBean.type == CommonBean.TYPE_MUSIC_URL:
self.playBean(playlistBean)
elif playlistBean.type == CommonBean.TYPE_GOOGLE_HELP:
self.search_panel.set_text(playlistBean.name)
else:
self.playBean(playlistBean)
def show_save_as_dialog(self, songs):
LOG.debug("Show Save As Song dialog", songs)
chooser = gtk.FileChooserDialog(title=_("Choose directory to save song"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
response = chooser.run()
if response == gtk.RESPONSE_OK:
path = chooser.get_filename()
save_as_song_thread(songs, path)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
def show_info(self, songs):
if not songs:
return None
result = ""
for song in songs:
result += song.getArtist() + " - " + song.getTitle() + "\n"
md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,
gtk.BUTTONS_CLOSE, result)
md.run()
md.destroy()
def changed(self, a, type=None):
if self.paths:
a.select_range(self.paths[0], self.paths[len(self.paths) - 1])
def on_song_key_press(self, w,e, model):
print w,e, e.keyval
if gtk.gdk.keyval_name(e.keyval) == 'Return':
self.on_play_selected(model);
if gtk.gdk.keyval_name(e.keyval) == 'Delete':
model.remove_selected()
def onPlaySong(self, w, e, similar_songs_model):
self.current_list_model = similar_songs_model
songs = similar_songs_model.get_all_selected_beans()
self.index = similar_songs_model.get_selected_index()
#selected rows
treeselection = similar_songs_model.widget.get_selection()
model, self.paths = treeselection.get_selected_rows()
#LOG.debug("Seletected index", self.index, songs)
if is_left_click(e):
self.paths = None
LOG.debug("SAVE SELECTED", self.paths)
elif is_double_click(e):
self.paths = None
self.on_play_selected(similar_songs_model);
elif is_rigth_click(e):
treeselection.connect('changed', self.changed, True)
menu = Popup()
menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.on_play_selected, similar_songs_model)
menu.add_item(_("Save"), gtk.STOCK_SAVE, save_song_thread, songs)
menu.add_item(_("Save as"), gtk.STOCK_SAVE_AS, self.show_save_as_dialog, songs)
menu.add_item(_("Add to virtual"), gtk.STOCK_ADD, self.add_selected_to_playlist)
menu.add_item(_("Delete from list"), gtk.STOCK_REMOVE, similar_songs_model.remove_selected)
menu.add_item(_("Show info"), gtk.STOCK_INFO, self.show_info, songs)
menu.add_item(_("I love it"), gtk.STOCK_OK, self.love_track, songs)
menu.show(e)
treeselection.select_all()
def love_track(self,songs):
for song in songs:
LOG.debug("I LOVE IT ", song.getArtist(),song.getTitle())
track = self.last_fm_connector.network.get_track(song.getArtist(),song.getTitle())
if track:
track.love()
LOG.debug("I LOVE IT SUCCESS")
def playBean(self, playlistBean):
if playlistBean.type in [CommonBean.TYPE_MUSIC_URL, CommonBean.TYPE_MUSIC_FILE]:
self.setSongResource(playlistBean)
LOG.info("Song source path", playlistBean.path)
if not playlistBean.path:
self.count += 1
LOG.info(self.count)
playlistBean.setIconErorr()
if self.count < 5 :
return self.playBean(self.getNextSong())
return
self.playerCntr.set_mode(PlayerController.MODE_ONLINE_LIST)
self.playerCntr.playSong(playlistBean)
self.current_list_model.repopulate(self.index)
def setSongResource(self, playlistBean, update_song_info=True):
if not playlistBean.path:
if playlistBean.type == CommonBean.TYPE_MUSIC_URL:
file = get_file_store_path(playlistBean)
if os.path.isfile(file) and os.path.getsize(file) > 1:
LOG.info("Find file dowloaded")
playlistBean.path = file
playlistBean.type = CommonBean.TYPE_MUSIC_FILE
return True
else:
LOG.info("FILE NOT FOUND IN SYSTEM")
#Seach by vk engine
update_song_path(playlistBean)
#if update_song_info:
"""retrive images and other info"""
#self.info.show_song_info(playlistBean)
def nextBean(self):
if self.index <= 0:
self.index = 0
if not self.current_list_model:
return None
if FConfiguration().play_looping == const.LOPPING_SINGLE:
return self.current_list_model.getBeenByPosition(self.index)
if FConfiguration().play_ordering == const.ORDER_RANDOM:
return self.current_list_model.get_random_bean()
self.index += 1
if self.index >= self.current_list_model.get_size():
self.index = 0
if FConfiguration().play_looping == const.LOPPING_DONT_LOOP:
self.index = self.current_list_model.get_size()
return None
LOG.info("PLAY BEAN", self.index)
return self.current_list_model.getBeenByPosition(self.index)
def prevBean(self):
if not self.current_list_model:
return None
if FConfiguration().play_looping == const.LOPPING_SINGLE:
return self.current_list_model.getBeenByPosition(self.index)
if FConfiguration().play_ordering == const.ORDER_RANDOM:
return self.current_list_model.get_random_bean()
self.index -= 1
list = self.current_list_model.get_all_beans()
if self.index <= 0:
self.index = self.current_list_model.get_size()
playlistBean = self.current_list_model.getBeenByPosition(self.index)
return playlistBean
#TODO: This file is under heavy refactoring, don't touch anything you think is wrong
def getNextSong(self):
currentSong = self.nextBean()
if(currentSong.type == CommonBean.TYPE_FOLDER):
currentSong = self.nextBean()
self.setSongResource(currentSong)
LOG.info("PATH", currentSong.path)
self.current_list_model.repopulate(currentSong.index);
return currentSong
def shuffle(self, *a):
LOG.info("Shuffle list")
self.current_list_model.repopulate(self.index, True);
def setState(self, state):
#TODO
pass
def getState(self):
#TODO
pass
def getPrevSong(self):
playlistBean = self.prevBean()
if(playlistBean.type == CommonBean.TYPE_FOLDER):
self.getPrevSong()
self.setSongResource(playlistBean)
self.current_list_model.repopulate(playlistBean.index);
return playlistBean
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-sponsored-links-search/
#
# Code is licensed under MIT license.
#
import re
import urllib
import random
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
#
# TODO: join GoogleSearch and SponsoredLinks classes under a single base class
#
class SLError(Exception):
""" Sponsored Links Error """
pass
class SLParseError(Exception):
"""
Parse error in Google results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
GET_ALL_SLEEP_FUNCTION = object()
class SponsoredLink(object):
""" a single sponsored link """
def __init__(self, title, url, display_url, desc):
self.title = title
self.url = url
self.display_url = display_url
self.desc = desc
class SponsoredLinks(object):
SEARCH_URL_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&btnG=Search+Sponsored+Links&hl=en"
NEXT_PAGE_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&sa=N&start=%(start)d&hl=en"
SEARCH_URL_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&btnG=Search+Sponsored+Links&hl=en"
NEXT_PAGE_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&sa=N&start=%(start)d&hl=en"
def __init__(self, query, random_agent=False, debug=False):
self.query = query
self.debug = debug
self.browser = Browser(debug=debug)
self._page = 0
self.eor = False
self.results_info = None
self._results_per_page = 10
if random_agent:
self.browser.set_random_user_agent()
@property
def num_results(self):
if not self.results_info:
page = self._get_results_page()
self.results_info = self._extract_info(page)
if self.results_info['total'] == 0:
self.eor = True
return self.results_info['total']
def _get_results_per_page(self):
return self._results_per_page
def _set_results_par_page(self, rpp):
self._results_per_page = rpp
results_per_page = property(_get_results_per_page, _set_results_par_page)
def get_results(self):
if self.eor:
return []
page = self._get_results_page()
info = self._extract_info(page)
if self.results_info is None:
self.results_info = info
if info['to'] == info['total']:
self.eor = True
results = self._extract_results(page)
if not results:
self.eor = True
return []
self._page += 1
return results
def _get_all_results_sleep_fn(self):
return random.random()*5 + 1 # sleep from 1 - 6 seconds
def get_all_results(self, sleep_function=None):
if sleep_function is GET_ALL_SLEEP_FUNCTION:
sleep_function = self._get_all_results_sleep_fn
if sleep_function is None:
sleep_function = lambda: None
ret_results = []
while True:
res = self.get_results()
if not res:
return ret_results
ret_results.extend(res)
return ret_results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _extract_info(self, soup):
empty_info = { 'from': 0, 'to': 0, 'total': 0 }
stats_span = soup.find('span', id='stats')
if not stats_span:
return empty_info
txt = ''.join(stats_span.findAll(text=True))
txt = txt.replace(',', '').replace(" ", ' ')
matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt)
if not matches:
return empty_info
return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))}
def _get_results_page(self):
if self._page == 0:
if self._results_per_page == 10:
url = SponsoredLinks.SEARCH_URL_0
else:
url = SponsoredLinks.SEARCH_URL_1
else:
if self._results_per_page == 10:
url = SponsoredLinks.NEXT_PAGE_0
else:
url = SponsoredLinks.NEXT_PAGE_1
safe_url = url % { 'query': urllib.quote_plus(self.query),
'start': self._page * self._results_per_page,
'num': self._results_per_page }
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise SLError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_results(self, soup):
results = soup.findAll('div', {'class': 'g'})
ret_res = []
for result in results:
eres = self._extract_result(result)
if eres:
ret_res.append(eres)
return ret_res
def _extract_result(self, result):
title, url = self._extract_title_url(result)
display_url = self._extract_display_url(result) # Warning: removes 'cite' from the result
desc = self._extract_description(result)
if not title or not url or not display_url or not desc:
return None
return SponsoredLink(title, url, display_url, desc)
def _extract_title_url(self, result):
title_a = result.find('a')
if not title_a:
self._maybe_raise(SLParseError, "Title tag in sponsored link was not found", result)
return None, None
title = ''.join(title_a.findAll(text=True))
title = self._html_unescape(title)
url = title_a['href']
match = re.search(r'q=(http[^&]+)&', url)
if not match:
self._maybe_raise(SLParseError, "URL inside a sponsored link was not found", result)
return None, None
url = urllib.unquote(match.group(1))
return title, url
def _extract_display_url(self, result):
cite = result.find('cite')
if not cite:
self._maybe_raise(SLParseError, "<cite> not found inside result", result)
return None
return ''.join(cite.findAll(text=True))
def _extract_description(self, result):
cite = result.find('cite')
if not cite:
return None
cite.extract()
desc_div = result.find('div', {'class': 'line23'})
if not desc_div:
self._maybe_raise(ParseError, "Description tag not found in sponsored link", result)
return None
desc_strs = desc_div.findAll(text=True)[0:-1]
desc = ''.join(desc_strs)
desc = desc.replace("\n", " ")
desc = desc.replace(" ", " ")
return self._html_unescape(desc)
def _html_unescape(self, str):
def entity_replacer(m):
entity = m.group(1)
if entity in name2codepoint:
return unichr(name2codepoint[entity])
else:
return m.group(0)
def ascii_replacer(m):
cp = int(m.group(1))
if cp <= 255:
return unichr(cp)
else:
return m.group(0)
s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U)
return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Code is licensed under MIT license.
#
import re
import urllib
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
class SearchError(Exception):
"""
Base class for Google Search exceptions.
"""
pass
class ParseError(SearchError):
"""
Parse error in Google results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
class SearchResult:
def __init__(self, title, url, desc):
self.title = title
self.url = url
self.desc = desc
def __str__(self):
return 'Google Search Result: "%s"' % self.title
class GoogleSearch(object):
SEARCH_URL_0 = "http://www.google.com/search?hl=en&q=%(query)s&btnG=Google+Search"
NEXT_PAGE_0 = "http://www.google.com/search?hl=en&q=%(query)s&start=%(start)d"
SEARCH_URL_1 = "http://www.google.com/search?hl=en&q=%(query)s&num=%(num)d&btnG=Google+Search"
NEXT_PAGE_1 = "http://www.google.com/search?hl=en&q=%(query)s&num=%(num)d&start=%(start)d"
def __init__(self, query, random_agent=False, debug=False):
self.query = query
self.debug = debug
self.browser = Browser(debug=debug)
self.results_info = None
self.eor = False # end of results
self._page = 0
self._results_per_page = 10
self._last_from = 0
if random_agent:
self.browser.set_random_user_agent()
@property
def num_results(self):
if not self.results_info:
page = self._get_results_page()
self.results_info = self._extract_info(page)
if self.results_info['total'] == 0:
self.eor = True
return self.results_info['total']
def _get_page(self):
return self._page
def _set_page(self, page):
self._page = page
page = property(_get_page, _set_page)
def _get_results_per_page(self):
return self._results_per_page
def _set_results_par_page(self, rpp):
self._results_per_page = rpp
results_per_page = property(_get_results_per_page, _set_results_par_page)
def get_results(self):
""" Gets a page of results """
#if self.eor:
# return []
page = self._get_results_page()
search_info = self._extract_info(page)
#if not self.results_info:
# self.results_info = search_info
# if self.num_results == 0:
# self.eor = True
# return []
results = self._extract_results(page)
return results
if not results:
self.eor = True
return []
if self._page > 0 and search_info['from'] == self._last_from:
self.eor = True
return []
if search_info['to'] == search_info['total']:
self.eor = True
self._page += 1
self._last_from = search_info['from']
return results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _get_results_page(self):
if self._page == 0:
if self._results_per_page == 10:
url = GoogleSearch.SEARCH_URL_0
else:
url = GoogleSearch.SEARCH_URL_1
else:
if self._results_per_page == 10:
url = GoogleSearch.NEXT_PAGE_0
else:
url = GoogleSearch.NEXT_PAGE_1
safe_url = url % { 'query': urllib.quote_plus(self.query),
'start': self._page * self._results_per_page,
'num': self._results_per_page }
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise SearchError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_info(self, soup):
empty_info = {'from': 0, 'to': 0, 'total': 0}
div_ssb = soup.find('div', id='ssb')
if not div_ssb:
self._maybe_raise(ParseError, "Div with number of results was not found on Google search page", soup)
return empty_info
p = div_ssb.find('p')
if not p:
self._maybe_raise(ParseError, """<p> tag within <div id="ssb"> was not found on Google search page""", soup)
return empty_info
txt = ''.join(p.findAll(text=True))
txt = txt.replace(',', '')
matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt, re.U)
if not matches:
return empty_info
return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))}
def _extract_results(self, soup):
results = soup.findAll('li', {'class': 'g'})
ret_res = []
for result in results:
eres = self._extract_result(result)
if eres:
ret_res.append(eres)
return ret_res
def _extract_result(self, result):
title, url = self._extract_title_url(result)
desc = self._extract_description(result)
if not title or not url or not desc:
return None
return SearchResult(title, url, desc)
def _extract_title_url(self, result):
#title_a = result.find('a', {'class': re.compile(r'\bl\b')})
title_a = result.find('a')
if not title_a:
self._maybe_raise(ParseError, "Title tag in Google search result was not found", result)
return None, None
title = ''.join(title_a.findAll(text=True))
title = self._html_unescape(title)
url = title_a['href']
match = re.match(r'/url\?q=(http[^&]+)&', url)
if match:
url = urllib.unquote(match.group(1))
return title, url
def _extract_description(self, result):
desc_div = result.find('div', {'class': re.compile(r'\bs\b')})
if not desc_div:
self._maybe_raise(ParseError, "Description tag in Google search result was not found", result)
return None
desc_strs = []
def looper(tag):
if not tag: return
for t in tag:
try:
if t.name == 'br': break
except AttributeError:
pass
try:
desc_strs.append(t.string)
except AttributeError:
desc_strs.append(t)
looper(desc_div)
looper(desc_div.find('wbr')) # BeautifulSoup does not self-close <wbr>
desc = ''.join(s for s in desc_strs if s)
return self._html_unescape(desc)
def _html_unescape(self, str):
def entity_replacer(m):
entity = m.group(1)
if entity in name2codepoint:
return unichr(name2codepoint[entity])
else:
return m.group(0)
def ascii_replacer(m):
cp = int(m.group(1))
if cp <= 255:
return unichr(cp)
else:
return m.group(0)
s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U)
return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-sponsored-links-search/
#
# Code is licensed under MIT license.
#
import re
import urllib
import random
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
#
# TODO: join GoogleSearch and SponsoredLinks classes under a single base class
#
class SLError(Exception):
""" Sponsored Links Error """
pass
class SLParseError(Exception):
"""
Parse error in Google results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
GET_ALL_SLEEP_FUNCTION = object()
class SponsoredLink(object):
""" a single sponsored link """
def __init__(self, title, url, display_url, desc):
self.title = title
self.url = url
self.display_url = display_url
self.desc = desc
class SponsoredLinks(object):
SEARCH_URL_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&btnG=Search+Sponsored+Links&hl=en"
NEXT_PAGE_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&sa=N&start=%(start)d&hl=en"
SEARCH_URL_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&btnG=Search+Sponsored+Links&hl=en"
NEXT_PAGE_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&sa=N&start=%(start)d&hl=en"
def __init__(self, query, random_agent=False, debug=False):
self.query = query
self.debug = debug
self.browser = Browser(debug=debug)
self._page = 0
self.eor = False
self.results_info = None
self._results_per_page = 10
if random_agent:
self.browser.set_random_user_agent()
@property
def num_results(self):
if not self.results_info:
page = self._get_results_page()
self.results_info = self._extract_info(page)
if self.results_info['total'] == 0:
self.eor = True
return self.results_info['total']
def _get_results_per_page(self):
return self._results_per_page
def _set_results_par_page(self, rpp):
self._results_per_page = rpp
results_per_page = property(_get_results_per_page, _set_results_par_page)
def get_results(self):
if self.eor:
return []
page = self._get_results_page()
info = self._extract_info(page)
if self.results_info is None:
self.results_info = info
if info['to'] == info['total']:
self.eor = True
results = self._extract_results(page)
if not results:
self.eor = True
return []
self._page += 1
return results
def _get_all_results_sleep_fn(self):
return random.random()*5 + 1 # sleep from 1 - 6 seconds
def get_all_results(self, sleep_function=None):
if sleep_function is GET_ALL_SLEEP_FUNCTION:
sleep_function = self._get_all_results_sleep_fn
if sleep_function is None:
sleep_function = lambda: None
ret_results = []
while True:
res = self.get_results()
if not res:
return ret_results
ret_results.extend(res)
return ret_results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _extract_info(self, soup):
empty_info = { 'from': 0, 'to': 0, 'total': 0 }
stats_span = soup.find('span', id='stats')
if not stats_span:
return empty_info
txt = ''.join(stats_span.findAll(text=True))
txt = txt.replace(',', '').replace(" ", ' ')
matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt)
if not matches:
return empty_info
return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))}
def _get_results_page(self):
if self._page == 0:
if self._results_per_page == 10:
url = SponsoredLinks.SEARCH_URL_0
else:
url = SponsoredLinks.SEARCH_URL_1
else:
if self._results_per_page == 10:
url = SponsoredLinks.NEXT_PAGE_0
else:
url = SponsoredLinks.NEXT_PAGE_1
safe_url = url % { 'query': urllib.quote_plus(self.query),
'start': self._page * self._results_per_page,
'num': self._results_per_page }
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise SLError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_results(self, soup):
results = soup.findAll('div', {'class': 'g'})
ret_res = []
for result in results:
eres = self._extract_result(result)
if eres:
ret_res.append(eres)
return ret_res
def _extract_result(self, result):
title, url = self._extract_title_url(result)
display_url = self._extract_display_url(result) # Warning: removes 'cite' from the result
desc = self._extract_description(result)
if not title or not url or not display_url or not desc:
return None
return SponsoredLink(title, url, display_url, desc)
def _extract_title_url(self, result):
title_a = result.find('a')
if not title_a:
self._maybe_raise(SLParseError, "Title tag in sponsored link was not found", result)
return None, None
title = ''.join(title_a.findAll(text=True))
title = self._html_unescape(title)
url = title_a['href']
match = re.search(r'q=(http[^&]+)&', url)
if not match:
self._maybe_raise(SLParseError, "URL inside a sponsored link was not found", result)
return None, None
url = urllib.unquote(match.group(1))
return title, url
def _extract_display_url(self, result):
cite = result.find('cite')
if not cite:
self._maybe_raise(SLParseError, "<cite> not found inside result", result)
return None
return ''.join(cite.findAll(text=True))
def _extract_description(self, result):
cite = result.find('cite')
if not cite:
return None
cite.extract()
desc_div = result.find('div', {'class': 'line23'})
if not desc_div:
self._maybe_raise(ParseError, "Description tag not found in sponsored link", result)
return None
desc_strs = desc_div.findAll(text=True)[0:-1]
desc = ''.join(desc_strs)
desc = desc.replace("\n", " ")
desc = desc.replace(" ", " ")
return self._html_unescape(desc)
def _html_unescape(self, str):
def entity_replacer(m):
entity = m.group(1)
if entity in name2codepoint:
return unichr(name2codepoint[entity])
else:
return m.group(0)
def ascii_replacer(m):
cp = int(m.group(1))
if cp <= 255:
return unichr(cp)
else:
return m.group(0)
s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U)
return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Code is licensed under MIT license.
#
import re
import urllib
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
class SearchError(Exception):
"""
Base class for Google Search exceptions.
"""
pass
class ParseError(SearchError):
"""
Parse error in Google results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
class SearchResult:
def __init__(self, title, url, desc):
self.title = title
self.url = url
self.desc = desc
def __str__(self):
return 'Google Search Result: "%s"' % self.title
class GoogleSearch(object):
SEARCH_URL_0 = "http://www.google.com/search?hl=en&q=%(query)s&btnG=Google+Search"
NEXT_PAGE_0 = "http://www.google.com/search?hl=en&q=%(query)s&start=%(start)d"
SEARCH_URL_1 = "http://www.google.com/search?hl=en&q=%(query)s&num=%(num)d&btnG=Google+Search"
NEXT_PAGE_1 = "http://www.google.com/search?hl=en&q=%(query)s&num=%(num)d&start=%(start)d"
def __init__(self, query, random_agent=False, debug=False):
self.query = query
self.debug = debug
self.browser = Browser(debug=debug)
self.results_info = None
self.eor = False # end of results
self._page = 0
self._results_per_page = 10
self._last_from = 0
if random_agent:
self.browser.set_random_user_agent()
@property
def num_results(self):
if not self.results_info:
page = self._get_results_page()
self.results_info = self._extract_info(page)
if self.results_info['total'] == 0:
self.eor = True
return self.results_info['total']
def _get_page(self):
return self._page
def _set_page(self, page):
self._page = page
page = property(_get_page, _set_page)
def _get_results_per_page(self):
return self._results_per_page
def _set_results_par_page(self, rpp):
self._results_per_page = rpp
results_per_page = property(_get_results_per_page, _set_results_par_page)
def get_results(self):
""" Gets a page of results """
#if self.eor:
# return []
page = self._get_results_page()
search_info = self._extract_info(page)
#if not self.results_info:
# self.results_info = search_info
# if self.num_results == 0:
# self.eor = True
# return []
results = self._extract_results(page)
return results
if not results:
self.eor = True
return []
if self._page > 0 and search_info['from'] == self._last_from:
self.eor = True
return []
if search_info['to'] == search_info['total']:
self.eor = True
self._page += 1
self._last_from = search_info['from']
return results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _get_results_page(self):
if self._page == 0:
if self._results_per_page == 10:
url = GoogleSearch.SEARCH_URL_0
else:
url = GoogleSearch.SEARCH_URL_1
else:
if self._results_per_page == 10:
url = GoogleSearch.NEXT_PAGE_0
else:
url = GoogleSearch.NEXT_PAGE_1
safe_url = url % { 'query': urllib.quote_plus(self.query),
'start': self._page * self._results_per_page,
'num': self._results_per_page }
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise SearchError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_info(self, soup):
empty_info = {'from': 0, 'to': 0, 'total': 0}
div_ssb = soup.find('div', id='ssb')
if not div_ssb:
self._maybe_raise(ParseError, "Div with number of results was not found on Google search page", soup)
return empty_info
p = div_ssb.find('p')
if not p:
self._maybe_raise(ParseError, """<p> tag within <div id="ssb"> was not found on Google search page""", soup)
return empty_info
txt = ''.join(p.findAll(text=True))
txt = txt.replace(',', '')
matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt, re.U)
if not matches:
return empty_info
return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))}
def _extract_results(self, soup):
results = soup.findAll('li', {'class': 'g'})
ret_res = []
for result in results:
eres = self._extract_result(result)
if eres:
ret_res.append(eres)
return ret_res
def _extract_result(self, result):
title, url = self._extract_title_url(result)
desc = self._extract_description(result)
if not title or not url or not desc:
return None
return SearchResult(title, url, desc)
def _extract_title_url(self, result):
#title_a = result.find('a', {'class': re.compile(r'\bl\b')})
title_a = result.find('a')
if not title_a:
self._maybe_raise(ParseError, "Title tag in Google search result was not found", result)
return None, None
title = ''.join(title_a.findAll(text=True))
title = self._html_unescape(title)
url = title_a['href']
match = re.match(r'/url\?q=(http[^&]+)&', url)
if match:
url = urllib.unquote(match.group(1))
return title, url
def _extract_description(self, result):
desc_div = result.find('div', {'class': re.compile(r'\bs\b')})
if not desc_div:
self._maybe_raise(ParseError, "Description tag in Google search result was not found", result)
return None
desc_strs = []
def looper(tag):
if not tag: return
for t in tag:
try:
if t.name == 'br': break
except AttributeError:
pass
try:
desc_strs.append(t.string)
except AttributeError:
desc_strs.append(t)
looper(desc_div)
looper(desc_div.find('wbr')) # BeautifulSoup does not self-close <wbr>
desc = ''.join(s for s in desc_strs if s)
return self._html_unescape(desc)
def _html_unescape(self, str):
def entity_replacer(m):
entity = m.group(1)
if entity in name2codepoint:
return unichr(name2codepoint[entity])
else:
return m.group(0)
def ascii_replacer(m):
cp = int(m.group(1))
if cp <= 255:
return unichr(cp)
else:
return m.group(0)
s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U)
return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Code is licensed under MIT license.
#
import random
import socket
import urllib
import urllib2
import httplib
BROWSERS = (
# Top most popular browsers in my access.log on 2009.02.12
# tail -50000 access.log |
# awk -F\" '{B[$6]++} END { for (b in B) { print B[b] ": " b } }' |
# sort -rn |
# head -20
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.6) Gecko/2009011912 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.48 Safari/525.19',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',
'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko/2008121621 Ubuntu/8.04 (hardy) Firefox/3.0.5',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
)
TIMEOUT = 5 # socket timeout
class BrowserError(Exception):
def __init__(self, url, error):
self.url = url
self.error = error
class PoolHTTPConnection(httplib.HTTPConnection):
def connect(self):
"""Connect to the host and port specified in __init__."""
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.settimeout(TIMEOUT)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class PoolHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(PoolHTTPConnection, req)
class Browser(object):
def __init__(self, user_agent=BROWSERS[0], debug=False, use_pool=False):
self.headers = {
'User-Agent': user_agent,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5'
}
self.debug = debug
def get_page(self, url, data=None):
handlers = [PoolHTTPHandler]
opener = urllib2.build_opener(*handlers)
if data: data = urllib.urlencode(data)
request = urllib2.Request(url, data, self.headers)
try:
response = opener.open(request)
return response.read()
except (urllib2.HTTPError, urllib2.URLError), e:
raise BrowserError(url, str(e))
except (socket.error, socket.sslerror), msg:
raise BrowserError(url, msg)
except socket.timeout, e:
raise BrowserError(url, "timeout")
except KeyboardInterrupt:
raise
except:
raise BrowserError(url, "unknown error")
def set_random_user_agent(self):
self.headers['User-Agent'] = random.choice(BROWSERS)
return self.headers['User-Agent']
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-sets/
#
# Code is licensed under MIT license.
#
import re
import urllib
import random
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
class GSError(Exception):
""" Google Sets Error """
pass
class GSParseError(Exception):
"""
Parse error in Google Sets results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
LARGE_SET = 1
SMALL_SET = 2
class GoogleSets(object):
URL_LARGE = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Large+Set"
URL_SMALL = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Small+Set+(15+items+or+fewer)"
def __init__(self, items, random_agent=False, debug=False):
self.items = items
self.debug = debug
self.browser = Browser(debug=debug)
if random_agent:
self.browser.set_random_user_agent()
def get_results(self, set_type=SMALL_SET):
page = self._get_results_page(set_type)
results = self._extract_results(page)
return results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _get_results_page(self, set_type):
if set_type == LARGE_SET:
url = GoogleSets.URL_LARGE
else:
url = GoogleSets.URL_SMALL
safe_items = [urllib.quote_plus(i) for i in self.items]
blank_items = 5 - len(safe_items)
if blank_items > 0:
safe_items += ['']*blank_items
safe_url = url % tuple(safe_items)
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise GSError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_results(self, soup):
a_links = soup.findAll('a', href=re.compile('/search'))
ret_res = [a.string for a in a_links]
return ret_res
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# A Google Python library:
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Distributed under MIT license:
#
# Copyright (c) 2009 Peteris Krumins
#
# Permission is hereby granted, free of charge, to any person
# Obtaining a copy of this software and associated documentation
# Files (the "Software"), to deal in the Software without
# Restriction, including without limitation the rights to use,
# Copy, modify, merge, publish, distribute, sublicense, and/or sell
# Copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# Conditions:
#
# The above copyright notice and this permission notice shall be
# Included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Code is licensed under MIT license.
#
import random
import socket
import urllib
import urllib2
import httplib
BROWSERS = (
# Top most popular browsers in my access.log on 2009.02.12
# tail -50000 access.log |
# awk -F\" '{B[$6]++} END { for (b in B) { print B[b] ": " b } }' |
# sort -rn |
# head -20
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.6) Gecko/2009011912 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.48 Safari/525.19',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)',
'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko/2008121621 Ubuntu/8.04 (hardy) Firefox/3.0.5',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
)
TIMEOUT = 5 # socket timeout
class BrowserError(Exception):
def __init__(self, url, error):
self.url = url
self.error = error
class PoolHTTPConnection(httplib.HTTPConnection):
def connect(self):
"""Connect to the host and port specified in __init__."""
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.settimeout(TIMEOUT)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class PoolHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(PoolHTTPConnection, req)
class Browser(object):
def __init__(self, user_agent=BROWSERS[0], debug=False, use_pool=False):
self.headers = {
'User-Agent': user_agent,
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-us,en;q=0.5'
}
self.debug = debug
def get_page(self, url, data=None):
handlers = [PoolHTTPHandler]
opener = urllib2.build_opener(*handlers)
if data: data = urllib.urlencode(data)
request = urllib2.Request(url, data, self.headers)
try:
response = opener.open(request)
return response.read()
except (urllib2.HTTPError, urllib2.URLError), e:
raise BrowserError(url, str(e))
except (socket.error, socket.sslerror), msg:
raise BrowserError(url, msg)
except socket.timeout, e:
raise BrowserError(url, "timeout")
except KeyboardInterrupt:
raise
except:
raise BrowserError(url, "unknown error")
def set_random_user_agent(self):
self.headers['User-Agent'] = random.choice(BROWSERS)
return self.headers['User-Agent']
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# A Google Python library:
# http://www.catonmat.net/blog/python-library-for-google-search/
#
# Distributed under MIT license:
#
# Copyright (c) 2009 Peteris Krumins
#
# Permission is hereby granted, free of charge, to any person
# Obtaining a copy of this software and associated documentation
# Files (the "Software"), to deal in the Software without
# Restriction, including without limitation the rights to use,
# Copy, modify, merge, publish, distribute, sublicense, and/or sell
# Copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# Conditions:
#
# The above copyright notice and this permission notice shall be
# Included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
| Python |
'''
Created on 24 Apr 2010
@author: Matik
'''
from foobnix.model.entity import CommonBean
from foobnix.thirdparty import pylast
from foobnix.thirdparty.pylast import WSError
from foobnix.util import LOG
from foobnix.util.configuration import FConfiguration
from foobnix.online.google.translate import translate
import thread
import time
import gtk
from foobnix.helpers.dialog_entry import show_entry_dialog, \
show_login_password_error_dialog
API_KEY = FConfiguration().API_KEY
API_SECRET = FConfiguration().API_SECRET
class LastFmConnector():
def __init__(self):
self.network = None
self.scrobler = None
self.preferences_window = None
thread.start_new_thread(self.init_thread, ())
def init_thread(self):
username = FConfiguration().lfm_login
password_hash = pylast.md5(FConfiguration().lfm_password)
try:
self.network = pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
"""scrobler"""
scrobler_network = pylast.get_lastfm_network(username=username, password_hash=password_hash)
self.scrobler = scrobler_network.get_scrobbler("fbx", "1.0")
except:
LOG.error("Invalid last fm login or password or network problems", username, FConfiguration().lfm_password)
val = show_login_password_error_dialog(_("Last.fm connection error"), _("Verify user and password"), username, FConfiguration().lfm_password)
if val:
FConfiguration().lfm_login = val[0]
FConfiguration().lfm_password = val[1]
def get_network(self):
return self.network
def get_scrobler(self):
return self.scrobler
def connected(self):
return self.network is not None
def search_top_albums(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
try:
albums = artist.get_top_albums()
except WSError:
LOG.info("No artist with that name")
return None
beans = []
LOG.info("Albums: ", albums)
for i, album in enumerate(albums):
if i > 6:
break;
try:
album_txt = album.item
except AttributeError:
album_txt = album['item']
tracks = album_txt.get_tracks()
bean = CommonBean(name=album_txt.get_title() + " (" + album_txt.get_release_year() + ")", path="", color="GREEN", type=CommonBean.TYPE_FOLDER, parent=query);
beans.append(bean)
for track in tracks:
bean = CommonBean(name=track, path="", type=CommonBean.TYPE_MUSIC_URL, parent=album_txt.get_title());
beans.append(bean)
return beans
def search_tags_genre(self, query):
query = translate(query, src="ru", to="en")
beans = []
tag = self.network.get_tag(query)
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
try:
tracks = tag.get_top_tracks()
except:
return None
for j, track in enumerate(tracks):
if j > 20:
break
try:
track_item = track.item
except AttributeError:
track_item = track['item']
bean = CommonBean(name=track_item.get_artist().get_name() + " - " + track_item.get_title(), path="", type=CommonBean.TYPE_MUSIC_URL, parent=tag.get_name())
beans.append(bean)
tags = self.network.search_for_tag(query)
LOG.info("tags")
LOG.info(tags)
flag = True
for i, tag in enumerate(tags.get_next_page()):
if i == 0:
LOG.info("we find it top", tag, query)
continue
if i < 4:
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
tracks = tag.get_top_tracks()
for j, track in enumerate(tracks):
if j > 10:
break
try:
track_item = track.item
except AttributeError:
track_item = track['item']
bean = CommonBean(name=track_item.get_artist().get_name() + " - " + track_item.get_title(), path="", type=CommonBean.TYPE_MUSIC_URL, parent=tag.get_name())
beans.append(bean)
else:
if flag:
bean = CommonBean(name="OTHER TAGS", path="", color="#FF99FF", type=CommonBean.TYPE_FOLDER, parent=None)
beans.append(bean)
flag = False
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
return beans
def search_top_tracks(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
try:
tracks = artist.get_top_tracks()
except WSError:
LOG.info("No artist with that name")
return None
beans = []
LOG.info("Tracks: ", tracks)
for track in tracks:
try:
track_item = track.item
except AttributeError:
track_item = track['item']
#LOG.info(track.get_duration()
bean = CommonBean(name=str(track_item), path="", type=CommonBean.TYPE_MUSIC_URL, parent=query);
#norm_duration = track_item.get_duration() / 1000
#LOG.info(track_item.get_duration(), norm_duration
#bean.time = normilize_time(norm_duration)
beans.append(bean)
return beans
def search_top_similar(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
artists = artist.get_similar(10)
beans = []
for artist in artists:
try:
artist_txt = artist.item
except AttributeError:
artist_txt = artist['item']
LOG.info(artist, artist_txt)
title = str(artist_txt)
bean = CommonBean(name=title, path="", type=CommonBean.TYPE_FOLDER, color="GREEN", parent=query);
beans.append(bean)
tops = self.search_top_tracks(title)
for top in tops:
beans.append(top)
return beans
def unimplemented_search(self, query):
song = CommonBean(name=query, type=CommonBean.TYPE_MUSIC_URL)
artist = song.getArtist()
title = song.getTitle()
track = self.network.get_track(artist, title)
LOG.debug("Search similar songs", song.getArtist(), song.getTitle())
beans = []
if not track:
return []
"""similar tracks"""
try:
similars = track.get_similar()
except:
LOG.error("Similar not found")
return None
beans.append(song)
for tsong in similars:
try:
tsong_item = tsong.item
except AttributeError:
tsong_item = tsong['item']
beans.append(CommonBean(name=str(tsong_item), type=CommonBean.TYPE_MUSIC_URL, parent=query))
return beans
| Python |
"""Beautiful Soup
Elixir and Tonic
"The Screen-Scraper's Friend"
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup parses a (possibly invalid) XML or HTML document into a
tree representation. It provides methods and Pythonic idioms that make
it easy to navigate, search, and modify the tree.
A well-formed XML/HTML document yields a well-formed data
structure. An ill-formed XML/HTML document yields a correspondingly
ill-formed data structure. If your document is only locally
well-formed, you can use this library to find and process the
well-formed part of it.
Beautiful Soup works with Python 2.2 and up. It has no external
dependencies, but you'll have more success at converting data to UTF-8
if you also install these three packages:
* chardet, for auto-detecting character encodings
http://chardet.feedparser.org/
* cjkcodecs and iconv_codec, which add more encodings to the ones supported
by stock Python.
http://cjkpython.i18n.org/
Beautiful Soup defines classes for two main parsing strategies:
* BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
language that kind of looks like XML.
* BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
or invalid. This class has web browser-like heuristics for
obtaining a sensible parse tree in the face of common HTML errors.
Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
the encoding of an HTML or XML document, and converting it to
Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
For more than you ever wanted to know about Beautiful Soup, see the
documentation:
http://www.crummy.com/software/BeautifulSoup/documentation.html
Here, have some legalese:
Copyright (c) 2004-2007, Leonard Richardson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the the Beautiful Soup Consortium and All
Night Kosher Bakery nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
"""
from __future__ import generators
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.0.6"
__copyright__ = "Copyright (c) 2004-2008 Leonard Richardson"
__license__ = "New-style BSD"
from sgmllib import SGMLParser, SGMLParseError
import codecs
import types
import re
import sgmllib
try:
from htmlentitydefs import name2codepoint
except ImportError:
name2codepoint = {}
#This hack makes Beautiful Soup able to parse XML with namespaces
sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
DEFAULT_OUTPUT_ENCODING = "utf-8"
# First, the classes that represent markup elements.
class PageElement:
"""Contains the navigational information for some part of the page
(either a tag or a piece of text)"""
def setup(self, parent=None, previous=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous = previous
self.next = None
self.previousSibling = None
self.nextSibling = None
if self.parent and self.parent.contents:
self.previousSibling = self.parent.contents[-1]
self.previousSibling.nextSibling = self
def replaceWith(self, replaceWith):
oldParent = self.parent
myIndex = self.parent.contents.index(self)
if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
# We're replacing this element with one of its siblings.
index = self.parent.contents.index(replaceWith)
if index and index < myIndex:
# Furthermore, it comes before this element. That
# means that when we extract it, the index of this
# element will change.
myIndex = myIndex - 1
self.extract()
oldParent.insert(myIndex, replaceWith)
def extract(self):
"""Destructively rips this element out of the tree."""
if self.parent:
try:
self.parent.contents.remove(self)
except ValueError:
pass
#Find the two elements that would be next to each other if
#this element (and any children) hadn't been parsed. Connect
#the two.
lastChild = self._lastRecursiveChild()
nextElement = lastChild.next
if self.previous:
self.previous.next = nextElement
if nextElement:
nextElement.previous = self.previous
self.previous = None
lastChild.next = None
self.parent = None
if self.previousSibling:
self.previousSibling.nextSibling = self.nextSibling
if self.nextSibling:
self.nextSibling.previousSibling = self.previousSibling
self.previousSibling = self.nextSibling = None
return self
def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild
def insert(self, position, newChild):
if (isinstance(newChild, basestring)
or isinstance(newChild, unicode)) \
and not isinstance(newChild, NavigableString):
newChild = NavigableString(newChild)
position = min(position, len(self.contents))
if hasattr(newChild, 'parent') and newChild.parent != None:
# We're 'inserting' an element that's already one
# of this object's children.
if newChild.parent == self:
index = self.find(newChild)
if index and index < position:
# Furthermore we're moving it further down the
# list of this object's children. That means that
# when we extract this element, our target index
# will jump down one.
position = position - 1
newChild.extract()
newChild.parent = self
previousChild = None
if position == 0:
newChild.previousSibling = None
newChild.previous = self
else:
previousChild = self.contents[position-1]
newChild.previousSibling = previousChild
newChild.previousSibling.nextSibling = newChild
newChild.previous = previousChild._lastRecursiveChild()
if newChild.previous:
newChild.previous.next = newChild
newChildsLastElement = newChild._lastRecursiveChild()
if position >= len(self.contents):
newChild.nextSibling = None
parent = self
parentsNextSibling = None
while not parentsNextSibling:
parentsNextSibling = parent.nextSibling
parent = parent.parent
if not parent: # This is the last element in the document.
break
if parentsNextSibling:
newChildsLastElement.next = parentsNextSibling
else:
newChildsLastElement.next = None
else:
nextChild = self.contents[position]
newChild.nextSibling = nextChild
if newChild.nextSibling:
newChild.nextSibling.previousSibling = newChild
newChildsLastElement.next = nextChild
if newChildsLastElement.next:
newChildsLastElement.next.previous = newChildsLastElement
self.contents.insert(position, newChild)
def append(self, tag):
"""Appends the given tag to the contents of this tag."""
self.insert(len(self.contents), tag)
def findNext(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears after this Tag in the document."""
return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
def findAllNext(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
after this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.nextGenerator,
**kwargs)
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document."""
return self._findOne(self.findNextSiblings, name, attrs, text,
**kwargs)
def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.nextSiblingGenerator, **kwargs)
fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears before this Tag in the document."""
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
before this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.previousGenerator,
**kwargs)
fetchPrevious = findAllPrevious # Compatibility with pre-3.x
def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._findOne(self.findPreviousSiblings, name, attrs, text,
**kwargs)
def findPreviousSiblings(self, name=None, attrs={}, text=None,
limit=None, **kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.previousSiblingGenerator, **kwargs)
fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
if l:
r = l[0]
return r
def findParents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._findAll(name, attrs, None, limit, self.parentGenerator,
**kwargs)
fetchParents = findParents # Compatibility with pre-3.x
#These methods do the real heavy lifting.
def _findOne(self, method, name, attrs, text, **kwargs):
r = None
l = method(name, attrs, text, 1, **kwargs)
if l:
r = l[0]
return r
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
else:
# Build a SoupStrainer
strainer = SoupStrainer(name, attrs, text, **kwargs)
results = ResultSet(strainer)
g = generator()
while True:
try:
i = g.next()
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if limit and len(results) >= limit:
break
return results
#These Generators can be used to navigate starting from both
#NavigableStrings and Tags.
def nextGenerator(self):
i = self
while i:
i = i.next
yield i
def nextSiblingGenerator(self):
i = self
while i:
i = i.nextSibling
yield i
def previousGenerator(self):
i = self
while i:
i = i.previous
yield i
def previousSiblingGenerator(self):
i = self
while i:
i = i.previousSibling
yield i
def parentGenerator(self):
i = self
while i:
i = i.parent
yield i
# Utility methods
def substituteEncoding(self, str, encoding=None):
encoding = encoding or "utf-8"
return str.replace("%SOUP-ENCODING%", encoding)
def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encoding)
else:
s = unicode(s)
else:
if encoding:
s = self.toEncoding(str(s), encoding)
else:
s = unicode(s)
return s
class NavigableString(unicode, PageElement):
def __getnewargs__(self):
return (NavigableString.__str__(self),)
def __getattr__(self, attr):
"""text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper."""
if attr == 'string':
return self
else:
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
def __unicode__(self):
return str(self).decode(DEFAULT_OUTPUT_ENCODING)
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
if encoding:
return self.encode(encoding)
else:
return self
class CData(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding)
class ProcessingInstruction(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
output = self
if "%SOUP-ENCODING%" in output:
output = self.substituteEncoding(output, encoding)
return "<?%s?>" % self.toEncoding(output, encoding)
class Comment(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!--%s-->" % NavigableString.__str__(self, encoding)
class Declaration(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!%s>" % NavigableString.__str__(self, encoding)
class Tag(PageElement):
"""Represents a found HTML tag with its attributes and contents."""
def _invert(h):
"Cheap function to invert a hash."
i = {}
for k,v in h.items():
i[v] = k
return i
XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
"quot" : '"',
"amp" : "&",
"lt" : "<",
"gt" : ">" }
XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntities and x in name2codepoint:
return unichr(name2codepoint[x])
elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
if self.convertXMLEntities:
return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
else:
return u'&%s;' % x
elif len(x) > 0 and x[0] == '#':
# Handle numeric entities
if len(x) > 1 and x[1] == 'x':
return unichr(int(x[2:], 16))
else:
return unichr(int(x[1:]))
elif self.escapeUnrecognizedEntities:
return u'&%s;' % x
else:
return u'&%s;' % x
def __init__(self, parser, name, attrs=None, parent=None,
previous=None):
"Basic constructor."
# We don't actually store the parser object: that lets extracted
# chunks be garbage-collected
self.parserClass = parser.__class__
self.isSelfClosing = parser.isSelfClosingTag(name)
self.name = name
if attrs == None:
attrs = []
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
self.containsSubstitutions = False
self.convertHTMLEntities = parser.convertHTMLEntities
self.convertXMLEntities = parser.convertXMLEntities
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
# Convert any HTML, XML, or numeric entities in the attribute values.
convert = lambda(k, val): (k,
re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
self._convertEntities,
val))
self.attrs = map(convert, self.attrs)
def get(self, key, default=None):
"""Returns the value of the 'key' attribute for the tag, or
the value given for 'default' if it doesn't have that
attribute."""
return self._getAttrMap().get(key, default)
def has_key(self, key):
return self._getAttrMap().has_key(key)
def __getitem__(self, key):
"""tag[key] returns the value of the 'key' attribute for the tag,
and throws an exception if it's not there."""
return self._getAttrMap()[key]
def __iter__(self):
"Iterating over a tag iterates over its contents."
return iter(self.contents)
def __len__(self):
"The length of a tag is the length of its list of contents."
return len(self.contents)
def __contains__(self, x):
return x in self.contents
def __nonzero__(self):
"A tag is non-None even if it has no contents."
return True
def __setitem__(self, key, value):
"""Setting tag[key] sets the value of the 'key' attribute for the
tag."""
self._getAttrMap()
self.attrMap[key] = value
found = False
for i in range(0, len(self.attrs)):
if self.attrs[i][0] == key:
self.attrs[i] = (key, value)
found = True
if not found:
self.attrs.append((key, value))
self._getAttrMap()[key] = value
def __delitem__(self, key):
"Deleting tag[key] deletes all 'key' attributes for the tag."
for item in self.attrs:
if item[0] == key:
self.attrs.remove(item)
#We don't break because bad HTML can define the same
#attribute multiple times.
self._getAttrMap()
if self.attrMap.has_key(key):
del self.attrMap[key]
def __call__(self, *args, **kwargs):
"""Calling a tag like a function is the same as calling its
findAll() method. Eg. tag('a') returns a list of all the A tags
found within this tag."""
return apply(self.findAll, args, kwargs)
def __getattr__(self, tag):
#print "Getattr %s.%s" % (self.__class__, tag)
if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
return self.find(tag[:-3])
elif tag.find('__') != 0:
return self.find(tag)
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag)
def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?"""
if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
return False
for i in range(0, len(self.contents)):
if self.contents[i] != other.contents[i]:
return False
return True
def __ne__(self, other):
"""Returns true iff this tag is not identical to the other tag,
as defined in __eq__."""
return not self == other
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
"""Renders this tag as a string."""
return self.__str__(encoding)
def __unicode__(self):
return self.__str__(None)
BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
+ "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
+ ")")
def _sub_entity(self, x):
"""Used with a regular expression to substitute the
appropriate XML entity for an XML special character."""
return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Returns a string or Unicode representation of this tag and
its contents. To get Unicode, pass None for encoding.
NOTE: since Python's HTML parser consumes whitespace, this
method is not certain to reproduce the whitespace present in
the original string."""
encodedName = self.toEncoding(self.name, encoding)
attrs = []
if self.attrs:
for key, val in self.attrs:
fmt = '%s="%s"'
if isString(val):
if self.containsSubstitutions and '%SOUP-ENCODING%' in val:
val = self.substituteEncoding(val, encoding)
# The attribute value either:
#
# * Contains no embedded double quotes or single quotes.
# No problem: we enclose it in double quotes.
# * Contains embedded single quotes. No problem:
# double quotes work here too.
# * Contains embedded double quotes. No problem:
# we enclose it in single quotes.
# * Embeds both single _and_ double quotes. This
# can't happen naturally, but it can happen if
# you modify an attribute value after parsing
# the document. Now we have a bit of a
# problem. We solve it by enclosing the
# attribute in single quotes, and escaping any
# embedded single quotes to XML entities.
if '"' in val:
fmt = "%s='%s'"
if "'" in val:
# TODO: replace with apos when
# appropriate.
val = val.replace("'", "&squot;")
# Now we're okay w/r/t quotes. But the attribute
# value might also contain angle brackets, or
# ampersands that aren't part of entities. We need
# to escape those to XML entities too.
val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
attrs.append(fmt % (self.toEncoding(key, encoding),
self.toEncoding(val, encoding)))
close = ''
closeTag = ''
if self.isSelfClosing:
close = ' /'
else:
closeTag = '</%s>' % encodedName
indentTag, indentContents = 0, 0
if prettyPrint:
indentTag = indentLevel
space = (' ' * (indentTag-1))
indentContents = indentTag + 1
contents = self.renderContents(encoding, prettyPrint, indentContents)
if self.hidden:
s = contents
else:
s = []
attributeString = ''
if attrs:
attributeString = ' ' + ' '.join(attrs)
if prettyPrint:
s.append(space)
s.append('<%s%s%s>' % (encodedName, attributeString, close))
if prettyPrint:
s.append("\n")
s.append(contents)
if prettyPrint and contents and contents[-1] != "\n":
s.append("\n")
if prettyPrint and closeTag:
s.append(space)
s.append(closeTag)
if prettyPrint and closeTag and self.nextSibling:
s.append("\n")
s = ''.join(s)
return s
def decompose(self):
"""Recursively destroys the contents of this tree."""
contents = [i for i in self.contents]
for i in contents:
if isinstance(i, Tag):
i.decompose()
else:
i.extract()
self.extract()
def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
return self.__str__(encoding, True)
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string.."""
s=[]
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.__str__(encoding)
elif isinstance(c, Tag):
s.append(c.__str__(encoding, prettyPrint, indentLevel))
if text and prettyPrint:
text = text.strip()
if text:
if prettyPrint:
s.append(" " * (indentLevel-1))
s.append(text)
if prettyPrint:
s.append("\n")
return ''.join(s)
#Soup methods
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
def findAll(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.recursiveChildGenerator
if not recursive:
generator = self.childGenerator
return self._findAll(name, attrs, text, limit, generator, **kwargs)
findChildren = findAll
# Pre-3.x compatibility methods
first = find
fetch = findAll
def fetchText(self, text=None, recursive=True, limit=None):
return self.findAll(text=text, recursive=recursive, limit=limit)
def firstText(self, text=None, recursive=True):
return self.find(text=text, recursive=recursive)
#Private methods
def _getAttrMap(self):
"""Initializes a map representation of this tag's attributes,
if not already initialized."""
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap
#Generator methods
def childGenerator(self):
for i in range(0, len(self.contents)):
yield self.contents[i]
raise StopIteration
def recursiveChildGenerator(self):
stack = [(self, 0)]
while stack:
tag, start = stack.pop()
if isinstance(tag, Tag):
for i in range(start, len(tag.contents)):
a = tag.contents[i]
yield a
if isinstance(a, Tag) and tag.contents:
if i < len(tag.contents) - 1:
stack.append((tag, i+1))
stack.append((a, 0))
break
raise StopIteration
# Next, a couple classes to represent queries and their results.
class SoupStrainer:
"""Encapsulates a number of ways of matching a markup element (tag or
text)."""
def __init__(self, name=None, attrs={}, text=None, **kwargs):
self.name = name
if isString(attrs):
kwargs['class'] = attrs
attrs = None
if kwargs:
if attrs:
attrs = attrs.copy()
attrs.update(kwargs)
else:
attrs = kwargs
self.attrs = attrs
self.text = text
def __str__(self):
if self.text:
return self.text
else:
return "%s|%s" % (self.name, self.attrs)
def searchTag(self, markupName=None, markupAttrs={}):
found = None
markup = None
if isinstance(markupName, Tag):
markup = markupName
markupAttrs = markup
callFunctionWithTagData = callable(self.name) \
and not isinstance(markupName, Tag)
if (not self.name) \
or callFunctionWithTagData \
or (markup and self._matches(markup, self.name)) \
or (not markup and self._matches(markupName, self.name)):
if callFunctionWithTagData:
match = self.name(markupName, markupAttrs)
else:
match = True
markupAttrMap = None
for attr, matchAgainst in self.attrs.items():
if not markupAttrMap:
if hasattr(markupAttrs, 'get'):
markupAttrMap = markupAttrs
else:
markupAttrMap = {}
for k,v in markupAttrs:
markupAttrMap[k] = v
attrValue = markupAttrMap.get(attr)
if not self._matches(attrValue, matchAgainst):
match = False
break
if match:
if markup:
found = markup
else:
found = markupName
return found
def search(self, markup):
#print 'looking for %s in %s' % (self, markup)
found = None
# If given a list of items, scan it for a text element that
# matches.
if isList(markup) and not isinstance(markup, Tag):
for element in markup:
if isinstance(element, NavigableString) \
and self.search(element):
found = element
break
# If it's a Tag, make sure its name or attributes match.
# Don't bother with Tags if we're searching for text.
elif isinstance(markup, Tag):
if not self.text:
found = self.searchTag(markup)
# If it's text, make sure the text matches.
elif isinstance(markup, NavigableString) or \
isString(markup):
if self._matches(markup, self.text):
found = markup
else:
raise Exception, "I don't know how to match against a %s" \
% markup.__class__
return found
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
class ResultSet(list):
"""A ResultSet is just a list that keeps track of the SoupStrainer
that created it."""
def __init__(self, source):
list.__init__([])
self.source = source
# Now, some helper functions.
def isList(l):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is listlike."""
return hasattr(l, '__iter__') \
or (type(l) in (types.ListType, types.TupleType))
def isString(s):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is stringlike."""
try:
return isinstance(s, unicode) or isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def buildTagMap(default, *args):
"""Turns a list of maps, lists, or scalars into a single map.
Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
NESTING_RESET_TAGS maps out of lists and partial maps."""
built = {}
for portion in args:
if hasattr(portion, 'items'):
#It's a map. Merge it.
for k,v in portion.items():
built[k] = v
elif isList(portion):
#It's a list. Map each item to the default.
for k in portion:
built[k] = default
else:
#It's a scalar. Map it to the default.
built[portion] = default
return built
# Now, the parser classes.
class BeautifulStoneSoup(Tag, SGMLParser):
"""This class contains the basic parser and search code. It defines
a parser that knows nothing about tag behavior except for the
following:
You can't close a tag without closing all the tags it encloses.
That is, "<foo><bar></foo>" actually means
"<foo><bar></bar></foo>".
[Another possible explanation is "<foo><bar /></foo>", but since
this class defines no SELF_CLOSING_TAGS, it will never use that
explanation.]
This class is useful for parsing XML or made-up markup languages,
or when BeautifulSoup makes an assumption counter to what you were
expecting."""
SELF_CLOSING_TAGS = {}
NESTABLE_TAGS = {}
RESET_NESTING_TAGS = {}
QUOTE_TAGS = {}
MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
lambda x: x.group(1) + ' />'),
(re.compile('<!\s+([^<>]*)>'),
lambda x: '<!' + x.group(1) + '>')
]
ROOT_TAG_NAME = u'[document]'
HTML_ENTITIES = "html"
XML_ENTITIES = "xml"
XHTML_ENTITIES = "xhtml"
# TODO: This only exists for backwards-compatibility
ALL_ENTITIES = XHTML_ENTITIES
# Used when determining whether a text node is all whitespace and
# can be replaced with a single space. A text node that contains
# fancy Unicode spaces (usually non-breaking) should be left
# alone.
STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
markupMassage=True, smartQuotesTo=XML_ENTITIES,
convertEntities=None, selfClosingTags=None):
"""The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don't apply to you, pass in False for markupMassage, and
you'll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want."""
self.parseOnlyThese = parseOnlyThese
self.fromEncoding = fromEncoding
self.smartQuotesTo = smartQuotesTo
self.convertEntities = convertEntities
# Set the rules for how we'll deal with the entities we
# encounter
if self.convertEntities:
# It doesn't make sense to convert encoded characters to
# entities even while you're converting entities to Unicode.
# Just convert it all to Unicode.
self.smartQuotesTo = None
if convertEntities == self.HTML_ENTITIES:
self.convertXMLEntities = False
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = True
elif convertEntities == self.XHTML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = False
elif convertEntities == self.XML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
else:
self.convertXMLEntities = False
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
try:
self._feed()
except StopParsing:
pass
self.markup = None # The markup can now be GCed
def convert_charref(self, name):
"""This method fixes a bug in Python's SGMLParser."""
try:
n = int(name)
except ValueError:
return
if not 0 <= n <= 127 : # ASCII ends at 127, not 255
return
return self.convert_codepoint(n)
def _feed(self, inDocumentEncoding=None):
# Convert the document to Unicode.
markup = self.markup
if isinstance(markup, unicode):
if not hasattr(self, 'originalEncoding'):
self.originalEncoding = None
else:
dammit = UnicodeDammit\
(markup, [self.fromEncoding, inDocumentEncoding],
smartQuotesTo=self.smartQuotesTo)
markup = dammit.unicode
self.originalEncoding = dammit.originalEncoding
if markup:
if self.markupMassage:
if not isList(self.markupMassage):
self.markupMassage = self.MARKUP_MASSAGE
for fix, m in self.markupMassage:
markup = fix.sub(m, markup)
# TODO: We get rid of markupMassage so that the
# soup object can be deepcopied later on. Some
# Python installations can't copy regexes. If anyone
# was relying on the existence of markupMassage, this
# might cause problems.
del(self.markupMassage)
self.reset()
SGMLParser.feed(self, markup)
# Close out any unfinished strings and close all the open tags.
self.endData()
while self.currentTag.name != self.ROOT_TAG_NAME:
self.popTag()
def __getattr__(self, methodName):
"""This method routes method call requests to either the SGMLParser
superclass or the Tag superclass, depending on the method name."""
#print "__getattr__ called on %s.%s" % (self.__class__, methodName)
if methodName.find('start_') == 0 or methodName.find('end_') == 0 \
or methodName.find('do_') == 0:
return SGMLParser.__getattr__(self, methodName)
elif methodName.find('__') != 0:
return Tag.__getattr__(self, methodName)
else:
raise AttributeError
def isSelfClosingTag(self, name):
"""Returns true iff the given string is the name of a
self-closing tag according to this parser."""
return self.SELF_CLOSING_TAGS.has_key(name) \
or self.instanceSelfClosingTags.has_key(name)
def reset(self):
Tag.__init__(self, self, self.ROOT_TAG_NAME)
self.hidden = 1
SGMLParser.reset(self)
self.currentData = []
self.currentTag = None
self.tagStack = []
self.quoteStack = []
self.pushTag(self)
def popTag(self):
tag = self.tagStack.pop()
# Tags with just one string-owning child get the child as a
# 'string' property, so that soup.tag.string is shorthand for
# soup.tag.contents[0]
if len(self.currentTag.contents) == 1 and \
isinstance(self.currentTag.contents[0], NavigableString):
self.currentTag.string = self.currentTag.contents[0]
#print "Pop", tag.name
if self.tagStack:
self.currentTag = self.tagStack[-1]
return self.currentTag
def pushTag(self, tag):
#print "Push", tag.name
if self.currentTag:
self.currentTag.contents.append(tag)
self.tagStack.append(tag)
self.currentTag = self.tagStack[-1]
def endData(self, containerClass=NavigableString):
if self.currentData:
currentData = ''.join(self.currentData)
if not currentData.translate(self.STRIP_ASCII_SPACES):
if '\n' in currentData:
currentData = '\n'
else:
currentData = ' '
self.currentData = []
if self.parseOnlyThese and len(self.tagStack) <= 1 and \
(not self.parseOnlyThese.text or \
not self.parseOnlyThese.search(currentData)):
return
o = containerClass(currentData)
o.setup(self.currentTag, self.previous)
if self.previous:
self.previous.next = o
self.previous = o
self.currentTag.contents.append(o)
def _popToTag(self, name, inclusivePop=True):
"""Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag."""
#print "Popping to %s" % name
if name == self.ROOT_TAG_NAME:
return
numPops = 0
mostRecentTag = None
for i in range(len(self.tagStack)-1, 0, -1):
if name == self.tagStack[i].name:
numPops = len(self.tagStack)-i
break
if not inclusivePop:
numPops = numPops - 1
for i in range(0, numPops):
mostRecentTag = self.popTag()
return mostRecentTag
def _smartPop(self, name):
"""We need to pop up to the previous tag of this type, unless
one of this tag's nesting reset triggers comes between this
tag and the previous tag of this type, OR unless this tag is a
generic nesting trigger and another generic nesting trigger
comes between this tag and the previous tag of this type.
Examples:
<p>Foo<b>Bar *<p>* should pop to 'p', not 'b'.
<p>Foo<table>Bar *<p>* should pop to 'table', not 'p'.
<p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'.
<li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
<tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
<td><tr><td> *<td>* should pop to 'tr', not the first 'td'
"""
nestingResetTriggers = self.NESTABLE_TAGS.get(name)
isNestable = nestingResetTriggers != None
isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
popTo = None
inclusive = True
for i in range(len(self.tagStack)-1, 0, -1):
p = self.tagStack[i]
if (not p or p.name == name) and not isNestable:
#Non-nestable tags get popped to the top or to their
#last occurance.
popTo = name
break
if (nestingResetTriggers != None
and p.name in nestingResetTriggers) \
or (nestingResetTriggers == None and isResetNesting
and self.RESET_NESTING_TAGS.has_key(p.name)):
#If we encounter one of the nesting reset triggers
#peculiar to this tag, or we encounter another tag
#that causes nesting to reset, pop up to but not
#including that tag.
popTo = p.name
inclusive = False
break
p = p.parent
if popTo:
self._popToTag(popTo, inclusive)
def unknown_starttag(self, name, attrs, selfClosing=0):
#print "Start tag %s: %s" % (name, attrs)
if self.quoteStack:
#This is not a real tag.
#print "<%s> is not real!" % name
attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs))
self.handle_data('<%s%s>' % (name, attrs))
return
self.endData()
if not self.isSelfClosingTag(name) and not selfClosing:
self._smartPop(name)
if self.parseOnlyThese and len(self.tagStack) <= 1 \
and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)):
return
tag = Tag(self, name, attrs, self.currentTag, self.previous)
if self.previous:
self.previous.next = tag
self.previous = tag
self.pushTag(tag)
if selfClosing or self.isSelfClosingTag(name):
self.popTag()
if name in self.QUOTE_TAGS:
#print "Beginning quote (%s)" % name
self.quoteStack.append(name)
self.literal = 1
return tag
def unknown_endtag(self, name):
#print "End tag %s" % name
if self.quoteStack and self.quoteStack[-1] != name:
#This is not a real end tag.
#print "</%s> is not real!" % name
self.handle_data('</%s>' % name)
return
self.endData()
self._popToTag(name)
if self.quoteStack and self.quoteStack[-1] == name:
self.quoteStack.pop()
self.literal = (len(self.quoteStack) > 0)
def handle_data(self, data):
self.currentData.append(data)
def _toStringSubclass(self, text, subclass):
"""Adds a certain piece of text to the tree as a NavigableString
subclass."""
self.endData()
self.handle_data(text)
self.endData(subclass)
def handle_pi(self, text):
"""Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later."""
if text[:3] == "xml":
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self._toStringSubclass(text, ProcessingInstruction)
def handle_comment(self, text):
"Handle comments as Comment objects."
self._toStringSubclass(text, Comment)
def handle_charref(self, ref):
"Handle character references as data."
if self.convertEntities:
data = unichr(int(ref))
else:
data = '&#%s;' % ref
self.handle_data(data)
def handle_entityref(self, ref):
"""Handle entity references as data, possibly converting known
HTML and/or XML entity references to the corresponding Unicode
characters."""
data = None
if self.convertHTMLEntities:
try:
data = unichr(name2codepoint[ref])
except KeyError:
pass
if not data and self.convertXMLEntities:
data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
if not data and self.convertHTMLEntities and \
not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
# TODO: We've got a problem here. We're told this is
# an entity reference, but it's not an XML entity
# reference or an HTML entity reference. Nonetheless,
# the logical thing to do is to pass it through as an
# unrecognized entity reference.
#
# Except: when the input is "&carol;" this function
# will be called with input "carol". When the input is
# "AT&T", this function will be called with input
# "T". We have no way of knowing whether a semicolon
# was present originally, so we don't know whether
# this is an unknown entity or just a misplaced
# ampersand.
#
# The more common case is a misplaced ampersand, so I
# escape the ampersand and omit the trailing semicolon.
data = "&%s" % ref
if not data:
# This case is different from the one above, because we
# haven't already gone through a supposedly comprehensive
# mapping of entities to Unicode characters. We might not
# have gone through any mapping at all. So the chances are
# very high that this is a real entity, and not a
# misplaced ampersand.
data = "&%s;" % ref
self.handle_data(data)
def handle_decl(self, data):
"Handle DOCTYPEs and the like as Declaration objects."
self._toStringSubclass(data, Declaration)
def parse_declaration(self, i):
"""Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object."""
j = None
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
k = len(self.rawdata)
data = self.rawdata[i+9:k]
j = k+3
self._toStringSubclass(data, CData)
else:
try:
j = SGMLParser.parse_declaration(self, i)
except SGMLParseError:
toHandle = self.rawdata[i:]
self.handle_data(toHandle)
j = i + len(toHandle)
return j
class BeautifulSoup(BeautifulStoneSoup):
"""This parser knows the following facts about HTML:
* Some tags have no closing tag and should be interpreted as being
closed as soon as they are encountered.
* The text inside some tags (ie. 'script') may contain tags which
are not really part of the document and which should be parsed
as text, not tags. If you want to parse the text as tags, you can
always fetch it and parse it explicitly.
* Tag nesting rules:
Most tags can't be nested at all. For instance, the occurance of
a <p> tag should implicitly close the previous <p> tag.
<p>Para1<p>Para2
should be transformed into:
<p>Para1</p><p>Para2
Some tags can be nested arbitrarily. For instance, the occurance
of a <blockquote> tag should _not_ implicitly close the previous
<blockquote> tag.
Alice said: <blockquote>Bob said: <blockquote>Blah
should NOT be transformed into:
Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
Some tags can be nested, but the nesting is reset by the
interposition of other tags. For instance, a <tr> tag should
implicitly close the previous <tr> tag within the same <table>,
but not close a <tr> tag in another table.
<table><tr>Blah<tr>Blah
should be transformed into:
<table><tr>Blah</tr><tr>Blah
but,
<tr>Blah<table><tr>Blah
should NOT be transformed into
<tr>Blah<table></tr><tr>Blah
Differing assumptions about tag nesting rules are a major source
of problems with the BeautifulSoup class. If BeautifulSoup is not
treating as nestable a tag your page author treats as nestable,
try ICantBelieveItsBeautifulSoup, MinimalSoup, or
BeautifulStoneSoup before writing your own subclass."""
def __init__(self, *args, **kwargs):
if not kwargs.has_key('smartQuotesTo'):
kwargs['smartQuotesTo'] = self.HTML_ENTITIES
BeautifulStoneSoup.__init__(self, *args, **kwargs)
SELF_CLOSING_TAGS = buildTagMap(None,
['br' , 'hr', 'input', 'img', 'meta',
'spacer', 'link', 'frame', 'base'])
QUOTE_TAGS = {'script' : None, 'textarea' : None}
#According to the HTML standard, each of these inline tags can
#contain another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
'center']
#According to the HTML standard, these block tags can contain
#another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
#Lists can contain other lists, but there are restrictions.
NESTABLE_LIST_TAGS = { 'ol' : [],
'ul' : [],
'li' : ['ul', 'ol'],
'dl' : [],
'dd' : ['dl'],
'dt' : ['dl'] }
#Tables can contain other tables, but there are restrictions.
NESTABLE_TABLE_TAGS = {'table' : [],
'tr' : ['table', 'tbody', 'tfoot', 'thead'],
'td' : ['tr'],
'th' : ['tr'],
'thead' : ['table'],
'tbody' : ['table'],
'tfoot' : ['table'],
}
NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre']
#If one of these tags is encountered, all tags up to the next tag of
#this type are popped.
RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
NON_NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS,
NESTABLE_TABLE_TAGS)
NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
# Used to detect the charset in a META tag; see start_meta
CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)")
def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSubstitution = False
for i in range(0, len(attrs)):
key, value = attrs[i]
key = key.lower()
if key == 'http-equiv':
httpEquiv = value
elif key == 'content':
contentType = value
contentTypeIndex = i
if httpEquiv and contentType: # It's an interesting meta tag.
match = self.CHARSET_RE.search(contentType)
if match:
if getattr(self, 'declaredHTMLEncoding') or \
(self.originalEncoding == self.fromEncoding):
# This is our second pass through the document, or
# else an encoding was specified explicitly and it
# worked. Rewrite the meta tag.
newAttr = self.CHARSET_RE.sub\
(lambda(match):match.group(1) +
"%SOUP-ENCODING%", contentType)
attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
newAttr)
tagNeedsEncodingSubstitution = True
else:
# This is our first pass through the document.
# Go through it again with the new information.
newCharset = match.group(3)
if newCharset and newCharset != self.originalEncoding:
self.declaredHTMLEncoding = newCharset
self._feed(self.declaredHTMLEncoding)
raise StopParsing
tag = self.unknown_starttag("meta", attrs)
if tag and tagNeedsEncodingSubstitution:
tag.containsSubstitutions = True
class StopParsing(Exception):
pass
class ICantBelieveItsBeautifulSoup(BeautifulSoup):
"""The BeautifulSoup class is oriented towards skipping over
common HTML errors like unclosed tags. However, sometimes it makes
errors of its own. For instance, consider this fragment:
<b>Foo<b>Bar</b></b>
This is perfectly valid (if bizarre) HTML. However, the
BeautifulSoup class will implicitly close the first b tag when it
encounters the second 'b'. It will think the author wrote
"<b>Foo<b>Bar", and didn't close the first 'b' tag, because
there's no real-world reason to bold something that's already
bold. When it encounters '</b></b>' it will close two more 'b'
tags, for a grand total of three tags closed instead of two. This
can throw off the rest of your document structure. The same is
true of a number of other tags, listed below.
It's much more common for someone to forget to close a 'b' tag
than to actually use nested 'b' tags, and the BeautifulSoup class
handles the common case. This class handles the not-co-common
case: where you can't believe someone wrote what they did, but
it's valid HTML and BeautifulSoup screwed up by assuming it
wouldn't be."""
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
'big']
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript']
NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
class MinimalSoup(BeautifulSoup):
"""The MinimalSoup class is for parsing HTML that contains
pathologically bad markup. It makes no assumptions about tag
nesting, but it does know which tags are self-closing, that
<script> tags contain Javascript and should not be parsed, that
META tags may contain encoding information, and so on.
This also makes it better for subclassing than BeautifulStoneSoup
or BeautifulSoup."""
RESET_NESTING_TAGS = buildTagMap('noscript')
NESTABLE_TAGS = {}
class BeautifulSOAP(BeautifulStoneSoup):
"""This class will push a tag with only a single string child into
the tag's parent as an attribute. The attribute's name is the tag
name, and the value is the string child. An example should give
the flavor of the change:
<foo><bar>baz</bar></foo>
=>
<foo bar="baz"><bar>baz</bar></foo>
You can then access fooTag['bar'] instead of fooTag.barTag.string.
This is, of course, useful for scraping structures that tend to
use subelements instead of attributes, such as SOAP messages. Note
that it modifies its input, so don't print the modified version
out.
I'm not sure how many people really want to use this class; let me
know if you do. Mainly I like the name."""
def popTag(self):
if len(self.tagStack) > 1:
tag = self.tagStack[-1]
parent = self.tagStack[-2]
parent._getAttrMap()
if (isinstance(tag, Tag) and len(tag.contents) == 1 and
isinstance(tag.contents[0], NavigableString) and
not parent.attrMap.has_key(tag.name)):
parent[tag.name] = tag.contents[0]
BeautifulStoneSoup.popTag(self)
#Enterprise class names! It has come to our attention that some people
#think the names of the Beautiful Soup parser classes are too silly
#and "unprofessional" for use in enterprise screen-scraping. We feel
#your pain! For such-minded folk, the Beautiful Soup Consortium And
#All-Night Kosher Bakery recommends renaming this file to
#"RobustParser.py" (or, in cases of extreme enterprisiness,
#"RobustParserBeanInterface.class") and using the following
#enterprise-friendly class aliases:
class RobustXMLParser(BeautifulStoneSoup):
pass
class RobustHTMLParser(BeautifulSoup):
pass
class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
pass
class RobustInsanelyWackAssHTMLParser(MinimalSoup):
pass
class SimplifyingSOAPParser(BeautifulSOAP):
pass
######################################################
#
# Bonus library: Unicode, Dammit
#
# This class forces XML data into a standard format (usually to UTF-8
# or Unicode). It is heavily based on code from Mark Pilgrim's
# Universal Feed Parser. It does not rewrite the XML or HTML to
# reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi
# (XML) and BeautifulSoup.start_meta (HTML).
# Autodetects character encodings.
# Download from http://chardet.feedparser.org/
try:
import chardet
# import chardet.constants
# chardet.constants._debug = 1
except ImportError:
chardet = None
# cjkcodecs and iconv_codec make Python know about more character encodings.
# Both are available from http://cjkpython.i18n.org/
# They're built in if you use Python 2.4.
try:
import cjkcodecs.aliases
except ImportError:
pass
try:
import iconv_codec
except ImportError:
pass
class UnicodeDammit:
"""A class for detecting the encoding of a *ML document and
converting it to a Unicode string. If the source encoding is
windows-1252, can replace MS smart quotes with their HTML or XML
equivalents."""
# This dictionary maps commonly seen values for "charset" in HTML
# meta tags to the corresponding Python codec names. It only covers
# values that aren't in Python's aliases and can't be determined
# by the heuristics in find_codec.
CHARSET_ALIASES = { "macintosh" : "mac-roman",
"x-sjis" : "shift-jis" }
def __init__(self, markup, overrideEncodings=[],
smartQuotesTo='xml'):
self.markup, documentEncoding, sniffedEncoding = \
self._detectEncoding(markup)
self.smartQuotesTo = smartQuotesTo
self.triedEncodings = []
if markup == '' or isinstance(markup, unicode):
self.originalEncoding = None
self.unicode = unicode(markup)
return
u = None
for proposedEncoding in overrideEncodings:
u = self._convertFrom(proposedEncoding)
if u: break
if not u:
for proposedEncoding in (documentEncoding, sniffedEncoding):
u = self._convertFrom(proposedEncoding)
if u: break
# If no luck and we have auto-detection library, try that:
if not u and chardet and not isinstance(self.markup, unicode):
u = self._convertFrom(chardet.detect(self.markup)['encoding'])
# As a last resort, try utf-8 and windows-1252:
if not u:
for proposed_encoding in ("utf-8", "windows-1252"):
u = self._convertFrom(proposed_encoding)
if u: break
self.unicode = u
if not u: self.originalEncoding = None
def _subMSChar(self, orig):
"""Changes a MS smart quote character to an XML or HTML
entity."""
sub = self.MS_CHARS.get(orig)
if type(sub) == types.TupleType:
if self.smartQuotesTo == 'xml':
sub = '&#x%s;' % sub[1]
else:
sub = '&%s;' % sub[0]
return sub
def _convertFrom(self, proposed):
proposed = self.find_codec(proposed)
if not proposed or proposed in self.triedEncodings:
return None
self.triedEncodings.append(proposed)
markup = self.markup
# Convert smart quotes to HTML if coming from an encoding
# that might have them.
if self.smartQuotesTo and proposed.lower() in("windows-1252",
"iso-8859-1",
"iso-8859-2"):
markup = re.compile("([\x80-\x9f])").sub \
(lambda(x): self._subMSChar(x.group(1)),
markup)
try:
# print "Trying to convert document to %s" % proposed
u = self._toUnicode(markup, proposed)
self.markup = u
self.originalEncoding = proposed
except Exception, e:
# print "That didn't work!"
# print e
return None
#print "Correct encoding: %s" % proposed
return self.markup
def _toUnicode(self, data, encoding):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == '\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == '\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == '\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding)
return newdata
def _detectEncoding(self, xml_data):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
elif xml_data[:4] == '\x00\x3c\x00\x3f':
# UTF-16BE
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
and (xml_data[2:4] != '\x00\x00'):
# UTF-16BE with BOM
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x3f\x00':
# UTF-16LE
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
(xml_data[2:4] != '\x00\x00'):
# UTF-16LE with BOM
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\x00\x3c':
# UTF-32BE
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x00\x00':
# UTF-32LE
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\xfe\xff':
# UTF-32BE with BOM
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\xff\xfe\x00\x00':
# UTF-32LE with BOM
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == '\xef\xbb\xbf':
# UTF-8 with BOM
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
xml_encoding_match = re.compile \
('^<\?.*encoding=[\'"](.*?)[\'"].*\?>')\
.match(xml_data)
except:
xml_encoding_match = None
if xml_encoding_match:
xml_encoding = xml_encoding_match.groups()[0].lower()
if sniffed_xml_encoding and \
(xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
'iso-10646-ucs-4', 'ucs-4', 'csucs4',
'utf-16', 'utf-32', 'utf_16', 'utf_32',
'utf16', 'u16')):
xml_encoding = sniffed_xml_encoding
return xml_data, xml_encoding, sniffed_xml_encoding
def find_codec(self, charset):
return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \
or (charset and self._codec(charset.replace("-", ""))) \
or (charset and self._codec(charset.replace("-", "_"))) \
or charset
def _codec(self, charset):
if not charset: return charset
codec = None
try:
codecs.lookup(charset)
codec = charset
except (LookupError, ValueError):
pass
return codec
EBCDIC_TO_ASCII_MAP = None
def _ebcdic_to_ascii(self, s):
c = self.__class__
if not c.EBCDIC_TO_ASCII_MAP:
emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
201,202,106,107,108,109,110,111,112,113,114,203,204,205,
206,207,208,209,126,115,116,117,118,119,120,121,122,210,
211,212,213,214,215,216,217,218,219,220,221,222,223,224,
225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
250,251,252,253,254,255)
import string
c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
''.join(map(chr, range(256))), ''.join(map(chr, emap)))
return s.translate(c.EBCDIC_TO_ASCII_MAP)
MS_CHARS = { '\x80' : ('euro', '20AC'),
'\x81' : ' ',
'\x82' : ('sbquo', '201A'),
'\x83' : ('fnof', '192'),
'\x84' : ('bdquo', '201E'),
'\x85' : ('hellip', '2026'),
'\x86' : ('dagger', '2020'),
'\x87' : ('Dagger', '2021'),
'\x88' : ('circ', '2C6'),
'\x89' : ('permil', '2030'),
'\x8A' : ('Scaron', '160'),
'\x8B' : ('lsaquo', '2039'),
'\x8C' : ('OElig', '152'),
'\x8D' : '?',
'\x8E' : ('#x17D', '17D'),
'\x8F' : '?',
'\x90' : '?',
'\x91' : ('lsquo', '2018'),
'\x92' : ('rsquo', '2019'),
'\x93' : ('ldquo', '201C'),
'\x94' : ('rdquo', '201D'),
'\x95' : ('bull', '2022'),
'\x96' : ('ndash', '2013'),
'\x97' : ('mdash', '2014'),
'\x98' : ('tilde', '2DC'),
'\x99' : ('trade', '2122'),
'\x9a' : ('scaron', '161'),
'\x9b' : ('rsaquo', '203A'),
'\x9c' : ('oelig', '153'),
'\x9d' : '?',
'\x9e' : ('#x17E', '17E'),
'\x9f' : ('Yuml', ''),}
#######################################################################
#By default, act as an HTML pretty-printer.
if __name__ == '__main__':
import sys
soup = BeautifulSoup(sys.stdin.read())
print soup.prettify()
| Python |
import urllib
import simplejson
baseUrl = "http://ajax.googleapis.com/ajax/services/language/translate"
def getSplits(text, splitLength=4500):
'''
Translate Api has a limit on length of text(4500 characters) that can be translated at once,
'''
return (text[index:index + splitLength] for index in xrange(0, len(text), splitLength))
def translate(text, src='en', to='ru'):
'''
A Python Wrapper for Google AJAX Language API:
* Uses Google Language Detection, in cases source language is not provided with the source text
* Splits up text if it's longer then 4500 characters, as a limit put up by the API
'''
params = ({'langpair': '%s|%s' % (src, to),
'v': '1.0'
})
retText = ''
for text in getSplits(text):
params['q'] = text
resp = simplejson.load(urllib.urlopen('%s' % (baseUrl), data=urllib.urlencode(params)))
try:
retText += resp['responseData']['translatedText']
except:
raise
return retText
| Python |
#!/usr/bin/python
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net -- good coders code, great reuse
#
# http://www.catonmat.net/blog/python-library-for-google-sets/
#
# Code is licensed under MIT license.
#
import re
import urllib
import random
from htmlentitydefs import name2codepoint
from BeautifulSoup import BeautifulSoup
from browser import Browser, BrowserError
class GSError(Exception):
""" Google Sets Error """
pass
class GSParseError(Exception):
"""
Parse error in Google Sets results.
self.msg attribute contains explanation why parsing failed
self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse
Thrown only in debug mode
"""
def __init__(self, msg, tag):
self.msg = msg
self.tag = tag
def __str__(self):
return self.msg
def html(self):
return self.tag.prettify()
LARGE_SET = 1
SMALL_SET = 2
class GoogleSets(object):
URL_LARGE = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Large+Set"
URL_SMALL = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Small+Set+(15+items+or+fewer)"
def __init__(self, items, random_agent=False, debug=False):
self.items = items
self.debug = debug
self.browser = Browser(debug=debug)
if random_agent:
self.browser.set_random_user_agent()
def get_results(self, set_type=SMALL_SET):
page = self._get_results_page(set_type)
results = self._extract_results(page)
return results
def _maybe_raise(self, cls, *arg):
if self.debug:
raise cls(*arg)
def _get_results_page(self, set_type):
if set_type == LARGE_SET:
url = GoogleSets.URL_LARGE
else:
url = GoogleSets.URL_SMALL
safe_items = [urllib.quote_plus(i) for i in self.items]
blank_items = 5 - len(safe_items)
if blank_items > 0:
safe_items += ['']*blank_items
safe_url = url % tuple(safe_items)
try:
page = self.browser.get_page(safe_url)
except BrowserError, e:
raise GSError, "Failed getting %s: %s" % (e.url, e.error)
return BeautifulSoup(page)
def _extract_results(self, soup):
a_links = soup.findAll('a', href=re.compile('/search'))
ret_res = [a.string for a in a_links]
return ret_res
| Python |
# -*- coding: utf-8 -*-
'''
Created on Mar 17, 2010
@author: ivan
'''
import urllib2
import urllib
import re
import time
from string import replace
from foobnix.util import LOG
from foobnix.util.configuration import FConfiguration
from foobnix.model.entity import CommonBean
from xml.sax.saxutils import unescape
from setuptools.package_index import htmldecode
from foobnix.helpers.dialog_entry import show_login_password_error_dialog
from foobnix.util.proxy_connect import set_proxy_settings
class Vkontakte:
def __init__(self, email=None, password=None):
self.cookie = None
self.execute_time = time.time()
def isLive(self):
return self.get_s_value()
def get_s_value(self):
set_proxy_settings()
host = 'http://login.vk.com/?act=login'
#host = 'http://vkontakte.ru/login.php'
post = urllib.urlencode({'email' : FConfiguration().vk_login,
'expire' : '',
'pass' : FConfiguration().vk_password,
'vk' : ''})
headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0',
'Host' : 'login.vk.com',
'Referer' : 'http://vkontakte.ru/index.php',
'Connection' : 'close',
'Pragma' : 'no-cache',
'Cache-Control' : 'no-cache',
}
conn = urllib2.Request(host, post, headers)
try:
data = urllib2.urlopen(conn)
except:
LOG.error("Error VK connection")
return None
result = data.read()
value = re.findall(r"name='s' value='(.*?)'", result)
"""old response format"""
if not value:
value = re.findall(r"name='s' id='s' value='(.*?)'", result)
if value:
return value[0]
return None
def get_cookie(self):
if FConfiguration().cookie:
LOG.info("Get VK cookie from cache")
return FConfiguration().cookie
s_value = self.get_s_value()
if not s_value:
FConfiguration().cookie = None
val = show_login_password_error_dialog(_("VKontakte connection error"), _("Verify user and password"), FConfiguration().vk_login, FConfiguration().vk_password)
if val:
FConfiguration().vk_login = val[0]
FConfiguration().vk_password = val[1]
return None
if self.cookie: return self.cookie
host = 'http://vkontakte.ru/login.php?op=slogin'
post = urllib.urlencode({'s' : s_value})
headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0',
'Host' : 'vkontakte.ru',
'Referer' : 'http://login.vk.com/?act=login',
'Connection' : 'close',
'Cookie' : 'remixchk=5; remixsid=nonenone',
'Pragma' : 'no-cache',
'Cache-Control' : 'no-cache'
}
conn = urllib2.Request(host, post, headers)
data = urllib2.urlopen(conn)
cookie_src = data.info().get('Set-Cookie')
self.cookie = re.sub(r'(expires=.*?;\s|path=\/;\s|domain=\.vkontakte\.ru(?:,\s)?)', '', cookie_src)
FConfiguration().cookie = self.cookie
return self.cookie
def get_page(self, query):
if not query:
return None
#GET /gsearch.php?section=audio&q=madonna&name=1
host = 'http://vkontakte.ru/gsearch.php?section=audio&q=vasya#c[q]=some%20id&c[section]=audio&name=1'
post = urllib.urlencode({
"c[q]" : query,
"c[section]":"audio"
})
headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0',
'Host' : 'vkontakte.ru',
'Referer' : 'http://vkontakte.ru/index.php',
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With' : 'XMLHttpRequest',
'Connection' : 'close',
'Cookie' : 'remixlang=0; remixchk=5; audio_vol=100; %s' % self.get_cookie(),
'Pragma' : 'no-cache',
'Cache-Control' : ' no-cache'
}
conn = urllib2.Request(host, post, headers)
#Do not run to offten
cur_time = time.time()
if cur_time - self.execute_time < 0.5:
LOG.info("Sleep because to many requests...")
time.sleep(0.8)
self.execute_time = time.time()
data = urllib2.urlopen(conn);
result = data.read()
return result
def get_page_by_url(self, host_url):
if not host_url:
return host_url
host_url.replace("#", "&")
post = host_url[host_url.find("?") + 1:]
LOG.debug("post", post)
headers = {'User-Agent' : 'Mozilla/5.0 (X11; U; Linux i686; uk; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 GTB7.0',
'Host' : 'vkontakte.ru',
'Referer' : 'http://vkontakte.ru/index.php',
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With' : 'XMLHttpRequest',
'Connection' : 'close',
'Cookie' : 'remixlang=0; remixchk=5; audio_vol=100; %s' % self.get_cookie(),
'Pragma' : 'no-cache',
'Cache-Control' : ' no-cache'
}
conn = urllib2.Request(host_url, post, headers)
#Do not run to offten
cur_time = time.time()
if cur_time - self.execute_time < 0.5:
LOG.info("Sleep because to many requests...")
time.sleep(0.8)
self.execute_time = time.time()
data = urllib2.urlopen(conn);
result = data.read()
return result
def get_name_by(self, id, result_album):
for album in result_album:
id_album = album[0]
name = album[1]
if id_album == id:
return name
return None
def find_most_relative_song(self, song_title):
vkSongs = self.find_song_urls(song_title)
if not vkSongs:
return None
times_count = {}
for song in vkSongs:
time = song.time
if time in times_count:
times_count[time] = times_count[time] + 1
else:
times_count[time] = 1
#get most relatives times time
r_count = max(times_count.values())
r_time = self.find_time_value(times_count, r_count)
LOG.info("LOG.info(Song time", r_time)
LOG.info("LOG.info(Count of congs", r_count)
for song in vkSongs:
if song.time == r_time:
return song
"""find songs by path"""
"""find the longest song via 10"""
"""""it is too slow
i = 0
max_len = 0
max_path = ""
for song in vkSongs:
if song.time == r_time:
i += 1
song.content_length = self.get_content_len(song.path)
if song.content_length > max_len:
max_len = song.content_length
max_path = song.path
print "Max len ", max_len, max_path
if i > 10:
song.path = max_path
return song
"""""
return vkSongs[0]
def get_content_len(self, path):
open = urllib.urlopen(path)
return open.info().getheaders("Content-Length")[0]
def find_time_value(self, times_count, r_count):
for i in times_count:
if times_count[i] == r_count:
return i
return None
def convert_vk_songs_to_beans(self, vk_songs):
beans = []
for vk_song in vk_songs:
bean = CommonBean(name=vk_song.album + " - " + vk_song.track, path=vk_song.path, type=CommonBean.TYPE_MUSIC_URL);
bean.name = bean.name.replace("'", "'")
bean.time = vk_song.time
beans.append(bean)
return beans
def find_song_urls(self, song_title):
LOG.info("start search songs", song_title)
page = self.get_page(song_title)
#page = page.decode('cp1251')
#page = page.decode("cp1251")
#unicode(page, "cp1251")
reg_all = "([^<>]*)"
resultall = re.findall("return operate\(([\w() ,']*)\);", page, re.IGNORECASE)
result_album = re.findall(u"<b id=\\\\\"performer([0-9]*)\\\\\">" + reg_all + "<", page, re.IGNORECASE | re.UNICODE)
result_track = re.findall(u"<span id=\\\\\"title([0-9]*)\\\\\">" + reg_all + "<", page, re.IGNORECASE | re.UNICODE)
result_time = re.findall("<div class=\\\\\"duration\\\\\">" + reg_all + "<", page, re.IGNORECASE)
urls = []
ids = []
vkSongs = []
for result in resultall:
result = replace(result, "'", " ")
result = replace(result, ",", " ")
result = result.split()
if len(result) > 4:
id_id = result[0]
id_server = result[1]
id_folder = result[2]
id_file = result[3]
url = "http://cs" + id_server + ".vkontakte.ru/u" + id_folder + "/audio/" + id_file + ".mp3"
urls.append(url)
ids.append(id_id)
#LOG.info(len(resultall), resultall
#LOG.info(len(urls), urls
#LOG.info(len(result_album), result_album
#LOG.info(len(result_track), result_track
LOG.info(len(result_time), result_time)
for i in xrange(len(result_time)):
id = ids[i]
path = urls[i]
album = self.get_name_by(id, result_album)
track = self.get_name_by(id, result_track)
time = result_time[i]
vkSong = VKSong(path, album, track, time)
vkSongs.append(vkSong)
return self.convert_vk_songs_to_beans(vkSongs)
def get_songs_by_url(self, url):
LOG.debug("Search By URL")
result = self.get_page_by_url(url)
try:
result = unicode(result)
except:
result = result
print result
reg_all = "([^{<}]*)"
result_url = re.findall(ur"http:([\\/.0-9_A-Z]*)", result, re.IGNORECASE)
result_artist = re.findall(u"q]=" + reg_all + "'", result, re.IGNORECASE | re.UNICODE)
result_title = re.findall(u"\"title([0-9_]*)\\\\\">" + reg_all + "", result, re.IGNORECASE | re.UNICODE)
print result_title
result_time = re.findall("duration\\\\\">" + reg_all, result, re.IGNORECASE | re.UNICODE)
result_lyr = re.findall(ur"showLyrics" + reg_all, result, re.IGNORECASE | re.UNICODE)
LOG.info("lyr:::", result_lyr)
songs = []
j = 0
for i, artist in enumerate(result_artist):
path = "http:" + result_url[i].replace("\\/", "/")
title = self.to_good_chars(result_title[i][1])
if not title:
if len(result_lyr) > j:
title = result_lyr[j]
title = title[title.find(";'>") + 3:]
j += 1
artist = self.to_good_chars(artist)
song = VKSong(path, artist, title, result_time[i]);
songs.append(song)
LOG.info(len(songs))
return self.convert_vk_songs_to_beans(songs)
def to_good_chars(self, line):
try:
return htmldecode(line)
except:
return unescape(line)
class VKSong():
def __init__(self, path, album, track, time):
self.path = path
self.album = album
self.track = track
self.time = time
self.content_length = 0
def getTime(self):
if self.time:
return time
else:
return "no time"
def getFullDescription(self):
return "[ " + self.s(self.album) + " ] " + self.s(self.track) + " " + self.s(self.time)
def __str__(self):
return "" + self.s(self.album) + " " + self.s(self.track) + " " + self.s(self.time) + " " + self.s(self.path) + " " + self.s(self.content_length)
def s(self, value):
if value:
return value
else:
return ""
def get_group_id(str):
search = "gid="
index = str.find("gid=")
return str[index + len(search):]
#vk = Vkontakte("ivan.ivanenko@gmail.com", "")
#vk.get_songs_by_url("http://vkontakte.ru/audio.php?id=3673898")
#print vk.get_s_value()
#print vk.get_cookie()
#print vk.get_page("Madonna")
#for song in vk.find_song_urls("Madoona"):
# print song.path
| Python |
'''
Created on 24 Apr 2010
@author: Matik
'''
from foobnix.model.entity import CommonBean
from foobnix.thirdparty import pylast
from foobnix.thirdparty.pylast import WSError
from foobnix.util import LOG
from foobnix.util.configuration import FConfiguration
from foobnix.online.google.translate import translate
import thread
import time
import gtk
from foobnix.helpers.dialog_entry import show_entry_dialog, \
show_login_password_error_dialog
API_KEY = FConfiguration().API_KEY
API_SECRET = FConfiguration().API_SECRET
class LastFmConnector():
def __init__(self):
self.network = None
self.scrobler = None
self.preferences_window = None
thread.start_new_thread(self.init_thread, ())
def init_thread(self):
username = FConfiguration().lfm_login
password_hash = pylast.md5(FConfiguration().lfm_password)
try:
self.network = pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
if FConfiguration().proxy_enable and FConfiguration().proxy_url:
proxy_rul = FConfiguration().proxy_url
index = proxy_rul.find(":")
proxy = proxy_rul[:index]
port = proxy_rul[index + 1:]
self.network.enable_proxy(proxy, port)
LOG.info("Enable proxy for last fm", proxy, port)
"""scrobler"""
scrobler_network = pylast.get_lastfm_network(username=username, password_hash=password_hash)
self.scrobler = scrobler_network.get_scrobbler("fbx", "1.0")
except:
LOG.error("Invalid last fm login or password or network problems", username, FConfiguration().lfm_password)
val = show_login_password_error_dialog(_("Last.fm connection error"), _("Verify user and password"), username, FConfiguration().lfm_password)
if val:
FConfiguration().lfm_login = val[0]
FConfiguration().lfm_password = val[1]
def get_network(self):
return self.network
def get_scrobler(self):
return self.scrobler
def connected(self):
return self.network is not None
def search_top_albums(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
try:
albums = artist.get_top_albums()
except WSError:
LOG.info("No artist with that name")
return None
beans = []
LOG.info("Albums: ", albums)
for i, album in enumerate(albums):
if i > 6:
break;
try:
album_txt = album.item
except AttributeError:
album_txt = album['item']
tracks = album_txt.get_tracks()
bean = CommonBean(name=album_txt.get_title() + " (" + album_txt.get_release_year() + ")", path="", color="GREEN", type=CommonBean.TYPE_FOLDER, parent=query);
beans.append(bean)
for track in tracks:
bean = CommonBean(name=track, path="", type=CommonBean.TYPE_MUSIC_URL, parent=album_txt.get_title());
beans.append(bean)
return beans
def search_tags_genre(self, query):
query = translate(query, src="ru", to="en")
beans = []
tag = self.network.get_tag(query)
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
try:
tracks = tag.get_top_tracks()
except:
return None
for j, track in enumerate(tracks):
if j > 20:
break
try:
track_item = track.item
except AttributeError:
track_item = track['item']
bean = CommonBean(name=track_item.get_artist().get_name() + " - " + track_item.get_title(), path="", type=CommonBean.TYPE_MUSIC_URL, parent=tag.get_name())
beans.append(bean)
tags = self.network.search_for_tag(query)
LOG.info("tags")
LOG.info(tags)
flag = True
for i, tag in enumerate(tags.get_next_page()):
if i == 0:
LOG.info("we find it top", tag, query)
continue
if i < 4:
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
tracks = tag.get_top_tracks()
for j, track in enumerate(tracks):
if j > 10:
break
try:
track_item = track.item
except AttributeError:
track_item = track['item']
bean = CommonBean(name=track_item.get_artist().get_name() + " - " + track_item.get_title(), path="", type=CommonBean.TYPE_MUSIC_URL, parent=tag.get_name())
beans.append(bean)
else:
if flag:
bean = CommonBean(name="OTHER TAGS", path="", color="#FF99FF", type=CommonBean.TYPE_FOLDER, parent=None)
beans.append(bean)
flag = False
bean = CommonBean(name=tag.get_name(), path="", color="GREEN", type=CommonBean.TYPE_GOOGLE_HELP, parent=None)
beans.append(bean)
return beans
def search_top_tracks(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
try:
tracks = artist.get_top_tracks()
except WSError:
LOG.info("No artist with that name")
return None
beans = []
LOG.info("Tracks: ", tracks)
for track in tracks:
try:
track_item = track.item
except AttributeError:
track_item = track['item']
#LOG.info(track.get_duration()
bean = CommonBean(name=str(track_item), path="", type=CommonBean.TYPE_MUSIC_URL, parent=query);
#norm_duration = track_item.get_duration() / 1000
#LOG.info(track_item.get_duration(), norm_duration
#bean.time = normilize_time(norm_duration)
beans.append(bean)
return beans
def search_top_similar(self, query):
#unicode(query, "utf-8")
artist = self.network.get_artist(query)
if not artist:
return None
artists = artist.get_similar(10)
beans = []
for artist in artists:
try:
artist_txt = artist.item
except AttributeError:
artist_txt = artist['item']
LOG.info(artist, artist_txt)
title = str(artist_txt)
bean = CommonBean(name=title, path="", type=CommonBean.TYPE_FOLDER, color="GREEN", parent=query);
beans.append(bean)
tops = self.search_top_tracks(title)
for top in tops:
beans.append(top)
return beans
def unimplemented_search(self, query):
song = CommonBean(name=query, type=CommonBean.TYPE_MUSIC_URL)
artist = song.getArtist()
title = song.getTitle()
track = self.network.get_track(artist, title)
LOG.debug("Search similar songs", song.getArtist(), song.getTitle())
beans = []
if not track:
return []
"""similar tracks"""
try:
similars = track.get_similar()
except:
LOG.error("Similar not found")
return None
beans.append(song)
for tsong in similars:
try:
tsong_item = tsong.item
except AttributeError:
tsong_item = tsong['item']
beans.append(CommonBean(name=str(tsong_item), type=CommonBean.TYPE_MUSIC_URL, parent=query))
return beans
| Python |
'''
Created on 20.04.2010
@author: ivan
'''
from foobnix.model.entity import CommonBean
import os
from foobnix.util import LOG
from foobnix.online.vk import Vkontakte
from foobnix.util.configuration import FConfiguration
try:
vk = Vkontakte(FConfiguration().vk_login, FConfiguration().vk_password)
except Exception, e:
print e
vk = None
LOG.error("Vkontakte connection error")
def get_song_path(song):
if not song.path:
if song.type == CommonBean.TYPE_MUSIC_URL:
"""File exists in file system"""
if _check_set_local_path(song):
return song.path
return _get_vk_song(song).path
return None
def get_songs_by_url(url):
return vk.get_songs_by_url(url);
def find_song_urls(title):
return vk.find_song_urls(title)
def update_song_path(song):
if not song.path:
if song.type == CommonBean.TYPE_MUSIC_URL:
"""File exists in file system"""
if _check_set_local_path(song):
return song.path
vkSong = _get_vk_song(song)
if vkSong:
song.path = vkSong.path
song.time = vkSong.time
LOG.debug("Time", song.time)
else:
LOG.error("VK song source not found")
return None
def _check_set_local_path(song):
file = _get_cached_song(song)
if os.path.isfile(file) and os.path.getsize(file) > 1:
song.path = file
song.type = CommonBean.TYPE_MUSIC_FILE
LOG.info("Find file on local disk", song.path)
return True
return False
def _get_vk_song(song):
LOG.info("Starting search song path in Internet", song.path)
vkSong = vk.find_most_relative_song(song.name)
return vkSong
def _make_dirs(path):
if not os.path.isdir(path):
os.makedirs(path)
def _get_cached_song(song):
dir = FConfiguration().onlineMusicPath
if song.getArtist():
dir = dir + "/" + song.getArtist()
_make_dirs(dir)
song = dir + "/" + song.name + ".mp3"
LOG.info("Stored dir: ", song)
return song
| Python |
'''
Created on 18.04.2010
@author: ivan
'''
from foobnix.util import LOG
from foobnix.thirdparty import pylast
import urllib
import gtk
import thread
from foobnix.model.entity import CommonBean
from foobnix.base.base_list_controller import BaseListController
from foobnix.util.configuration import FConfiguration
from foobnix.online.song_resource import update_song_path
from foobnix.util.mouse_utils import is_double_left_click, \
is_rigth_click
from foobnix.online.dowload_util import save_song_thread, save_as_song_thread
from foobnix.lyric.lyr import get_lyrics
import os
import time
from foobnix.helpers.menu import Popup
from cgi import escape
class SimilartSongsController(BaseListController):
def __init__(self, gx_main, playerCntr, directoryCntr, online_controller):
self.directoryCntr = directoryCntr
self.online_controller = online_controller
self.playerCntr = playerCntr
widget = gx_main.get_widget("treeview_similar_songs")
widget.set_size_request(FConfiguration().info_panel_image_size + 50, -1)
widget.get_parent().set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
BaseListController.__init__(self, widget)
self.parent = "Similar to"
def get_parent_name(self):
return _("Similar to: ") + self.parent
def get_all_songs(self):
items = self.get_all_items()
songs = []
similar = self.get_parent_name()
song = CommonBean(name=similar, type=CommonBean.TYPE_FOLDER, color="GREEN")
songs.append(song)
for item in items:
song = CommonBean(name=item, type=CommonBean.TYPE_MUSIC_URL, parent=similar)
songs.append(song)
return songs
def on_drag(self):
self.directoryCntr.append_virtual(self.get_all_songs())
def play_selected_song(self):
artist_track = self.get_selected_item()
song = CommonBean(name=artist_track, type=CommonBean.TYPE_MUSIC_URL)
update_song_path(song)
self.playerCntr.playSong(song)
def show_save_as_dialog(self, song):
LOG.debug("Show Save As Song dialog")
chooser = gtk.FileChooserDialog(title=_("Choose directory to save song"), action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
response = chooser.run()
if response == gtk.RESPONSE_OK:
path = chooser.get_filename()
save_as_song_thread(song, path)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
def show_info(self, song):
md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO,
gtk.BUTTONS_CLOSE, song.getArtist() + " - " + song.getTitle())
md.run()
md.destroy()
def on_button_press(self, w, e):
if is_double_left_click(e):
self.play_selected_song()
if is_rigth_click(e):
artist_track = self.get_selected_item()
song = CommonBean(name=artist_track, type=CommonBean.TYPE_MUSIC_URL)
menu = Popup()
menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.play_selected_song, None)
menu.add_item(_("Save"), gtk.STOCK_SAVE, save_song_thread, [song])
menu.add_item(_("Save as"), gtk.STOCK_SAVE, self.show_save_as_dialog, [song])
menu.add_item(_("Add all to virtual"), gtk.STOCK_ADD, self.on_drag, None)
menu.add_item(_("Add all to tab"), gtk.STOCK_ADD, self.on_append_to_tab, None)
menu.add_item(_("Delete from list"), gtk.STOCK_DELETE, self.remove_selected, None)
menu.add_item(_("Info"), gtk.STOCK_INFO, self.show_info, song)
menu.show(e)
def on_append_to_tab(self):
LOG.info("Create new tab and play")
self.online_controller.append_notebook_page(self.get_parent_name())
beans = self.get_all_songs()
self.online_controller.append_and_play(beans)
class SimilartArtistsController(BaseListController):
def __init__(self, gx_main, search_panel):
self.search_panel = search_panel
widget = gx_main.get_widget("treeview_similart_artists")
widget.set_size_request(FConfiguration().info_panel_image_size, -1)
widget.get_parent().set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
BaseListController.__init__(self, widget)
def on_button_press(self, w, e):
if is_double_left_click(e):
artist = self.get_selected_item()
LOG.debug("Clicked Similar Artist:", artist)
self.search_panel.set_text(artist)
class SimilartTagsController(BaseListController):
def __init__(self, gx_main, search_panel):
self.search_panel = search_panel
widget = gx_main.get_widget("treeview_song_tags")
widget.set_size_request(FConfiguration().info_panel_image_size - 50, -1)
widget.get_parent().set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
BaseListController.__init__(self, widget)
def on_button_press(self, w, e):
if is_double_left_click(e):
tags = self.get_selected_item()
LOG.debug("Clicked tags:", tags)
self.search_panel.set_text(tags)
class InformationController():
def set_no_image_album(self):
image_name = "blank-disc-cut.jpg"
try:
pix = gtk.gdk.pixbuf_new_from_file("/usr/local/share/pixmaps/" + image_name) #@UndefinedVariable
except:
try:
pix = gtk.gdk.pixbuf_new_from_file("/usr/share/pixmaps/" + image_name) #@UndefinedVariable
except:
pix = gtk.gdk.pixbuf_new_from_file("foobnix/pixmaps/" + image_name) #@UndefinedVariable
size = FConfiguration().info_panel_image_size
pix = pix.scale_simple(size, size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.album_image.set_from_pixbuf(pix)
self.lyric_image_widget.set_from_pixbuf(pix)
self.info_thread = None
def __init__(self, gx_main, playerCntr, directoryCntr, search_panel, online_controller, last_fm_connector):
self.last_fm_connector = last_fm_connector
self.album_image = gx_main.get_widget("image_widget")
self.lyric_image_widget = gx_main.get_widget("lyric_image_widget")
self.lyrics_text_widget = gx_main.get_widget("lyric_text")
self.lyrics_text_widget.set_size_request(FConfiguration().lyric_panel_image_size, -1)
self.lyric_artist_title = gx_main.get_widget("lyric_artist_title")
self.lyrics_buffer = self.lyrics_text_widget.get_buffer()
self.set_no_image_album()
"""album name"""
self.album_name = gx_main.get_widget("label_album_name")
self.album_name.set_use_markup(True)
self.current_song_label = gx_main.get_widget("current_song_label")
self.current_song_label.set_use_markup(True)
"""Similar artists"""
self.similar_artists_cntr = SimilartArtistsController(gx_main, search_panel)
self.similar_artists_cntr.set_title(_('Similar Artists'))
"""similar songs"""
self.similar_songs_cntr = SimilartSongsController(gx_main, playerCntr, directoryCntr, online_controller)
self.similar_songs_cntr.set_title(_("Similar Songs"))
"""song tags"""
self.song_tags_cntr = SimilartTagsController(gx_main, search_panel)
self.song_tags_cntr.set_title(_("Similar Tags"))
"""link buttons"""
self.lastfm_url = gx_main.get_widget("lastfm_linkbutton")
self.wiki_linkbutton = gx_main.get_widget("wiki_linkbutton")
self.mb_linkbutton = gx_main.get_widget("mb_linkbutton")
self.last_album_name = None
self.last_image = None
self.none_thead = None
def clear_all(self):
self.similar_artists_cntr.clear()
self.similar_songs_cntr.clear()
self.song_tags_cntr.clear()
def show_song_info(self, song):
if FConfiguration().view_info_panel or FConfiguration().view_lyric_panel:
self.info_thread = thread.start_new_thread(self.show_song_info_tread, (song,))
#self.show_song_info_tread(song)
else:
LOG.warn("Please try later... search is not finished, or get permission in 20 sec")
#if not self.none_thead:
#self.none_thead = thread.start_new_thread(self.none_thread, ())
def none_thread(self):
LOG.info("run none thread")
time.sleep(20)
LOG.info("None thread finished, try search again")
self.info_thread = None
self.none_thead = None
def add_similar_song(self, song):
self.current_list_model.append([song.get_short_description(), song.path])
#self.similar_songs_cntr.add_item(song.get_name())
def add_similar_artist(self, artist):
self.similar_artists_cntr.add_item(artist)
def add_tag(self, tag):
self.song_tags_cntr.add_item(tag)
def get_track(self, song):
try:
return self.last_fm_connector.get_network().get_track(song.getArtist(), song.getTitle())
except:
return None
def show_song_info_tread(self, song):
self.song = song
if not song.getArtist() or not song.getTitle():
LOG.warn("For update info artist and title are required", song.name, song.getArtist(), song.getTitle())
self.info_thread = None
return None
self.update_links(song)
LOG.info("Update song info", song.name, song.getArtist(), song.getTitle())
try:
track = self.get_track(song)
album = track.get_album()
except:
LOG.error("Error getting track and album from last.fm")
self.set_no_image_album()
self.info_thread = None
return None
if song.image:
self.update_image_from_file(song)
else:
self.update_image_from_url(album)
self.update_info_panel(song, track, album)
self.update_lyrics(song)
self.info_thread = None
def update_image_from_file(self, song):
if os.path.isfile(song.image):
pixbuf = gtk.gdk.pixbuf_new_from_file(song.image) #@UndefinedVariable
size = FConfiguration().info_panel_image_size
scaled_buf = pixbuf.scale_simple(size, size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.album_image.set_from_pixbuf(scaled_buf)
self.lyric_image_widget.set_from_pixbuf(scaled_buf)
else:
LOG.error("Song image not found", song)
def update_image_from_url(self, album):
image_url = self.get_album_image_url(album)
if not image_url:
LOG.info("Image not found, load empty.")
self.set_no_image_album()
self.info_thread = None
return None
try:
image_pix_buf = self.create_pbuf_image_from_url(image_url)
size = FConfiguration().info_panel_image_size
image_pix_buf = image_pix_buf.scale_simple(size, size, gtk.gdk.INTERP_BILINEAR) #@UndefinedVariable
self.album_image.set_from_pixbuf(image_pix_buf)
self.lyric_image_widget.set_from_pixbuf(image_pix_buf)
except:
LOG.error("dowload image error")
self.set_no_image_album()
def update_lyrics(self, song):
if song.getArtist() and song.getTitle():
try:
lyric = get_lyrics(song.getArtist(), song.getTitle())
except:
lyric = None
LOG.error("Lyrics get error")
pass
if lyric:
self.lyrics_buffer.set_text(lyric)
else:
self.lyrics_buffer.set_text(_("Lyric not found"))
self.lyric_artist_title.set_markup("<b>" + escape(song.getArtist()) +
" - " + escape(song.getTitle()) + "</b>")
self.current_song_label.set_markup("<b>" + escape(song.getTitle()) + "</b>")
def update_links(self, song):
"""set urls"""
"""TODO TypeError: cannot concatenate 'str' and 'NoneType' objects """
self.lastfm_url.set_uri("http://www.lastfm.ru/search?q=" + song.getArtist().replace('&','%26') + "&type=artist")
self.wiki_linkbutton.set_uri("http://en.wikipedia.org/w/index.php?search=" + song.getArtist().replace('&','%26'))
self.mb_linkbutton.set_uri("http://musicbrainz.org/search/textsearch.html?type=artist&query=" + song.getArtist().replace('&','%26'))
def update_info_panel(self, song, track, album):
self.similar_songs_cntr.parent = song.getArtist() + " - " + song.getTitle()
LOG.info(track)
if not track:
return None
"""similar tracks"""
try:
similars = track.get_similar()
except:
LOG.error("Similar not found")
return None
self.similar_songs_cntr.clear()
for tsong in similars:
try:
tsong_item = tsong.item
except AttributeError:
tsong_item = tsong['item']
#tsong = CommonBean(name=str(tsong_item), type=CommonBean.TYPE_MUSIC_URL)
self.similar_songs_cntr.add_item(str(tsong_item))
"""similar tags"""
tags = track.get_top_tags(15)
self.song_tags_cntr.clear()
for tag in tags:
try:
tag_item = tag.item
except AttributeError:
tag_item = tag['item']
self.add_tag(tag_item.get_name())
"""similar artists"""
artist = track.get_artist()
try:
similar_artists = artist.get_similar(25)
except Exception, e:
LOG.error(e)
return None
self.similar_artists_cntr.clear()
for artist in similar_artists:
try:
artist_item = artist.item
except AttributeError:
artist_item = artist['item']
self.add_similar_artist(artist_item.get_name())
if album:
self.album_name.set_markup("<b>" + song.getArtist() + " - " + album.get_name() + " (" + album.get_release_year() + ")</b>")
else:
self.album_name.set_markup(u"<b>" + song.getArtist() + "</b>")
def get_album_image_url(self, album):
if not album:
return None
if self.last_album_name == album.get_name():
LOG.info("Album the same, not need to dowlaod image")
#TODO need to implement album image cache
return self.last_image
LOG.info(album)
try:
self.last_album_name = album.get_name()
if FConfiguration().info_panel_image_size < 180:
self.last_image = album.get_cover_image(size=pylast.COVER_LARGE)
else:
self.last_image = album.get_cover_image(size=pylast.COVER_EXTRA_LARGE)
except:
LOG.info("image not found for:")
LOG.info("image:", self.last_image)
return self.last_image
def create_pbuf_image_from_url(self, url_to_image):
f = urllib.urlopen(url_to_image)
data = f.read()
pbl = gtk.gdk.PixbufLoader() #@UndefinedVariable
pbl.write(data)
pbuf = pbl.get_pixbuf()
pbl.close()
return pbuf
| Python |
'''
Created on Jun 10, 2010
@author: ivan
'''
from foobnix.online.google.search import GoogleSearch
from foobnix.util import LOG
"""Get search result titles from google"""
def google_search_resutls(query, results_count=10):
results = []
try:
LOG.debug("Start google search", query)
ask = query.encode('utf-8')
gs = GoogleSearch(ask)
gs.results_per_page = results_count
returns = gs.get_results()
for res in returns:
result = res.title.encode('utf8')
results.append(str(result))
except :
LOG.error("Google Search Result Error")
return results | Python |
'''
Created on Mar 16, 2010
@author: ivan
'''
from random import randint
from foobnix.util import LOG
import random
'''
Created on Mar 11, 2010
@author: ivan
'''
import gtk
from foobnix.model.entity import CommonBean
class OnlineListModel:
POS_ICON = 0
POS_TRACK_NUMBER = 1
POS_NAME = 2
POS_PATH = 3
POS_COLOR = 4
POS_INDEX = 5
POS_TYPE = 6
POS_PARENT = 7
POS_TIME = 8
POS_START_AT = 9
POS_DURATION = 10
POS_ID3 = 11
POS_IMAGE = 12
POS_INFO = 13
def __init__(self, widget):
self.widget = widget
self.current_list_model = gtk.ListStore(str, str, str, str, str, int, str, str, str, str, str, str, str, str)
self.random_list = []
cellpb = gtk.CellRendererPixbuf()
cellpb.set_property('cell-background', 'yellow')
iconColumn = gtk.TreeViewColumn(None, cellpb, stock_id=0, cell_background=4)
iconColumn.set_fixed_width(5)
descriptionColumn = gtk.TreeViewColumn('Artist - Title', gtk.CellRendererText(), text=self.POS_NAME, background=self.POS_COLOR)
descriptionColumn.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
descriptionColumn.set_resizable(True)
descriptionColumn.set_expand(True)
number_column = gtk.TreeViewColumn(None, gtk.CellRendererText(), text=self.POS_TRACK_NUMBER, background=self.POS_COLOR)
number_column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
timeColumn = gtk.TreeViewColumn('Time', gtk.CellRendererText(), text=self.POS_TIME, background=self.POS_COLOR)
timeColumn.set_fixed_width(5)
timeColumn.set_min_width(5)
widget.append_column(iconColumn)
widget.append_column(number_column)
widget.append_column(descriptionColumn)
widget.append_column(timeColumn)
#widget.append_column(empty)
widget.set_model(self.current_list_model)
def get_size(self):
return len(self.current_list_model)
def get_all_beans(self):
beans = []
for i in xrange(self.get_size()):
beans.append(self.getBeenByPosition(i))
return beans
def getBeenByPosition(self, position):
if position < 0:
position = 0
if position >= self.get_size():
position = 0
bean = CommonBean()
bean.icon = self.current_list_model[position][ self.POS_ICON]
bean.tracknumber = self.current_list_model[position][ self.POS_TRACK_NUMBER]
bean.name = self.current_list_model[position][ self.POS_NAME]
bean.path = self.current_list_model[position][ self.POS_PATH]
bean.color = self.current_list_model[position][ self.POS_COLOR]
bean.index = self.current_list_model[position][ self.POS_INDEX]
bean.type = self.current_list_model[position][ self.POS_TYPE]
bean.parent = self.current_list_model[position][ self.POS_PARENT]
bean.time = self.current_list_model[position][ self.POS_TIME]
bean.start_at = self.current_list_model[position][ self.POS_START_AT]
bean.duration = self.current_list_model[position][ self.POS_DURATION]
bean.id3 = self.current_list_model[position][ self.POS_ID3]
bean.image = self.current_list_model[position][ self.POS_IMAGE]
bean.info = self.current_list_model[position][ self.POS_INFO]
return bean
def get_random_bean(self):
if not self.random_list:
self.random_list = [x for x in xrange(self.get_size())]
index = random.choice(self.random_list)
self.random_list.remove(index)
return self.getBeenByPosition(index)
def getModel(self):
return self.current_list_model
def get_selected_bean(self):
selection = self.widget.get_selection()
model, paths = selection.get_selected_rows()
if not paths:
return None
return self._get_bean_by_path(paths[0])
def get_all_selected_beans(self):
selection = self.widget.get_selection()
model, paths = selection.get_selected_rows()
if not paths:
return None
beans = []
for path in paths:
selection.select_path(path)
bean = self._get_bean_by_path(path)
beans.append(bean)
return beans
def _get_bean_by_path(self, path):
model = self.current_list_model
iter = model.get_iter(path)
if iter:
bean = CommonBean()
bean.icon = model.get_value(iter, self.POS_ICON)
bean.tracknumber = model.get_value(iter, self.POS_TRACK_NUMBER)
bean.name = model.get_value(iter, self.POS_NAME)
bean.path = model.get_value(iter, self.POS_PATH)
bean.color = model.get_value(iter, self.POS_COLOR)
bean.index = model.get_value(iter, self.POS_INDEX)
bean.type = model.get_value(iter, self.POS_TYPE)
bean.parent = model.get_value(iter, self.POS_PARENT)
bean.time = model.get_value(iter, self.POS_TIME)
bean.start_at = model.get_value(iter, self.POS_START_AT)
bean.duration = model.get_value(iter, self.POS_DURATION)
bean.id3 = model.get_value(iter, self.POS_ID3)
bean.image = model.get_value(iter, self.POS_IMAGE)
bean.info = model.get_value(iter, self.POS_INFO)
return bean
return None
def clear(self):
self.random_list = []
self.current_list_model.clear()
def remove_selected(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected_rows()
iters = [model.get_iter(path) for path in selected]
LOG.debug("REMOVE:", iters)
for iter in iters:
model.remove(iter)
self.random_list = [x for x in xrange(self.get_size())]
def append(self, bean):
"""teplorary disable colors"""
self.random_list.append(self.get_size())
self.current_list_model.append([bean.icon, bean.tracknumber, bean.name, bean.path, bean.color, bean.index, bean.type, bean.parent, bean.time, bean.start_at, bean.duration, bean.id3, bean.image, bean.info])
def __del__(self, *a):
LOG.info("del")
def get_selected_index(self):
selection = self.widget.get_selection()
#model, selected = selection.get_selected()
model, selected = selection.get_selected_rows()
if not selected:
return None
iter = self.current_list_model.get_iter(selected[0])
if iter:
i = model.get_string_from_iter(iter)
#LOG.info("!!I", i
#if i.find(":") == -1:
#return int(i)
return int(i)
return None
def repopulate(self, played_index, shuffle=False):
LOG.info("Selected index", played_index)
beanslist = self.get_all_beans()
random_list = self.random_list[:]
if shuffle:
random.shuffle(beanslist)
self.clear()
for i in xrange(len(beanslist)):
songBean = beanslist[i]
if not songBean.color:
songBean.color = self.get_bg_color(i)
songBean.name = songBean.getPlayListDescription()
songBean.index = i
if i == played_index:
songBean.setIconPlaying()
self.append(songBean)
else:
songBean.setIconNone()
self.append(songBean)
self.random_list = random_list
def get_bg_color(self, i):
"""temp no color"""
return None
if i % 2 :
return "#F2F2F2"
else:
return "#FFFFE5"
| Python |
'''
Created on 25 Apr 2010
@author: Matik
'''
from __future__ import with_statement
import gtk
from gobject import TYPE_NONE, TYPE_PYOBJECT, TYPE_STRING #@UnresolvedImport
from foobnix.util import LOG
from foobnix.base import BaseController, SIGNAL_RUN_FIRST
from threading import Thread
from foobnix.online.song_resource import get_songs_by_url, find_song_urls
class SearchResults(Thread):
def __init__ (self, query, function):
Thread.__init__(self)
self.query = query
self.function = function
def run(self):
self.function(self.query)
class SearchPanel(BaseController):
__gsignals__ = {
'show_search_results': (SIGNAL_RUN_FIRST, TYPE_NONE, (TYPE_STRING, TYPE_PYOBJECT)),
'show_searching_line': (SIGNAL_RUN_FIRST, TYPE_NONE, (TYPE_STRING,)),
'starting_search': (SIGNAL_RUN_FIRST, TYPE_NONE, ())
}
def __init__(self, gx_main, last_fm_connector):
BaseController.__init__(self)
self.last_fm_connector = last_fm_connector
self.search_routine = self.last_fm_connector.search_top_tracks
self.create_search_mode_buttons(gx_main)
self.search_text = gx_main.get_widget("search_entry")
self.search_text.connect("activate", self.on_search) # GTK manual doesn't recommend to do this
#self.search_text.connect("key-press-event", self.on_key_pressed)
search_button = gx_main.get_widget("search_button")
search_button.connect("clicked", self.on_search)
self.search_thread = None
def on_key_pressed(self, w, event):
if event.type == gtk.gdk.KEY_PRESS: #@UndefinedVariable
#Enter pressed
LOG.info("keyval", event.keyval, "keycode", event.hardware_keycode)
if event.hardware_keycode == 36:
self.on_search()
def get_search_query(self):
query = self.search_text.get_text()
if query and len(query.strip()) > 0:
LOG.info(query)
return query
#Nothing found
return None
def set_text(self, text):
self.search_text.set_text(text)
def create_search_mode_buttons(self, gx_main):
mode_to_button_map = {self.last_fm_connector.search_top_tracks : 'top_songs_togglebutton',
self.last_fm_connector.search_top_albums : 'top_albums_togglebutton',
self.last_fm_connector.search_top_similar : 'top_similar_togglebutton',
find_song_urls : 'all_search_togglebutton',
self.last_fm_connector.search_tags_genre : 'tags_togglebutton',
self.last_fm_connector.unimplemented_search : 'tracks_togglebutton' }
self.search_mode_buttons = {}
for mode, name in mode_to_button_map.items():
button = gx_main.get_widget(name)
button.connect('toggled', self.on_search_mode_selected, mode)
self.search_mode_buttons[mode] = button
def on_search_mode_selected(self, clicked_button, selected_mode=None):
# Look if the clicked button was the only button that was checked. If yes, then turn
# it back to checked - we don't allow all buttons to be unchecked at the same time
if all([not button.get_active() for button in self.search_mode_buttons.values()]):
clicked_button.set_active(True)
# if the button should become unchecked, then do nothing
if not clicked_button.get_active():
return
# so, the button becomes checked. Uncheck all other buttons
for button in self.search_mode_buttons.values():
if button != clicked_button:
button.set_active(False)
self.search_routine = selected_mode
def capitilize_query(self, line):
if line.startswith("http"):
return line
line = line.strip()
result = ""
for l in line.split():
result += " " + l[0].upper() + l[1:]
return result
def on_search(self, *args):
LOG.debug('>>>>>>> search with ' + str(self.search_routine))
query = self.get_search_query()
if query:
query = self.capitilize_query(u"" + query)
#self.perform_search(query)
if not self.search_thread:
#self.search_thread = thread.start_new_thread(self.perform_search, (query,))
self.perform_search(query)
else:
LOG.info("Shearch is working...")
def perform_search(self, query):
#self.emit('show_searching_line', query)
beans = None
try:
if query.lower().startswith("http"):
beans = get_songs_by_url(query)
elif self.search_routine:
beans = self.search_routine(query)
except BaseException, ex:
LOG.error('Error while search for %s: %s' % (query, ex))
self.emit('show_search_results', query, beans)
self.search_thread = None
| Python |
# -*- coding: utf-8 -*-
'''
Created on Mar 18, 2010
@author: ivan
'''
import urllib2
import re
from string import replace
def _engine_search(value):
value = replace(value, " ", "+")
host = "http://en.vpleer.ru/?q=" + value
LOG.info(host)
data = urllib2.urlopen(host)
return data.read()
def get_song_path(line):
path = re.findall(r"href=\"([\w#!:.?+=&%@!\-\/]*.mp3)", line)
if path:
return path
def get_auname(line):
path = re.findall(r"class=\"auname\">(\w*)", line)
if path:
return path
def get_ausong(line):
path = re.findall(r"class=\"auname\">(\w*)<", line)
if path:
return path
def find_song_urls(song_title):
data = _engine_search(song_title)
paths = get_song_path(data)
return paths
#LOG.info("Result:", find_song_urls("Ария - Антихрист")
| Python |
# -*- coding: utf-8 -*-
# lyricwiki.py
#
# Copyright 2009 Amr Hassan <amr.hassan@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import simplejson, urllib, os, hashlib, time
def _download(args):
"""
Downloads the json response and returns it
"""
base = "http://lyrics.wikia.com/api.php?"
str_args = {}
for key in args:
str_args[key] = args[key].encode("utf-8")
args = urllib.urlencode(str_args)
return urllib.urlopen(base + args).read()
def _get_page_titles(artist, title):
"""
Returns a list of available page titles
"""
args = {"action": "query",
"list": "search",
"srsearch": artist + " " + title,
"format": "json",
}
titles = ["%s:%s" % (artist, title), "%s:%s" % (artist.title(), title.title())]
content = simplejson.loads(_download(args))
for t in content["query"]["search"]:
titles.append(t["title"])
return titles
def _get_lyrics(artist, title):
for page_title in _get_page_titles(artist, title):
args = {"action": "query",
"prop": "revisions",
"rvprop": "content",
"titles": page_title,
"format": "json",
}
revisions = simplejson.loads(_download(args))["query"]["pages"].popitem()[1]
if not "revisions" in revisions:
continue
content = revisions["revisions"][0]["*"]
if content.startswith("#Redirect"):
n_title = content[content.find("[[") + 2:content.rfind("]]")]
return _get_lyrics(*n_title.split(":"))
if "<lyrics>" in content:
return content[content.find("<lyrics>") + len("<lyrics>") : content.find("</lyrics>")].strip()
elif "<lyric>" in content:
return content[content.find("<lyric>") + len("<lyric>") : content.find("</lyric>")].strip()
def get_lyrics(artist, title, cache_dir=None):
#return "Lyrics Disabled"
"""
Get lyrics by artist and title
set cache_dir to a valid (existing) directory
to enable caching.
"""
path = None
if cache_dir and os.path.exists(cache_dir):
digest = hashlib.sha1(artist.lower().encode("utf-8") + title.lower().encode("utf-8")).hexdigest()
path = os.path.join(cache_dir, digest)
if os.path.exists(path):
fp = open(path)
return simplejson.load(fp)["lyrics"].strip()
lyrics = _get_lyrics(artist, title)
if path and lyrics:
fp = open(path, "w")
simplejson.dump({"time": time.time(), "artist": artist, "title": title,
"source": "lyricwiki", "lyrics": lyrics }, fp, indent=4)
fp.close()
return lyrics
| Python |
#-*- coding: utf-8 -*-
'''
Created on Oct 3, 2010
@author: anton.komolov
'''
import gtk
from foobnix.regui.model.signal import FControl
from foobnix.regui.state import LoadSave
from foobnix.util.fc import FC
from foobnix.regui.model import FModel
from foobnix.dm.dm_bean import DMBean
class DownloadManager(gtk.Window, FControl, LoadSave):
def __init__(self, controls):
FControl.__init__(self, controls)
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title("Download Manager")
self.set_position(gtk.WIN_POS_CENTER)
self.set_geometry_hints(self, min_width=700, min_height=400)
self.set_resizable(False)
self.connect("delete-event", self.hide_window)
self.connect("configure-event", self.on_configure_event)
self.set_icon(self.controls.trayicon.get_pixbuf())
self.beans = []
vbox = gtk.VBox(False, 0)
vbox.show()
vbox.pack_start(self.line_add(), False, False, 0)
vbox.pack_start(self.line_control(), False, False, 0)
vbox.pack_start(self.line_list(), True, True, 0)
self.add(vbox)
def _add_button(self, text='Ok', stock=None, func=None, param=None):
bt = gtk.Button(text)
if stock:
image = gtk.Image()
image.set_from_stock(stock, gtk.ICON_SIZE_BUTTON)
bt.set_image(image)
if func:
if param:
bt.connect("clicked", lambda * a: func(param))
else:
bt.connect("clicked", lambda * a: func())
bt.show()
return bt
def line_add(self):
hbox = gtk.HBox(False, 0)
hbox.show()
self.entry = gtk.Entry()
self.entry.show()
bt_add = self._add_button("Add", gtk.STOCK_ADD, self.add_click)
hbox.pack_start(self.entry, True, True, 0)
hbox.pack_start(bt_add, False, False, 0)
return hbox
def line_control(self):
hbox = gtk.HBox(True, 0)
hbox.show()
_buttons = [["Start All", gtk.STOCK_MEDIA_PLAY, self.start_all],
["Stop All", gtk.STOCK_MEDIA_STOP, self.stop_all],
["Clear list", gtk.STOCK_OK, self.clear_all],
["Preferences", gtk.STOCK_PREFERENCES, self.controls.show_preferences]]
for b in _buttons:
bt = self._add_button(*b)
hbox.pack_start(bt, False, True, 0)
return hbox
def line_list(self):
swin = gtk.ScrolledWindow()
swin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
swin.show()
vbox = gtk.VBox(False, 0)
vbox.show()
self.dm_list = vbox
swin.add_with_viewport(vbox)
return swin
def start_all(self):
for dmbean in self.beans:
dmbean.start()
def stop_all(self):
for dmbean in self.beans:
dmbean.stop()
def clear_all(self):
beans = self.beans[:]
for dmbean in beans:
dmbean.clear()
def add_click(self):
bean = FModel(text = self.entry.get_text(), path = self.entry.get_text())
self.add_bean(bean)
def add_bean(self, bean):
dmbean = DMBean(bean, self.on_clear_dmbean)
dmbean.show()
self.beans.append(dmbean)
self.dm_list.pack_start(dmbean, False, False, 0)
def on_clear_dmbean(self, dmbean):
self.beans.remove(dmbean)
print 'ACTIVE BEANS', self.beans
dmbean.destroy()
def hide_window(self, *a):
self.hide()
return True
def destroy(self):
self.hide()
return True
def on_configure_event(self, w, e):
pass
#~ FC().dm_window_size = [e.x, e.y, e.width, e.height]
def on_save(self, *a):
pass
def on_load(self):
pass
#~ cfg = FC().dm_window_size
#~ if cfg:
#~ self.set_default_size(cfg[2], cfg[3])
#~ self.move(cfg[0], cfg[1])
| Python |
#-*- coding: utf-8 -*-
'''
Created on Oct 4, 2010
@author: anton.komolov
'''
import gtk
import random
import thread
import time
class DMBean(gtk.HBox):
STATE_READY = 0
STATE_DOWNLOAD = 1
STATE_COMPLITE = 2
STATE_STOP_THREAD = 3
def __init__(self, bean, on_clear):
gtk.HBox.__init__(self, False, 0)
self._on_clear = on_clear
self.bean = bean
"""for test download"""
self.total_size = random.randrange(5*1024*1024, 15*10124*1024, 1024)
self.speed = random.randrange(500, 1024)*1024
self.ping = random.random()*2
self.cur_size = 0
self.label = gtk.Label(bean.text)
self.label.show()
self.progressbar = gtk.ProgressBar()
self.progressbar.set_text(bean.path)
self.progressbar.hide()
toolbar = gtk.Toolbar()
toolbar.show()
toolbar.set_style(gtk.TOOLBAR_ICONS)
toolbar.set_show_arrow(False)
toolbar.set_icon_size(gtk.ICON_SIZE_SMALL_TOOLBAR)
self._state = self.STATE_READY
self.start_stop = gtk.ToolButton(gtk.STOCK_MEDIA_PLAY)
self.start_stop.show()
self.start_stop.set_tooltip_text('Start download')
self.start_stop.connect("clicked", self.on_start_stop)
self.toolbutton_clear = gtk.ToolButton(gtk.STOCK_CLOSE)
self.toolbutton_clear.show()
self.toolbutton_clear.set_tooltip_text('Delete download')
self.toolbutton_clear.connect("clicked", self.on_clear)
toolbar.insert(self.toolbutton_clear, 0)
toolbar.insert(self.start_stop, 1)
self.pack_start(self.label, True, False, 0)
self.pack_start(self.progressbar, True, True, 0)
self.pack_start(toolbar, False, False, 0)
def set_state(self, state):
stocks = [gtk.STOCK_MEDIA_PLAY, gtk.STOCK_MEDIA_STOP, gtk.STOCK_OK, gtk.STOCK_CANCEL]
tooltips = ['Start download', 'Stop download', 'Clear download', 'Stopping']
label_vis = [self.label.show, self.label.hide, self.label.show, self.label.hide]
progr_vis = [self.progressbar.hide, self.progressbar.show, self.progressbar.hide, self.progressbar.show]
if self._state != state:
gtk.gdk.threads_enter()
if state == self.STATE_READY:
self.toolbutton_clear.show()
else:
self.toolbutton_clear.hide()
self.start_stop.set_stock_id(stocks[state])
self.start_stop.set_tooltip_text(tooltips[state])
label_vis[state]()
progr_vis[state]()
self._state = state
gtk.gdk.threads_leave()
def on_start_stop(self, *a):
if self._state == self.STATE_READY:
"""Start download"""
self.start()
elif self._state == self.STATE_DOWNLOAD:
"""Stop download"""
self.stop()
elif self._state == self.STATE_COMPLITE:
"""Clear download"""
self.clear()
def start(self):
if self._state == self.STATE_READY:
self.dm_thread_id = thread.start_new_thread(self.download_thread, ())
self.set_state(self.STATE_DOWNLOAD)
def stop(self):
if self._state == self.STATE_DOWNLOAD:
self.set_state(self.STATE_STOP_THREAD)
def clear(self):
if self._state == self.STATE_COMPLITE:
self.hide()
if self._on_clear:
self._on_clear(self)
def on_clear(self, *a):
if self._state == self.STATE_READY:
self.hide()
if self._on_clear:
self._on_clear(self)
def download_thread(self):
i = 0
cur_size = 0
while cur_size < self.total_size:
self.url_report(i, self.speed, self.total_size)
i += 1
cur_size += self.speed
time.sleep(self.ping)
if self._state == self.STATE_STOP_THREAD:
self.set_state(self.STATE_READY)
return
self.set_state(self.STATE_COMPLITE)
def url_report(self, block_count, block_size, total_size):
"""Hook function for urllib.urlretrieve()"""
"""stop download
if self._state == self.STATE_STOP_THREAD:
thread.exit()
self.set_state(self.STATE_READY)
return"""
"""update info"""
gtk.gdk.threads_enter()
if total_size<=0:
persent = 0.5
total_size = "NaN"
else:
persent = block_count * block_size * 1.0 / total_size
self.progressbar.set_text("%s | %s / %s (%.2f%%)" % (self.bean.text, size2text(block_count * block_size),
size2text(total_size), persent * 100))
self.progressbar.set_fraction(persent)
gtk.gdk.threads_leave()
def size2text(size):
if size > 1024*1024*1024:
return "%.2f Gb" % (size / (1024*1024*1024.0))
if size > 1024*1024:
return "%.2f Mb" % (size / (1024*1024.0))
if size > 1024:
return "%.2f Kb" % (size / 1024.0)
return size
| Python |
# -*- coding: utf-8 -*-
'''
Created on Mar 30, 2010
@author: ivan
'''
import gtk
from foobnix.util import LOG
class PrefListModel():
POS_NAME = 0
def __init__(self, widget, prefListMap):
self.widget = widget
self.prefListMap = prefListMap
self.current_list_model = gtk.ListStore(str)
renderer = gtk.CellRendererText()
renderer.connect('edited', self.editRow)
renderer.set_property('editable', True)
column = gtk.TreeViewColumn(_("My play lists"), renderer, text=0, font=2)
column.set_resizable(True)
widget.append_column(column)
widget.set_model(self.current_list_model)
def removeSelected(self):
selection = self.widget.get_selection()
selected = selection.get_selected()[1]
if selected:
self.current_list_model.remove(selected)
def editRow(self, w, event, value):
beforeRename = unicode(self.getSelected())
if value:
i = self.getSelectedIndex()
if i > 0 and not self.isContain(value):
self.current_list_model[i][self.POS_NAME] = value
"""copy songs with new name"""
LOG.info("beforeRename ", beforeRename, self.prefListMap.keys())
datas = self.prefListMap[beforeRename]
LOG.info(datas)
del self.prefListMap[beforeRename]
self.prefListMap[value] = datas
def getSelectedIndex(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
if selected:
i = model.get_string_from_iter(selected)
if i.find(":") == -1:
LOG.info("Selected index is " , i)
return int(i)
return None
def isContain(self, name):
for i in xrange(len(self.current_list_model)):
if str(self.current_list_model[i][self.POS_NAME]) == name:
return True
return False
def getSelected(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
if selected:
return model.get_value(selected, self.POS_NAME)
else:
return None
def clear(self):
self.current_list_model.clear()
def append(self, name):
self.current_list_model.append([name])
| Python |
'''
Created on Mar 11, 2010
@author: ivan
'''
from foobnix.model.entity import CommonBean
from foobnix.util import LOG
class VirturalLIstCntr():
def __init__(self):
self.items = []
def get_items(self):
return self.items
def get_item_by_index(self, index):
return self.items[index]
def append(self, item):
self.items.append(item)
def getState(self):
return self.items
def setState(self, items):
self.items = items
def remove(self, index):
if index > len(self.items):
"INDEX TOO BIG"
return
item = self.get_item_by_index(index)
LOG.info("DELETE", item.name)
self.items.remove(item)
def remove_with_childrens(self, index, parent=None):
type = self.get_item_by_index(index).type
LOG.info(type)
if type not in [CommonBean.TYPE_FOLDER, CommonBean.TYPE_GOOGLE_HELP] :
self.remove(index)
return
self.remove(index)
size = len(self.items)
for i in xrange(index, size):
LOG.info("index" + str(i),)
LOG.info(self.items[index].parent)
if self.items[index].parent == parent:
return
else:
self.remove(index)
| Python |
'''
Created on Mar 11, 2010
@author: ivan
'''
import gtk
import gobject
from foobnix.model.entity import CommonBean
from foobnix.util import LOG
class DirectoryModel():
POS_NAME = 0
POS_PATH = 1
POS_FONT = 2
POS_VISIBLE = 3
POS_TYPE = 4
POS_INDEX = 5
POS_PARENT = 6
POS_FILTER_CHILD_COUNT = 7
POS_START_AT = 8
POS_DURATION = 9
def __init__(self, widget):
self.widget = widget
self.current_list_model = gtk.TreeStore(str, str, str, gobject.TYPE_BOOLEAN, str, int, str, str, str, str)
renderer = gtk.CellRendererText()
#renderer.connect('edited', self.editRow)
#renderer.set_property('editable', True)
LOG.info("ATTTR", renderer.get_property("attributes"))
column = gtk.TreeViewColumn(_("Title"), renderer, text=0, font=2)
column.set_resizable(True)
widget.append_column(column)
filter = self.current_list_model.filter_new()
filter.set_visible_column(self.POS_VISIBLE)
widget.set_model(filter)
def editRow(self, w, event, value):
if value:
selection = self.widget.get_selection()
model, selected = selection.get_selected()
LOG.info("VAlue", value)
LOG.info(selected)
i = model.get_string_from_iter(selected)
LOG.info("I ", i)
if i.find(":") == -1:
LOG.info(i)
self.current_list_model[int(i)][self.POS_NAME] = value
def append(self, level, bean):
return self.current_list_model.append(level, [bean.name, bean.path, bean.font, bean.is_visible, bean.type, bean.index, bean.parent, bean.child_count, bean.start_at, bean.duration])
def clear(self):
self.current_list_model.clear()
def getModel(self):
return self.current_list_model
def setModel(self, model):
self.current_list_model = model
def get_selected_bean(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
return self._getBeanByIter(model, selected)
def deleteSelected(self):
model, iter = self.widget.get_selection().get_selected()
if iter:
model.remove(iter)
def _getBeanByIter(self, model, iter):
if iter:
bean = CommonBean()
bean.name = model.get_value(iter, self.POS_NAME)
bean.path = model.get_value(iter, self.POS_PATH)
bean.font = model.get_value(iter, self.POS_FONT)
bean.visible = model.get_value(iter, self.POS_VISIBLE)
bean.type = model.get_value(iter, self.POS_TYPE)
bean.index = model.get_value(iter, self.POS_INDEX)
bean.parent = model.get_value(iter, self.POS_PARENT)
bean.child_count = model.get_value(iter, self.POS_FILTER_CHILD_COUNT)
bean.start_at = model.get_value(iter, self.POS_START_AT)
bean.duration = model.get_value(iter, self.POS_DURATION)
return bean
return None
def getBeenByPosition(self, position):
bean = CommonBean()
bean.name = self.current_list_model[position][ self.POS_NAME]
bean.path = self.current_list_model[position][ self.POS_PATH]
bean.type = self.current_list_model[position][ self.POS_TYPE]
bean.visible = self.current_list_model[position][ self.POS_VISIBLE]
bean.font = self.current_list_model[position][ self.POS_FONT]
bean.parent = self.current_list_model[position][self.POS_PARENT]
bean.child_count = self.current_list_model[position][self.POS_FILTER_CHILD_COUNT]
bean.start_at = self.current_list_model[position][self.POS_START_AT]
bean.duration = self.current_list_model[position][self.POS_DURATION]
return bean
def getAllSongs(self):
result = []
for i in xrange(len(self.current_list_model)):
been = self.getBeenByPosition(i)
if been.type in [CommonBean.TYPE_MUSIC_FILE, CommonBean.TYPE_MUSIC_URL, CommonBean.TYPE_RADIO_URL]:
result.append(been)
return result
def getChildSongBySelected(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
n = model.iter_n_children(selected)
iterch = model.iter_children(selected)
results = []
for i in xrange(n):
song = self._getBeanByIter(model, iterch)
if song.type != CommonBean.TYPE_FOLDER:
results.append(self._getBeanByIter(model, iterch))
iterch = model.iter_next(iterch)
return results
def filterByName(self, query):
if len(query.strip()) > 0:
query = query.strip().decode("utf-8").lower()
for line in self.current_list_model:
name = str(line[self.POS_NAME]).lower()
if name.find(query) >= 0:
LOG.info("FIND PARENT:", name, query)
line[self.POS_VISIBLE] = True
else:
find = False
child_count = 0;
for child in line.iterchildren():
name = str(child[self.POS_NAME]).decode("utf-8").lower()
if name.find(query) >= 0:
child_count += 1
LOG.info("FIND CHILD :", name, query)
child[self.POS_VISIBLE] = True
line[self.POS_VISIBLE] = True
line[self.POS_FILTER_CHILD_COUNT] = child_count
find = True
else:
child[self.POS_VISIBLE] = False
if not find:
line[self.POS_VISIBLE] = False
else:
self.widget.expand_all()
else:
self.widget.collapse_all()
for line in self.current_list_model:
line[self.POS_VISIBLE] = True
for child in line.iterchildren():
child[self.POS_VISIBLE] = True
| Python |
# -*- coding: utf-8 -*-
'''
Created on Mar 11, 2010
@author: ivan
'''
import os
from foobnix.util import LOG
from foobnix.directory.directory_model import DirectoryModel
from foobnix.model.entity import CommonBean
from foobnix.util.configuration import FConfiguration
from foobnix.util.file_utils import isDirectory, get_file_extenstion
import gtk
from foobnix.directory.pref_list_model import PrefListModel
import gettext
from foobnix.util.mouse_utils import is_double_left_click, is_rigth_click
from mutagen.mp3 import MP3
from foobnix.util.time_utils import normilize_time
from foobnix.radio.radios import RadioFolder
from foobnix.cue.cue_reader import CueReader
from foobnix.helpers.menu import Popup
gettext.install("foobnix", unicode=True)
class DirectoryCntr():
VIEW_LOCAL_MUSIC = 0
VIEW_RADIO_STATION = 1
VIEW_VIRTUAL_LISTS = 2
VIEW_CHARTS_LISTS = 2
DEFAULT_LIST = "Default list";
#DEFAULT_LIST_NAME = _("Default list");
def __init__(self, gxMain, playlistCntr, virtualListCntr):
self.playlistCntr = playlistCntr
self.virtualListCntr = virtualListCntr
widget = gxMain.get_widget("direcotry_treeview")
self.current_list_model = DirectoryModel(widget)
widget.connect("button-press-event", self.onMouseClick)
widget.connect("key-release-event", self.onTreeViewDeleteItem)
widget.connect("drag-end", self.on_drag_get)
"Pref lists "
self.prefListMap = {self.DEFAULT_LIST : []}
self.currentListMap = self.DEFAULT_LIST
prefList = gxMain.get_widget("treeview3")
prefList.connect("button-press-event", self.onPreflListMouseClick)
prefList.connect("key-release-event", self.onPreflListDeleteItem)
prefList.connect("cursor-changed", self.onPreflListSelect)
self.prefModel = PrefListModel(prefList, self.prefListMap)
self.filter = gxMain.get_widget("filter-entry")
self.filter.connect("key-release-event", self.onFiltering)
show_local = gxMain.get_widget("show_local_music_button")
show_local.connect("toggled", self.onChangeView, self.VIEW_LOCAL_MUSIC)
show_local.connect("button-press-event", self.on_local_toggle_click)
show_local.view_type = self.VIEW_LOCAL_MUSIC
self.active_view = self.VIEW_LOCAL_MUSIC
show_radio = gxMain.get_widget("show_radio_button")
show_radio.connect("toggled", self.onChangeView, self.VIEW_RADIO_STATION)
show_radio.view_type = self.VIEW_RADIO_STATION
show_play_list = gxMain.get_widget("show_lists_button")
show_play_list.connect("toggled", self.onChangeView, self.VIEW_VIRTUAL_LISTS)
show_play_list.view_type = self.VIEW_VIRTUAL_LISTS
self.search_mode_buttons = []
self.search_mode_buttons.append(show_local)
self.search_mode_buttons.append(show_radio)
self.search_mode_buttons.append(show_play_list)
#show_charts_ = gxMain.get_widget("show_charts_button")
#show_charts_.connect("clicked", self.onChangeView, self.VIEW_CHARTS_LISTS)
self.onChangeView
self.saved_model = None
self.radio_folder = RadioFolder()
self.cache_music_beans = FConfiguration().cache_music_beans
self.radio_update_thread = None
self.direcotory_thread = None
self.addAll(reload=False)
self.direcotory_thread = None
def getState(self):
return self.prefListMap
def setState(self, preflists):
self.prefListMap = preflists
self.prefModel.prefListMap = preflists
for key in self.prefListMap:
LOG.info("add key to virtual list", unicode(key))
self.prefModel.append(key)
def getPrefListBeans(self, preflist=DEFAULT_LIST):
if preflist in self.prefListMap:
return self.prefListMap[preflist]
return None
def appendToPrefListBeans(self, beans, preflist=DEFAULT_LIST):
if not preflist in self.prefListMap:
LOG.info("Key not found")
self.prefListMap[preflist] = []
if beans:
for bean in beans:
self.prefListMap[preflist].append(bean)
def clearPrefList(self, listName):
if listName in self.prefListMap:
self.prefListMap[listName] = []
def onPreflListSelect(self, *args):
#self.view_list.set_active(self.VIEW_VIRTUAL_LISTS)
self.currentListMap = self.prefModel.getSelected()
if self.currentListMap in self.prefListMap:
beans = self.prefListMap[self.currentListMap]
self.display_virtual(beans)
else:
self.clear()
def create_new_playlist(self):
unknownListName = _("New play list")
if not self.prefModel.isContain(unknownListName):
self.prefModel.append(unknownListName)
self.prefListMap[unknownListName] = []
def delete_playlist(self):
if self.prefModel.getSelectedIndex() > 0:
del self.prefListMap[unicode(self.prefModel.getSelected())]
self.prefModel.removeSelected()
self.clear()
def onPreflListMouseClick(self, w, event):
if event.button == 3 and event.type == gtk.gdk._2BUTTON_PRESS: #@UndefinedVariable
LOG.debug("Create new paly list")
self.create_new_playlist()
if is_rigth_click(event):
menu = Popup()
#menu.add_item(_"Set"), gtk.STOCK_INDEX, func, arg)
menu.add_item(_("Create new"), gtk.STOCK_ADD, self.create_new_playlist, None)
menu.add_item(_("Delete"), gtk.STOCK_DELETE, self.delete_playlist, None)
menu.show(event)
def onPreflListDeleteItem(self, w, event):
if event.type == gtk.gdk.KEY_RELEASE: #@UndefinedVariable
#Enter pressed
LOG.info(event.keyval)
LOG.info(event.hardware_keycode)
if event.hardware_keycode == 119 or event.hardware_keycode == 107:
self.delete_playlist()
def all(self, *args):
for arg in args:
LOG.info(arg)
def getModel(self):
return self.current_list_model
def on_drag_get(self, *args):
self.populate_playlist(append=True)
"TODO: set active button state"
def set_active_view(self, view_type):
for button in self.search_mode_buttons:
if button.view_type == view_type:
button.set_active(True)
else:
button.set_active(False)
def on_local_toggle_click(self, w, event):
if is_rigth_click(event):
menu = Popup()
menu.add_item(_("Update Music Tree"), gtk.STOCK_REFRESH, self.addAll, True)
menu.show(event)
def onChangeView(self, clicked_button, active_view):
if all([not button.get_active() for button in self.search_mode_buttons]):
clicked_button.set_active(True)
# if the button should become unchecked, then do nothing
if not clicked_button.get_active():
return
# so, the button becomes checked. Uncheck all other buttons
for button in self.search_mode_buttons:
if button != clicked_button:
button.set_active(False)
self.active_view = active_view
if active_view == self.VIEW_LOCAL_MUSIC:
self.clear()
self.addAll(reload=False)
elif active_view == self.VIEW_RADIO_STATION:
if not self.radio_update_thread:
#self.radio_update_thread = thread.start_new_thread(self.update_radio_thread, ())
self.update_radio_thread()
elif active_view == self.VIEW_VIRTUAL_LISTS:
items = self.getPrefListBeans(self.DEFAULT_LIST)
self.display_virtual(items)
def update_radio_thread(self):
self.clear()
files = self.radio_folder.get_radio_FPLs()
for fpl in files:
parent = self.current_list_model.append(None, CommonBean(name=fpl.name, path=None,
font="bold", is_visible=True, type=CommonBean.TYPE_RADIO_FOLDER))
for radio, urls in fpl.urls_dict.iteritems():
self.current_list_model.append(parent, CommonBean(name=radio, path=urls[0],
font="normal", is_visible=True, type=CommonBean.TYPE_RADIO_URL,
parent=fpl.name))
self.radio_update_thread = None
def append_virtual(self, beans=None):
LOG.debug("Current virtual list", self.currentListMap)
if not self.currentListMap:
self.currentListMap = self.DEFAULT_LIST
self.appendToPrefListBeans(beans, self.currentListMap)
items = self.getPrefListBeans(self.currentListMap)
self.display_virtual(items)
def display_virtual(self, items):
self.clear()
"Displya list title"
self.current_list_model.append(None, CommonBean(name="[" + self.currentListMap + "]", path=None,
font="bold", is_visible=True, type=CommonBean.TYPE_RADIO_FOLDER,
parent=None, index=0))
if not items:
return None
parent = None
i = 1
for item in items:
LOG.info(item)
if item.parent == None:
parent = self.current_list_model.append(None, CommonBean(name=item.name, path=item.path,
font="normal", is_visible=True, type=item.type,
parent=item.parent, index=i))
else:
self.current_list_model.append(parent, CommonBean(name=item.name, path=item.path,
font="normal", is_visible=True, type=item.type,
parent=item.parent, index=i))
i += 1
def delete_virtual_list(self):
bean = self.current_list_model.get_selected_bean()
LOG.info(bean.index)
if bean.index > 0:
self.virtualListCntr.items = self.prefListMap[self.currentListMap]
self.virtualListCntr.remove_with_childrens(bean.index - 1, bean.parent)
self.append_virtual()
def onTreeViewDeleteItem(self, w, event):
if self.active_view != self.VIEW_VIRTUAL_LISTS:
return
LOG.info(event)
if event.type == gtk.gdk.KEY_RELEASE: #@UndefinedVariable
#Enter pressed
LOG.info(event.keyval)
LOG.info(event.hardware_keycode)
if event.hardware_keycode == 119 or event.hardware_keycode == 107:
LOG.info("Delete")
self.delete_virtual_list()
def onFiltering(self, *args):
text = self.filter.get_text()
LOG.info("filtering by text", text)
self.current_list_model.filterByName(text)
def onMouseClick(self, w, event):
if is_double_left_click(event):
self.populate_playlist()
if is_rigth_click(event):
if self.active_view == self.VIEW_LOCAL_MUSIC:
menu = Popup()
menu.add_item(_("Update Music Tree"), gtk.STOCK_REFRESH, self.addAll, True)
menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.populate_playlist, None)
menu.add_item(_("Add folder"), gtk.STOCK_OPEN, self.add_folder, None)
menu.show(event)
elif self.active_view == self.VIEW_RADIO_STATION:
pass
elif self.active_view == self.VIEW_VIRTUAL_LISTS:
menu = Popup()
menu.add_item(_("Play"), gtk.STOCK_MEDIA_PLAY, self.populate_playlist, None)
menu.add_item(_("Delete"), gtk.STOCK_DELETE, self.delete_virtual_list, None)
menu.show(event)
def add_folder(self):
chooser = gtk.FileChooserDialog(title=_("Choose directory with music"),
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))
chooser.set_default_response(gtk.RESPONSE_OK)
chooser.set_select_multiple(True)
if FConfiguration().last_dir:
chooser.set_current_folder(FConfiguration().last_dir)
response = chooser.run()
if response == gtk.RESPONSE_OK:
paths = chooser.get_filenames()
path = paths[0]
FConfiguration().last_dir = path[:path.rfind("/")]
for path in paths:
if path in FConfiguration().media_library_path:
pass
else:
FConfiguration().media_library_path.append(path)
self.addAll(True)
elif response == gtk.RESPONSE_CANCEL:
LOG.info('Closed, no files selected')
chooser.destroy()
print "add folder(s)"
def update_songs_time(self, songs):
for song in songs:
if song.path and song.path.endswith("3") and not song.time:
try:
audio = MP3(song.path)
song.time = normilize_time(audio.info.length)
except:
pass
#audio = EasyID3(song.path)
#song.title = str(audio["title"][0])
#song.artist =str( audio["artist"][0])
#song.album = str(audio["album"][0])
#song.tracknumber= str(audio["tracknumber"][0])
#LOG.info(song.title, song.artist, song.album
def populate_playlist(self, append=False):
LOG.info("Drug begin")
directoryBean = self.current_list_model.get_selected_bean()
if not directoryBean:
return
LOG.info("Select: ", directoryBean.name, directoryBean.type)
LOG.info("Drug type", directoryBean.type)
if append and not self.playlistCntr.current_list_model:
self.playlistCntr.append_notebook_page(directoryBean.name)
if directoryBean.type in [CommonBean.TYPE_FOLDER, CommonBean.TYPE_GOOGLE_HELP, CommonBean.TYPE_RADIO_FOLDER] :
LOG.info("Directory Bean type:",directoryBean.type)
if directoryBean.type == CommonBean.TYPE_RADIO_FOLDER or directoryBean.path == None:
LOG.info("Radio folder")
songs = self.current_list_model.getChildSongBySelected()
elif FConfiguration().add_child_folders:
LOG.info("dir folder requrcive folder")
songs = self.get_common_beans_by_folder(directoryBean.path)
else:
LOG.info("dir folder NOT requrcive folder")
songs = self.current_list_model.getChildSongBySelected()
self.update_songs_time(songs)
LOG.info("Select songs", songs)
if not songs:
return
if append:
self.playlistCntr.append(songs)
else:
self.playlistCntr.append_notebook_page(directoryBean.name)
self.playlistCntr.append_and_play(songs)
elif directoryBean.type == CommonBean.TYPE_LABEL:
songs = self.current_list_model.getAllSongs()
if append:
self.playlistCntr.append(songs)
else:
self.playlistCntr.append_notebook_page(directoryBean.name)
self.playlistCntr.append_and_play(songs)
else:
if append:
self.playlistCntr.append([directoryBean])
else:
self.playlistCntr.append_notebook_page(directoryBean.name)
self.playlistCntr.append_and_play([directoryBean])
def getALLChildren(self, row, string):
for child in row.iterchildren():
name = child[self.POS_NAME].lower()
if name.find(string) >= 0:
LOG.info("FIND SUB :", name, string)
child[self.POS_VISIBLE] = True
else:
child[self.POS_VISIBLE] = False
def updateDirectoryByPath(self, path=None):
self.current_list_model.clear()
self.addAll(reload=True)
def clear(self):
self.current_list_model.clear()
def getAllSongsByPath(self, path):
dir = os.path.abspath(path)
list = os.listdir(dir)
list = sorted(list)
result = []
for file_name in list:
if get_file_extenstion(file_name) not in FConfiguration().supportTypes:
continue
full_path = path + "/" + file_name
if not isDirectory(full_path):
bean = CommonBean(name=file_name, path=full_path, type=CommonBean.TYPE_MUSIC_FILE)
result.append(bean)
LOG.debug(result)
return result
cachModel = []
def addAllThread(self, reload):
if reload:
self.cache_music_beans = []
if not self.cache_music_beans:
self.clear()
self.current_list_model.append(None, CommonBean(name=_("Updating music, please wait... ") , path=None,
font="bold", is_visible=True, type=CommonBean.TYPE_FOLDER,
parent=None))
for path in FConfiguration().media_library_path:
if path == "/":
FConfiguration().media_library_path = None
LOG.error("not possible value in the path!!!")
self.current_list_model.append(None, CommonBean(name=_("Music not found") + path, path=None,
font="bold", is_visible=True, type=CommonBean.TYPE_FOLDER,
parent=None))
break;
LOG.info("Media path is", path)
self.go_recursive(path, None)
FConfiguration().cache_music_beans = self.cache_music_beans
if not self.cache_music_beans:
self.current_list_model.clear()
self.current_list_model.append(None, CommonBean(name=_("Music not found"), path=None,
font="bold", is_visible=True, type=CommonBean.TYPE_FOLDER,
parent=None))
for path in FConfiguration().media_library_path:
self.current_list_model.append(None, CommonBean(name=path, path=None,
font="normal", is_visible=True, type=CommonBean.TYPE_FOLDER,
parent=None))
else:
self.show_music_tree(self.cache_music_beans)
self.direcotory_thread = None
"""show music tree by parent-child relations"""
def show_music_tree(self, beans):
self.current_list_model.clear()
hash = {None:None}
for bean in beans:
if hash.has_key(bean.parent):
iter = hash[bean.parent]
else:
iter = None
new_iter = self.current_list_model.append(iter, bean)
hash[bean.path] = new_iter
def addAll(self, reload=False):
self.addAllThread(reload)
if not self.direcotory_thread:
pass
# self.direcotory_thread = thread.start_new_thread(self.addAllThread, (reload,))
#self.addAllThread(reload)
else:
LOG.info("Directory is updating...")
#self.addAllThread()
def sortedDirsAndFiles(self, path, list):
files = []
directories = []
#First add dirs
for file in list:
full_path = path + "/" + file
if isDirectory(full_path):
directories.append(file)
else:
files.append(file)
return sorted(directories) + sorted(files)
def isDirectoryWithMusic(self, path):
LOG.info("Begin read", path)
if isDirectory(path):
dir = os.path.abspath(path)
list = None
try:
list = os.listdir(dir)
except OSError, e:
LOG.info("Can'r get list of dir", e)
if not list:
return False
for file in list:
full_path = path + "/" + file
if isDirectory(full_path):
if self.isDirectoryWithMusic(full_path):
return True
else:
if get_file_extenstion(file) in FConfiguration().supportTypes:
return True
return False
def get_common_beans_by_folder(self, path):
LOG.info("begin schanning")
self.result = []
self.scanner(path, None)
return self.result
def get_common_bean_by_file(self, full_path):
if not os.path.isfile(full_path):
LOG.warn(full_path + " not a file")
return None
ext = get_file_extenstion(full_path)
LOG.info("Extension is ", ext)
if ext not in FConfiguration().supportTypes:
LOG.warn(full_path + " extensions not supported")
return None
"""check cue is valid"""
if full_path.endswith(".cue") and not CueReader(full_path).is_cue_valid():
LOG.warn(full_path + " cue not valid")
return None
return CommonBean(name=full_path, path=full_path,
font="normal", is_visible=True, type=CommonBean.TYPE_MUSIC_FILE,
parent=full_path)
def scanner(self, path, level):
LOG.info("scanner", path)
dir = os.path.abspath(path)
list = os.listdir(dir)
list = self.sortedDirsAndFiles(path, list)
for file in list:
full_path = path + "/" + file
if not isDirectory(full_path) and get_file_extenstion(file) not in FConfiguration().supportTypes:
continue
"""check cue is valid"""
if full_path.endswith(".cue") and not CueReader(full_path).is_cue_valid():
continue
if self.isDirectoryWithMusic(full_path):
#self.result.append(CommonBean(name=file, path=full_path,
# font="bold", is_visible=True, type=CommonBean.TYPE_FOLDER,
# parent=level))
self.scanner(full_path, None)
else:
if not isDirectory(full_path):
self.result.append(CommonBean(name=file, path=full_path,
font="normal", is_visible=True, type=CommonBean.TYPE_MUSIC_FILE,
parent=level))
def go_recursive(self, path, level):
dir = os.path.abspath(path)
list = os.listdir(dir)
list = self.sortedDirsAndFiles(path, list)
for file in list:
full_path = path + "/" + file
if not isDirectory(full_path) and get_file_extenstion(file) not in FConfiguration().supportTypes:
continue
"""check cue is valid"""
if full_path.endswith(".cue") and not CueReader(full_path).is_cue_valid():
continue
if self.isDirectoryWithMusic(full_path):
#LOG.debug("directory", file)
self.cache_music_beans.append(CommonBean(name=file, path=full_path,
font="bold", is_visible=True, type=CommonBean.TYPE_FOLDER,
parent=level))
self.go_recursive(full_path, full_path)
else:
if not isDirectory(full_path):
self.cache_music_beans.append(CommonBean(name=file, path=full_path,
font="normal", is_visible=True, type=CommonBean.TYPE_MUSIC_FILE,
parent=level))
#LOG.debug("file", file)
| Python |
# ~*~ coding:utf-8 ~*~ #
'''
Created on Feb 26, 2010
@author: ivan
'''
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
import os
import gtk
from foobnix.util.configuration import FConfiguration
from mutagen.flac import FLAC
from mutagen.apev2 import APEv2
from foobnix.util import LOG
import mutagen.mp3
from foobnix.regui.model import FModel
class CommonBean(FModel):
TYPE_FOLDER = "TYPE_FOLDER"
TYPE_RADIO_FOLDER = "TYPE_RADIO_FOLDER"
TYPE_LABEL = "TYPE_LABEL"
TYPE_GOOGLE_HELP = "TYPE_GOOGLE_HELP"
TYPE_MUSIC_FILE = "TYPE_MUSIC_FILE"
TYPE_MUSIC_URL = "TYPE_MUSIC_URL"
TYPE_RADIO_URL = "TYPE_RADIO_URL"
#Song attributes
album = ""
date = ""
genre = ""
tracknumber = ""
def __init__(self, name=None, path=None, type=None, is_visible=True, color=None, font="normal", index= -1, parent=None, id3=None):
FModel.__init__(self)
self.name = name
self.path = path
self.type = type
self.icon = None
self.color = color
self.index = index
self.time = None
self.is_visible = is_visible
self.font = font
self.parent = parent
self.time = None
self.album = None
self.year = None
self.artist = None
self.title = None
self.child_count = None
self.start_at = None
self.duration = None
self.id3 = None
self.image = None
self.info = ""
def set_name(self, name):
self.artist = None;
self.tilte = None
self.name = name
def getArtist(self):
if self.artist:
return self.artist
s = self.name.split(" - ")
if len(s) > 1:
artist = self.name.split(" - ")[0]
self.artist = ("" + artist).strip()
return self.decode_string(self.artist)
return ""
def decode_string(self, str):
try:
return str.decode('utf-8')
except:
LOG.error("Error decode str", str)
return str
def getTitle(self):
if self.title:
return self.title
s = self.name.split(" - ")
result = ""
if len(s) > 1:
title = self.name.split(" - ")[1]
result = ("" + title).strip()
else:
result = self.name
for ex in FConfiguration().supportTypes:
if result.endswith(ex):
result = result[:-len(ex)]
self.title = result
return self.decode_string(result)
def setIconPlaying(self):
self.icon = gtk.STOCK_GO_FORWARD
def setIconErorr(self):
self.icon = gtk.STOCK_DIALOG_ERROR
def setIconNone(self):
self.icon = None
def getTitleDescription(self):
if self.title and self.artist and self.album:
return self.artist + " - [" + self.album + "] #" + self.tracknumber + " " + self.title
else:
if self.id3:
return "[" + self.id3 + "] " + self.name
else:
return self.name
def get_short_description(self):
if self.title:
return self.tracknumber + " - " + self.title
else:
return self.name
def getPlayListDescription(self):
if self.title and self.album:
return self.name + " - " + self.title + " (" + self.album + ")" + self.parent
return self.name
def getMp3TagsName(self):
audio = None
if not self.path:
return
if not self.type:
return
if self.type != self.TYPE_MUSIC_FILE:
return
if not os.path.exists(self.path):
return
path = self.path.lower()
if path.endswith(".flac"):
try:
audio = FLAC(self.path)
except:
return None
elif path.endswith(".ape") or path.endswith(".mpc"):
try:
audio = APEv2(self.path)
except:
return None
else:
try:
audio = MP3(self.path, ID3=EasyID3)
except:
return None
artist = None
title = None
try:
if audio and audio.has_key('artist'): artist = audio["artist"][0]
if audio and audio.has_key('title'): title = audio["title"][0]
if audio.info: self.info = audio.info.pprint()
#if audio and audio.has_key('duration'): self.duration = audio["duration"][0]
if artist and title:
line = artist + " - " + title
try:
decode_line = line.decode("cp866")
if decode_line.find(u"├") >= 0 :
LOG.warn("File tags encoding is very old cp866")
line = decode_line.replace(
u"\u252c", u'ё').replace(
u"├", "").replace(
u"░", u"р").replace(
u"▒", u"с").replace(
u"▓", u"т").replace(
u"│", u"у").replace(
u"┤", u"ф").replace(
u"╡", u"х").replace(
u"╢", u"ц").replace(
u"╖", u"ч").replace(
u"╕", u"ш").replace(
u"╣", u"щ").replace(
u"║", u"ъ").replace(
u"╗", u"ы").replace(
u"╝", u"ь").replace(
u"╜", u"э").replace(
u"╛", u"ю").replace(
u"┐", u"я")
#fix ёш to ё
line = line.replace(u'\u0451\u0448', u'\u0451')
except:
pass
self.id3, self.name = self.name, line
return line
except:
LOG.error("Get song attribute error")
pass
def __str__(self):
return "Common Bean :" + self.__contcat(
"name:", self.name,
"path:", self.path,
"type:", self.type,
"icon:", self.icon,
"color:", self.color,
"index:", self.index,
"time:", self.time,
"is_visible:", self.is_visible,
"font:", self.font,
"parent", self.parent)
def __contcat(self, *args):
result = ""
for arg in args:
result += " " + str(arg)
return result
| Python |
#-*- coding: utf-8 -*-
'''
Created on 11 сент. 2010
@author: ivan
'''
import os
def get_image_by_path(path):
dir = os.path.dirname(path)
files = os.listdir(dir)
for file in files:
if file.lower().endswith(".jpg"):
original = file
file = file.lower()
if file.find("cover") >= 0:
return os.path.join(dir, original)
if file.find("face") >= 0:
return os.path.join(dir, original)
if file.find("front") >= 0:
return os.path.join(dir, original)
if file.find("case") >= 0:
return os.path.join(dir, original)
"""return any"""
return os.path.join(dir, original)
return None
| Python |
import gtk
def is_double_click(event):
if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: #@UndefinedVariable
return True
else:
return False
def is_double_left_click(event):
if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: #@UndefinedVariable
return True
else:
return False
def is_double_rigth_click(event):
if event.button == 3 and event.type == gtk.gdk._2BUTTON_PRESS: #@UndefinedVariable
return True
else:
return False
def is_rigth_click(event):
if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3: #@UndefinedVariable
return True
else:
return False
def is_left_click(event):
if event.type == gtk.gdk.BUTTON_PRESS and event.button == 1: #@UndefinedVariable
return True
else:
return False
def is_middle_click(event):
return is_mouse_click(event)
def is_mouse_click(event):
if event.type == gtk.gdk.BUTTON_PRESS and event.button == 2: #@UndefinedVariable
return True
else:
return False
| Python |
#-*- coding: utf-8 -*-
'''
Created on 30 авг. 2010
@author: ivan
'''
ORDER_LINEAR = "ORDER_LINEAR"
ORDER_SHUFFLE = "ORDER_SHUFFLE"
ORDER_RANDOM = "ORDER_RANDOM"
LOPPING_LOOP_ALL = "LOPPING_LOOP_ALL"
LOPPING_SINGLE = "LOPPING_SINGLE"
LOPPING_DONT_LOOP = "LOPPING_DONT_LOOP"
ON_CLOSE_CLOSE = "ON_CLOSE_CLOSE"
ON_CLOSE_HIDE = "ON_CLOSE_HIDE"
ON_CLOSE_MINIMIZE = "ON_CLOSE_MINIMIZE"
PLAYLIST_PLAIN = "PLAYLIST_PLAIN"
PLAYLIST_TREE = "PLAYLIST_TREE" | Python |
import commands
import os
import sys
class SingleInstance():
'''
SingleInstance - based on Windows version by Dragan Jovelic this is a Linux
version that accomplishes the same task: make sure that
only a single instance of an application is running.
'''
def __init__(self, pidPath="/tmp/foobnix.pid"):
'''
pidPath - full path/filename where pid for running application is to be
stored. Often this is ./var/<pgmname>.pid
'''
self.pidPath=pidPath
#
# See if pidFile exists
#
if os.path.exists(pidPath):
#
# Make sure it is not a "stale" pidFile
#
pid=open(pidPath, 'r').read().strip()
#
# Check list of running pids, if not running it is stale so
# overwrite
#
pidRunning=commands.getoutput('ls /proc | grep %s' % pid)
if pidRunning:
self.lasterror=True
else:
self.lasterror=False
else:
self.lasterror=False
if not self.lasterror:
#
# Write my pid into pidFile to keep multiple copies of program from
# running.
#
fp=open(pidPath, 'w')
fp.write(str(os.getpid()))
fp.close()
def alreadyrunning(self):
return self.lasterror
def __del__(self):
if not self.lasterror:
os.unlink(self.pidPath)
if __name__ == "__main__":
#
# do this at beginnig of your application
#
myapp = SingleInstance()
#
# check is another instance of same program running
#
if myapp.alreadyrunning():
sys.exit("Another instance of this program is already running")
#
# not running, safe to continue...
#
print "No another instance is running, can continue here" | Python |
#-*- coding: utf-8 -*-
'''
Created on 23 сент. 2010
@author: ivan
'''
import ConfigParser
class GlobalConfig():
def __init__(self):
config = ConfigParser.RawConfigParser()
config.read('foobnix.cfg')
| Python |
'''
Created on Feb 26, 2010
@author: ivan
'''
import sys
import platform
import logging
def init():
return None
LOG_FILENAME = '/tmp/foobnix.log'
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
logging.basicConfig(filename=LOG_FILENAME, level=logging.NOTSET)
def debug(*args):
init()
print "DEBUG:", args
logging.debug(args)
def info(*args):
init()
print "INFO:", args
logging.info(args)
def warn(*args):
init()
print "WARN:", args
logging.warn(args)
def error(*args):
init()
print >> sys.stderr, "ERROR", args
logging.error(args)
def print_debug_info():
init()
debug('*************** PLATFORM INFORMATION ************************')
debug('==Interpreter==')
debug('Version :', platform.python_version())
debug('Version tuple:', platform.python_version_tuple())
debug('Compiler :', platform.python_compiler())
debug('Build :', platform.python_build())
debug('==Platform==')
debug('Normal :', platform.platform())
debug('Aliased:', platform.platform(aliased=True))
debug('Terse :', platform.platform(terse=True))
debug('==Operating System and Hardware Info==')
debug('uname:', platform.uname())
debug('system :', platform.system())
debug('node :', platform.node())
debug('release :', platform.release())
debug('version :', platform.version())
debug('machine :', platform.machine())
debug('processor:', platform.processor())
debug('==Executable Architecture==')
debug('interpreter:', platform.architecture())
debug('/bin/ls :', platform.architecture('/bin/ls'))
debug('*******************************************************')
| Python |
'''
Created on Jul 27, 2010
@author: ivan
'''
import os
import ConfigParser
from foobnix.util import LOG
from foobnix.util.singleton import Singleton
class Config:
__metaclass__ = Singleton
FOOBNIX = "foobnix"
SUPPORTED_AUDIO_FORMATS = 'supported_audio_formats'
USER_DIR = os.getenv("HOME") or os.getenv('USERPROFILE')
CFG_LOCAL_FILE = USER_DIR + "/foobnix.cfg"
CFG_INSTALLED_FILE = USER_DIR + "/foobnix.cfg"
CFG_LOCAL_TEST_FILE = "../../foobnix.cfg"
def __init__(self):
self.config = None
if self.get_file_path():
self.config = ConfigParser.RawConfigParser()
self.config.read(self.get_file_path())
else:
LOG.error("Config file not found")
def get_file_path(self):
if os.path.isfile(self.CFG_LOCAL_FILE):
LOG.debug("Read local cfg file", self.CFG_LOCAL_FILE)
return self.CFG_LOCAL_FILE
elif os.path.isfile(self.CFG_INSTALLED_FILE):
LOG.debug("Read installed cfg file", self.CFG_INSTALLED_FILE)
return self.CFG_INSTALLED_FILE
elif os.path.isfile(self.CFG_LOCAL_TEST_FILE):
LOG.debug("Read local cfg file from test", self.CFG_LOCAL_TEST_FILE)
return self.CFG_LOCAL_TEST_FILE
else:
LOG.debug("Config file not found")
return None
def get(self, type):
if self.config:
LOG.debug("Get cfg value for", type)
return self.config.get(self.FOOBNIX, type)
else:
return None
def test():
print Config().get(Config.SUPPORTED_AUDIO_FORMATS)
print Config().get(Config.SUPPORTED_AUDIO_FORMATS)
print Config().get(Config.SUPPORTED_AUDIO_FORMATS)
test()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 1 сент. 2010
@author: ivan
'''
import urllib2
from foobnix.util.configuration import FConfiguration
from foobnix.util import LOG
class ProxyPasswordMgr:
def __init__(self):
self.user = self.passwd = None
def add_password(self, realm, uri, user, passwd):
self.user = user
self.passwd = passwd
def find_user_password(self, realm, authuri):
return self.user, self.passwd
def set_proxy_settings():
if FConfiguration().proxy_enable and FConfiguration().proxy_url:
#http://spys.ru/proxylist/
proxy = FConfiguration().proxy_url
user = FConfiguration().proxy_user
password = FConfiguration().proxy_password
LOG.info("Proxy enable:", proxy, user, password)
proxy = urllib2.ProxyHandler({"http" : proxy})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler(ProxyPasswordMgr())
proxy_auth_handler.add_password(None, None, user, password)
opener = urllib2.build_opener(proxy, proxy_auth_handler)
urllib2.install_opener(opener)
else:
LOG.info("Proxy not enable")
| Python |
'''
Created on Feb 26, 2010
@author: ivan
'''
import os
def isDirectory(path):
return os.path.isdir(path)
def get_file_extenstion(fileName):
return os.path.splitext(fileName)[1].lower()
def file_extenstion(file_name):
return os.path.splitext(file_name)[1].lower()
| Python |
#-*- coding: utf-8 -*-
'''
Created on 27 сент. 2010
@author: ivan
'''
import thread
from threading import Lock
from foobnix.util import LOG
import time
class SingreThread():
def __init__(self, progressbar):
self.lock = Lock()
self.progressbar = progressbar
def run(self, method, args=None):
if not self.lock.locked():
self.lock.acquire()
thread.start_new_thread(self.thread_task, (method, args,))
else:
LOG.warn("Thread not finished", method, args)
def run_with_text(self, method, args, text):
self.progressbar.start(text)
self.run(method, args)
def thread_task(self, method, args):
try:
if args:
method(args)
else:
method()
time.sleep(0.1)
except Exception, e:
LOG.error(e)
finally:
self.progressbar.stop()
self.lock.release()
| Python |
'''
Created on Feb 26, 2010
@author: ivan
'''
def convert_ns(time_int):
time_int = time_int / 1000000000
time_str = ""
if time_int >= 3600:
_hours = time_int / 3600
time_int = time_int - (_hours * 3600)
time_str = str(_hours) + ":"
if time_int >= 600:
_mins = time_int / 60
time_int = time_int - (_mins * 60)
time_str = time_str + str(_mins) + ":"
elif time_int >= 60:
_mins = time_int / 60
time_int = time_int - (_mins * 60)
time_str = time_str + "0" + str(_mins) + ":"
else:
time_str = time_str + "00:"
if time_int > 9:
time_str = time_str + str(time_int)
else:
time_str = time_str + "0" + str(time_int)
return time_str
def convert_seconds_to_text(time_sec):
time_sec = int(time_sec)
time_str = ""
if time_sec >= 3600:
_hours = time_sec / 3600
time_sec = time_sec - (_hours * 3600)
time_str = str(_hours) + ":"
if time_sec >= 600:
_mins = time_sec / 60
time_sec = time_sec - (_mins * 60)
time_str = time_str + str(_mins) + ":"
elif time_sec >= 60:
_mins = time_sec / 60
time_sec = time_sec - (_mins * 60)
time_str = time_str + "0" + str(_mins) + ":"
else:
time_str = time_str + "00:"
if time_sec > 9:
time_str = time_str + str(time_sec)
else:
time_str = time_str + "0" + str(time_sec)
return time_str
def normilize_time(length):
if length < 0:
return 0
length = int(length)
result = ""
hour = int(length / 60 / 60)
if hour:
if hour < 10:
hour = "0" + str(hour)
result = str(hour) + ":"
min = int(length / 60) - int(hour) * 60
if min:
if min < 10:
min = "0" + str(min)
result += str(min) + ":"
else:
result += "00:"
sec = length - int(min) * 60 - int(hour) * 3600
if sec < 10:
sec = "0" + str(sec)
result += str(sec)
return result
| Python |
#-*- coding: utf-8 -*-
'''
Created on 23 сент. 2010
@author: ivan
'''
import pickle
from foobnix.util import LOG, const
import os
from foobnix.util.singleton import Singleton
"""Foobnix configuration"""
class FC:
__metaclass__ = Singleton
API_KEY = "bca6866edc9bdcec8d5e8c32f709bea1"
API_SECRET = "800adaf46e237805a4ec2a81404b3ff2"
LASTFM_USER = "l_user_"
LASTFM_PASSWORD = "l_pass_"
def __init__(self):
"""init default values"""
self.is_view_info_panel = True
self.is_view_search_panel = True
self.is_view_music_tree_panel = True
self.is_view_lyric_panel = True
self.is_order_random = False
self.lopping = const.LOPPING_LOOP_ALL
self.playlist_type = const.PLAYLIST_TREE
"""player controls"""
self.volume = 10
"""tabs"""
self.len_of_tab = 30
self.tab_close_element = "label"
self.count_of_tabs = 5
"""main window controls"""
self.main_window_size = [119, 154, 884, 479]
self.hpaned_left = 248;
self.hpaned_right = 320;
self.vpaned_small = 100;
"""main window action"""
self.on_close_window = const.ON_CLOSE_HIDE
"""support file formats"""
self.last_music_path = None
self.music_paths = ["/tmp"]
self.support_formats = [".mp3", ".ogg", ".ape", ".flac", ".wma", ".cue", ".mpc", ".aiff", ".raw", ".au", ".aac", ".mp4", ".ra", ".m4p", ".3gp" ]
self.cache_music_tree_beans = []
"""last fm"""
self.lfm_login = self.LASTFM_USER
self.lfm_password = self.LASTFM_PASSWORD
"""vk"""
self.vk_login = "c891888@bofthew.com"
self.vk_password = "c891888"
self.vk_cookie = None
"""proxy"""
self.proxy_enable = False
self.proxy_url = None
"""try icon"""
self.show_tray_icon = True
"""download manager controls"""
self.dm_window_size = [119, 154, 200, 200]
self = self._load();
def save(self):
FCHelper().save(self)
def _load(self):
"""restore from file"""
object = FCHelper().load()
if object:
dict = object.__dict__
keys = self.__dict__.keys()
for i in dict:
try:
if i in keys:
setattr(self, i, dict[i])
except Exception, e:
LOG.warn("Value not found", e)
return False
return True
def info(self):
FCHelper().print_info(self)
def delete(self):
FCHelper().delete()
CONFIG_FILE = "/tmp/foobnix.pkl"
class FCHelper():
def __init__(self):
pass
def save(self, object):
save_file = file(CONFIG_FILE, 'w')
try:
pickle.dump(object, save_file)
except Exception, e:
LOG.error("Erorr dumping pickle conf", e)
save_file.close()
LOG.debug("Config save")
self.print_info(object);
def load(self):
if not os.path.exists(CONFIG_FILE):
LOG.warn("Config file not found", CONFIG_FILE)
return None
with file(CONFIG_FILE, 'r') as load_file:
try:
load_file = file(CONFIG_FILE, 'r')
pickled = load_file.read()
object = pickle.loads(pickled)
LOG.debug("Config loaded")
self.print_info(object);
return object
except Exception, e:
LOG.error("Error laod config", e)
return None
def delete(self):
if os.path.exists(CONFIG_FILE):
os.remove(CONFIG_FILE)
def print_info(self, object):
dict = object.__dict__
for i in object.__dict__:
LOG.debug(i, str(dict[i])[:500]);
"""""
class A():
def __init__(self):
line = [1,2,3]
a = A()
setattr(a, "line", [3, 2, 1])
print a.line
"""""
| Python |
'''
Created on Jul 27, 2010
@author: ivan
'''
class Singleton(type):
def __call__(self, *args, **kw):
if self.instance is None:
self.instance = super(Singleton, self).__call__(*args, **kw)
return self.instance
def __init__(self, name, bases, dict):
super(Singleton, self).__init__(name, bases, dict)
self.instance = None | Python |
#-*- coding: utf-8 -*-
'''
Created on 28 сент. 2010
@author: anton.komolov
'''
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from foobnix.util.configuration import get_version
DBusGMainLoop(set_as_default=True)
DBUS_NAME = "org.mpris.foobnix"
DBUS_OBJECT_PATH = "/FoobnixObject"
MPRIS_ROOT_PATH = "/"
MPRIS_PLAYER_PATH = "/Player"
MPRIS_TRACKLIST_PATH = "/TrackList"
DBUS_MAIN_INTERFACE = 'org.mpris.foobnix'
DBUS_MEDIAPLAYER_INTERFACE = 'org.freedesktop.MediaPlayer'
class MprisRoot(dbus.service.Object):
def __init__(self, interface, object_path=MPRIS_ROOT_PATH):
self.interface = interface
dbus.service.Object.__init__(self, dbus.SessionBus(), object_path)
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='s')
def Identity(self):
return "foobnix %s" % get_version()
@dbus.service.method (DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='(qq)')
def MprisVersion (self):
return (1, 0)
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Quit(self):
self.interface.app.exit()
class MprisPlayer(dbus.service.Object):
def __init__(self, interface, object_path=MPRIS_PLAYER_PATH):
self.interface = interface
dbus.service.Object.__init__(self, dbus.SessionBus(), object_path)
#Next ( )
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Next(self):
self.interface.app.action_command(['--next'])
#Prev ( )
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Prev(self):
self.interface.app.action_command(['--prev'])
#Pause ( )
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Pause(self):
self.interface.app.action_command(['--pause'])
#Stop ( )
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Stop(self):
self.interface.app.action_command(['--stop'])
#Play ( )
@dbus.service.method(DBUS_MEDIAPLAYER_INTERFACE, in_signature='', out_signature='')
def Play(self):
self.interface.app.action_command(['--play'])
#TODO
#Repeat ( b: State )
"""State − b
TRUE to repeat the current track, FALSE to stop repeating."""
#GetStatus ( ) → (iiii)
"""Return the status of media player as a struct of 4 ints.
Returns
Status − (iiii) (Status_Struct)
Status_Struct − ( i: Playback_State, i: Shuffle_State, i: Repeat_Current_State, i: Endless_State )
Playback_State − i
0 = Playing, 1 = Paused, 2 = Stopped.
Shuffle_State − i
0 = Playing linearly, 1 = Playing randomly.
Repeat_Current_State − i
0 = Go to the next element once the current has finished playing, 1 = Repeat the current element.
Endless_State − i
0 = Stop playing once the last element has been played, 1 = Never give up playing"""
#GetMetadata ( ) → a{sv}
"""Gives all meta data available for the currently played element.
Guidelines for field names are at http://wiki.xmms2.xmms.se/wiki/MPRIS_Metadata .
Returns Metadata − a{sv} (String_Variant_Map)"""
#GetCaps ( ) → i
"""Return the "media player"'s current capabilities.
Returns Capabilities − i (Caps_Flags)"""
#VolumeSet ( i: Volume )
#VolumeGet ( ) → i
#PositionSet ( i: Position )
"""Track position between [0;<track_length>] in ms."""
#PositionGet ( ) → i
"""Track position between [0;<track_length>] in ms."""
#Signals:
#TrackChange ( a{sv}: Metadata )
#StatusChange ( (iiii): Status )
#CapsChange ( i: Capabilities )
class DBusManager(dbus.service.Object):
def __init__(self, interface, object_path=DBUS_OBJECT_PATH):
self.interface = interface
self.bus = dbus.SessionBus()
bus_name = dbus.service.BusName(DBUS_NAME, bus=self.bus)
dbus.service.Object.__init__(self, bus_name, object_path)
MprisRoot(interface)
MprisPlayer(interface)
try:
dbus_interface = 'org.gnome.SettingsDaemon.MediaKeys'
mm_object = bus.get_object('org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys')
mm_object.GrabMediaPlayerKeys("MyMultimediaThingy", 0, dbus_interface=dbus_interface)
mm_object.connect_to_signal('MediaPlayerKeyPressed', self.on_mediakey)
except Exception, e:
print "your OS is not GNOME", e
@dbus.service.method(DBUS_MAIN_INTERFACE, in_signature='', out_signature='')
def interactive_play_args(self, args):
print "manager recive", args
self.interface.play_args(args)
def on_mediakey(self, comes_from, what):
"""
gets called when multimedia keys are pressed down.
"""
if what in ['Stop', 'Play', 'Next', 'Previous']:
if what == 'Stop':
thread.start_new_thread(os.system, ("foobnix --stop",))
elif what == 'Play':
thread.start_new_thread(os.system, ("foobnix --play-pause",))
elif what == 'Next':
thread.start_new_thread(os.system, ("foobnix --next",))
elif what == 'Previous':
thread.start_new_thread(os.system, ("foobnix --prev",))
else:
print ('Got a multimedia key...')
def getFoobnixDBusInterface():
bus = dbus.SessionBus()
dbus_objects = dbus.Interface(bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus'), 'org.freedesktop.DBus').ListNames()
if not DBUS_NAME in dbus_objects:
return None
else:
return dbus.Interface(bus.get_object(DBUS_NAME, DBUS_OBJECT_PATH), DBUS_MAIN_INTERFACE)
| Python |
'''
Created on Mar 3, 2010
@author: ivan
'''
import urllib2
from foobnix.util import LOG
"Get content of the url"
def get_content(url):
if not url:
return None
try:
connect = urllib2.urlopen(url)
data = connect.read()
return data
except:
LOG.error("INCORRECT URL ERROR .... ", url)
return None
def getStationPath(url):
print "get station"
if not url:
return None
_file_url = url
urls = []
try:
connect = urllib2.urlopen(url)
data = connect.read()
urls = getStations(data, urls)
except:
print "INCORRECT URL ERROR .... ", url
if urls:
return urls[0]
def getStations(data, urls):
for line in data.rsplit():
line = line.lower()
if line.startswith("file"):
index = line.find("=")
url = line[index + 1 : ]
print url
urls.append(url)
return urls
def get_radio_source(url):
if url:
if url.lower().endswith(".pls"):
source_url = getStationPath(url)
LOG.info("Radio content", source_url)
if source_url :
LOG.info("Radio url", source_url)
return source_url
elif url.lower().endswith(".m3u"):
content = get_content(url)
LOG.info("Radio content", content)
if not content:
return None
for line in content.rsplit():
if line.startswith("http://"):
LOG.info("Radio url", line)
return line
LOG.info("Radio url", url)
return url
def getPlsName(_file_url):
index = _file_url.rfind("/")
return _file_url[index + 1:]
def getFirst(self, urls):
if urls:
return urls[0]
else:
return None
| Python |
#-*- coding: utf-8 -*-
'''
Created on 24 2010
@author: ivan
'''
import gettext
APP_NAME = "foobnix"
gettext.install(APP_NAME, unicode=True)
gettext.textdomain(APP_NAME)
| Python |
# -*- coding: utf-8 -*-
'''
Created on Feb 27, 2010
@author: ivan
'''
from __future__ import with_statement
import os
from foobnix.util.singleton import Singleton
import tempfile
from foobnix.util import const, LOG
import gtk
import pickle
import uuid
import random
FOOBNIX_TMP = "/usr/share/foobnix"
FOOBNIX_TMP_RADIO = os.path.join(FOOBNIX_TMP, "radio")
FOOBNIX_VERSION_FILE_NAME = "version"
USER_DIR = os.getenv("HOME") or os.getenv('USERPROFILE')
CFG_FILE_DIR = os.path.join(USER_DIR, ".config/foobnix")
CFG_FILE = os.path.join(CFG_FILE_DIR, "foobnix_conf.pkl")
"""get last version from file"""
def get_version():
result = "A"
version_file = None
if os.path.exists(os.path.join(FOOBNIX_TMP, FOOBNIX_VERSION_FILE_NAME)):
version_file = os.path.join(FOOBNIX_TMP, FOOBNIX_VERSION_FILE_NAME)
elif os.path.exists(FOOBNIX_VERSION_FILE_NAME):
version_file = os.path.join(FOOBNIX_VERSION_FILE_NAME)
with file(version_file, 'r') as v_file:
for line in v_file:
line = str(line).strip()
if line.find("VERSION=") >= 0:
result = line[len("VERSION="):]
elif line.find("RELEASE=") >= 0:
result += "-" + line[len("RELEASE="):]
return result
VERSION = get_version()
def check_create_cfg_dir():
if not os.path.exists(CFG_FILE_DIR):
os.makedirs(CFG_FILE_DIR)
def get_random_vk():
vks = {
"c891888@bofthew.com":"c891888",
"c892009@bofthew.com":"c892009",
"c892406@bofthew.com":"c892406",
"c892588@bofthew.com":"c892588"
}
rand = random.randint(0,len(vks)-1)
key = vks.keys()[rand]
value = vks[key]
return key, value
class FConfiguration:
FOOBNIX = "foobnix"
SUPPORTED_AUDIO_FORMATS = 'supported_audio_formats'
__metaclass__ = Singleton
#config = ConfigParser.RawConfigParser()
#config.read(CFG_FILE)
#def get(self, type):
# return self.config.get(self.FOOBNIX, self.SUPPORTED_AUDIO_FORMATS)
check_create_cfg_dir()
def __init__(self, is_load_file=True):
self.media_library_path = [tempfile.gettempdir()]
self.onlineMusicPath = tempfile.gettempdir()
self.supportTypes = [".mp3", ".ogg", ".ape", ".flac", ".wma", ".cue", ".mpc", ".aiff", ".raw", ".au", ".aac", ".mp4", ".ra", ".m4p", ".3gp" ]
self.isRandom = False
self.isRepeat = True
self.isPlayOnStart = False
self.savedPlayList = []
self.savedRadioList = []
self.savedSongIndex = 0
self.volumeValue = 50.0
self.vpanelPostition = 234
self.hpanelPostition = 370
self.hpanel2Postition = 521
### view panels ###
self.view_tree_panel = True
self.view_search_panel = True
self.view_info_panel = False
self.view_lyric_panel = False
self.playlistState = None
self.radiolistState = None
self.virtualListState = {"Default list" : []}
self.is_save_online = False
self.song_source_relevance_algorithm = 0
self.online_tab_show_by = 0
vk = get_random_vk()
self.vk_login = vk[0]
self.vk_password = vk[1]
self.lfm_user_default = "l_user_"
self.lfm_login = self.lfm_user_default
self.lfm_password = "l_pass_"
self.API_KEY = "bca6866edc9bdcec8d5e8c32f709bea1"
self.API_SECRET = "800adaf46e237805a4ec2a81404b3ff2"
self.cookie = None
self.count_of_tabs = 3
self.len_of_tab = 30
self.cache_music_beans = []
self.tab_position = "top"
self.last_dir = None
self.on_close_window = const.ON_CLOSE_HIDE;
self.show_tray_icon = True
self.proxy_enable = False
self.proxy_url = None
self.proxy_user = None
self.proxy_password = None
"""info panel"""
if gtk.gdk.screen_height() < 800:
self.info_panel_image_size = 150
else:
self.info_panel_image_size = 200
self.tab_close_element = "label"
self.play_ordering = const.ORDER_LINEAR
self.play_looping = const.LOPPING_LOOP_ALL
"""random uuis of player"""
self.uuid = uuid.uuid4().hex
self.check_new_version = True
self.add_child_folders = True
self.lyric_panel_image_size = 250
self.tray_icon_auto_hide = True
self.action_hotkey = {'foobnix --volume-up': '<SUPER>Up', 'foobnix --volume-down': '<SUPER>Down', 'foobnix --show-hide': '<SUPER>a', 'foobnix --prev': '<SUPER>Left', 'foobnix --play': '<SUPER>x', 'foobnix --pause': '<SUPER>z', 'foobnix --next': '<SUPER>Right'}
self.last_notebook_page = "Foobnix"
self.last_notebook_beans = []
self.last_play_bean = 0
self.save_tabs = True
self.play_on_start = True
self.configure_state = None
self.enable_music_srobbler = False
self.enable_radio_srobbler = False
instance = self._loadCfgFromFile(is_load_file)
if instance:
try:
self.supportTypes = instance.supportTypes
self.virtualListState = instance.virtualListState
self.playlistState = instance.playlistState
self.radiolistState = instance.radiolistState
self.media_library_path = instance.media_library_path
self.isRandom = instance.isRandom
self.isRepeat = instance.isRepeat
self.isPlayOnStart = instance.isPlayOnStart
self.savedPlayList = instance.savedPlayList
self.savedSongIndex = instance.savedSongIndex
self.volumeValue = instance.volumeValue
self.vpanelPostition = instance.vpanelPostition
self.hpanelPostition = instance.hpanelPostition
self.hpanel2Postition = instance.hpanel2Postition
self.savedRadioList = instance.savedRadioList
self.is_save_online = instance.is_save_online
self.onlineMusicPath = instance.onlineMusicPath
self.vk_login = instance.vk_login
self.vk_password = instance.vk_password
self.lfm_login = instance.lfm_login
self.lfm_password = instance.lfm_password
self.count_of_tabs = instance.count_of_tabs
self.len_of_tab = instance.len_of_tab
self.cookie = instance.cookie
self.view_tree_panel = instance.view_tree_panel
self.view_search_panel = instance.view_search_panel
self.view_info_panel = instance.view_info_panel
self.view_lyric_panel = instance.view_lyric_panel
self.cache_music_beans = instance.cache_music_beans
self.tab_position = instance.tab_position
self.last_dir = instance.last_dir
self.info_panel_image_size = instance.info_panel_image_size
self.tab_close_element = instance.tab_close_element
self.play_ordering = instance.play_ordering
self.play_looping = instance.play_looping
self.on_close_window = instance.on_close_window;
self.show_tray_icon = instance.show_tray_icon
"proxy"
self.proxy_enable = instance.proxy_enable
self.proxy_url = instance.proxy_url
self.proxy_user = instance.proxy_user
self.proxy_password = instance.proxy_password
self.uuid = instance.uuid
self.check_new_version = instance.check_new_version
self.add_child_folders = instance.add_child_folders
self.lyric_panel_image_size = instance.lyric_panel_image_size
self.action_hotkey = instance.action_hotkey
self.tray_icon_auto_hide = instance.tray_icon_auto_hide
self.last_notebook_page = instance.last_notebook_page
self.last_notebook_beans = instance.last_notebook_beans
self.play_on_start = instance.play_on_start
self.save_tabs = instance.save_tabs
self.last_play_bean = instance.last_play_bean
self.configure_state = instance.configure_state
self.enable_music_srobbler = instance.enable_music_srobbler
self.enable_radio_srobbler = instance.enable_radio_srobbler
except AttributeError:
LOG.debug("Configuraton attributes are changed")
os.remove(CFG_FILE)
LOG.info("LOAD CONFIGS")
self.printArttibutes()
def save(self):
LOG.info("SAVE CONFIGS")
self.printArttibutes()
FConfiguration()._saveCfgToFile()
def printArttibutes(self):
for i in dir(self):
if not i.startswith("__"):
value = str(getattr(self, i))[:300]
LOG.info(i, value)
def _saveCfgToFile(self):
#conf = FConfiguration()
save_file = file(CFG_FILE, 'w')
try:
pickle.dump(self, save_file)
except:
LOG.error("Erorr dumping pickle conf")
save_file.close()
LOG.debug("Save configuration")
def remove_cfg_file(self):
if os.path.isfile(CFG_FILE):
os.remove(CFG_FILE)
def _loadCfgFromFile(self, is_load_file):
if not is_load_file:
return
try:
with file(CFG_FILE, 'r') as load_file:
load_file = file(CFG_FILE, 'r')
pickled = load_file.read()
# fixing mistyped 'configuration' package name
if 'confguration' in pickled:
pickled = pickled.replace('confguration', 'configuration')
return pickle.loads(pickled)
except IOError:
LOG.debug('Configuration file does not exist.')
except ImportError, ex:
LOG.error('Configuration file is corrupted. Removing it...')
os.remove(CFG_FILE)
except BaseException, ex:
LOG.error('Unexpected exception of type %s: "%s".' % (ex.__class__.__name__, ex))
| Python |
#-*- coding: utf-8 -*-
'''
Created on Sep 8, 2010
@author: ivan
'''
import gtk
from foobnix.regui.model.signal import FControl
def label():
label = gtk.Label("–")
label.show()
return label
def empty():
label = gtk.Label(" ")
label.show()
return label
def text(text):
label = gtk.Label(text)
label.show()
return label
class EQContols(gtk.Window, FControl):
def top_row(self):
box = gtk.HBox(False, 0)
box.show()
on = gtk.ToggleButton("On")
#on.set_size_request(30,-1)
on.show()
auto = gtk.ToggleButton("Auto")
#auto.set_size_request(50,-1)
auto.show()
empt = empty()
empt.set_size_request(65, -1)
#auto.set_size_request(50,-1)
auto.show()
combo = gtk.combo_box_entry_new_text()
combo.append_text("Will be soon....")
combo.set_active(0)
#combo = gtk.ComboBoxEntry()
combo.set_size_request(240, -1)
combo.show()
save = gtk.Button("Save")
save.show()
box.pack_start(on, False, False, 0)
box.pack_start(auto, False, True, 0)
box.pack_start(empt, False, True, 0)
box.pack_start(combo, False, True, 0)
box.pack_start(save, False, True, 0)
return box
def dash_line(self):
lables = gtk.VBox(False, 0)
lables.show()
lables.pack_start(label(), False, False, 0)
lables.pack_start(label(), True, False, 0)
lables.pack_start(label(), False, False, 0)
lables.pack_start(empty(), False, False, 0)
return lables
def db_line(self):
lables = gtk.VBox(False, 0)
lables.show()
lables.pack_start(text("+12db"), False, False, 0)
lables.pack_start(text("+0db"), True, False, 0)
lables.pack_start(text("-12db"), False, False, 0)
lables.pack_start(empty(), False, False, 0)
return lables
def empty_line(self):
lables = gtk.VBox(False, 0)
lables.show()
lables.pack_start(empty(), False, False, 0)
lables.pack_start(empty(), True, False, 0)
lables.pack_start(empty(), False, False, 0)
lables.pack_start(empty(), False, False, 0)
return lables
def equlalizer_line(self, text):
vbox = gtk.VBox(False, 0)
vbox.show()
adjustment = gtk.Adjustment(value=0, lower= -12, upper=12, step_incr=1, page_incr=2, page_size=0)
scale = gtk.VScale(adjustment)
scale.set_size_request(-1, 140)
scale.set_draw_value(False)
scale.set_inverted(True)
scale.show()
"""text under"""
text = gtk.Label(text)
text.show()
vbox.pack_start(scale, False, False, 0)
vbox.pack_start(text, False, False, 0)
return vbox
def middle_lines(self):
lines = gtk.HBox(False, 0)
lines.show()
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("PREAMP"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.empty_line(), False, False, 0)
lines.pack_start(self.db_line(), False, False, 0)
lines.pack_start(self.empty_line(), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("29"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("59"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("119"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("237"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("474"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("1K"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("2K"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("4K"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("8K"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.equlalizer_line("15K"), False, False, 0)
lines.pack_start(self.dash_line(), False, False, 0)
lines.pack_start(self.empty_line(), False, False, 0)
return lines
def __init__(self, controls):
FControl.__init__(self, controls)
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
self.set_title("Equalizer")
self.set_position(gtk.WIN_POS_CENTER)
self.set_resizable(False)
self.connect("delete-event", self.hide_window)
lbox = gtk.VBox(False, 0)
lbox.show()
lbox.pack_start(self.top_row(), False, False, 0)
lbox.pack_start(self.middle_lines(), False, False, 0)
self.add(lbox)
def destroy(self):
self.hide()
return True
def show(self):
self.show_all()
def hide_window(self, *a):
self.hide()
return True
if __name__ == '__main__':
eq = EQContols(None)
eq.connect("destroy", lambda * a:gtk.main_quit())
eq.show()
gtk.main()
| Python |
'''
Created on Apr 19, 2010
@author: matik
'''
from gobject import GObject, type_register, signal_new #@UnresolvedImport
import gobject
SIGNAL_RUN_FIRST = gobject.SIGNAL_RUN_FIRST #@UndefinedVariable
TYPE_NONE = gobject.TYPE_NONE
TYPE_PYOBJECT = gobject.TYPE_PYOBJECT
class BaseController(GObject):
def __init__(self):
self.__gobject_init__()
type_register(self.__class__)
| Python |
'''
Created on 20.04.2010
@author: ivan
'''
import gtk
"""Base list controller for similar functional on any listview or treeview"""
class BaseListController():
POSITION_NAME = 0
def __init__(self, widget):
self.widget = widget
self.model = gtk.ListStore(str)
self.title = None
self.column = gtk.TreeViewColumn(self.title, gtk.CellRendererText(), text=0)
self.widget.append_column(self.column)
self.widget.set_model(self.model)
self.widget.connect("button-press-event", self.on_button_press)
self.widget.connect("drag-end", self.__on_drag_end)
def set_title(self, title):
self.column.set_title(title)
def __on_drag_end(self, *args):
self.on_drag()
def on_button_press(self, w, e):
pass
def on_drag(self):
pass
def on_duble_click(self):
pass
def get_item_by_position(self, position):
return self.model[position][self.POSITION_NAME]
def get_all_items(self):
items = []
for item in self.model:
item = item[self.POSITION_NAME]
items.append(item)
return items
def get_selected_item(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
return self._get_item_by_iter(selected)
def _get_item_by_iter(self, iter):
if iter:
item_value = self.model.get_value(iter, self.POSITION_NAME)
return item_value
def add_item(self, value):
self.model.append([value])
def clear(self):
self.model.clear()
def remove_selected(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
model.remove(selected)
| Python |
# -*- coding: utf-8 -*-
'''
Created on Mar 11, 2010
@author: ivan
'''
from foobnix.lyric.lyr import get_lyrics
from foobnix.util import LOG, const
from foobnix.util.configuration import FConfiguration
from foobnix.online.google.translate import translate
from foobnix.util.mouse_utils import is_double_click
import time
import gtk
class PlayerWidgetsCntl():
'''
'''
def scroll_event(self, button, event):
volume = self.volume.get_value()
if event.direction == gtk.gdk.SCROLL_UP:
self.volume.set_value(volume + 1)
else:
self.volume.set_value(volume - 1)
self.playerCntr.setVolume(volume / 100)
return True
def __init__(self, gxMain, playerCntr):
self.playerCntr = playerCntr
self.gxMain = gxMain
self.volume = gxMain.get_widget("volume_hscale")
self.volume.connect("change-value", self.onVolumeChange)
self.volume.connect("scroll-event", self.scroll_event)
self.seek = gxMain.get_widget("seek_eventbox")
self.seek.connect("button-press-event", self.onSeek)
self.seekBar = gxMain.get_widget("seek_progressbar")
self.timeLabel = gxMain.get_widget("seek_progressbar")
self.vpanel = gxMain.get_widget("vpaned1")
self.hpanel = gxMain.get_widget("hpaned1")
self.hpanel2 = gxMain.get_widget("hpaned2")
self.hpanel2.max_pos = False
#self.hpanel.connect("button-press-event", self.on_show_hide_paned);
#self.hpanel.set_property("position-set", True)
#self.hpanel2 = gxMain.get_widget("vpaned1")
#print "POSITION", self.hpanel2.get_position()
#self.lyric = gxMain.get_widget("lyric_textview")
#self.textbuffer = self.lyric.get_buffer()
#self.tr_lyric = gxMain.get_widget("translate_lyric_textview")
#self.tr_textbuffer = self.tr_lyric.get_buffer()
self.info_panel = gxMain.get_widget("info_frame")
self.search_panel = gxMain.get_widget("search_frame")
self.lyric_panel = gxMain.get_widget("lyric_frame")
self.view_tree_panel = gxMain.get_widget("view-left-navigation")
self.view_tree_panel.connect("toggled", self.show_tree_panel)
self.view_info_panel = gxMain.get_widget("view-info-panel")
self.view_info_panel.connect("toggled", self.show_info_panel)
self.view_search_panel = gxMain.get_widget("view-search-panel")
self.view_search_panel.connect("toggled", self.show_search_panel)
self.view_lyric_panel = gxMain.get_widget("view-lyric-panel")
self.view_lyric_panel.connect("toggled", self.show_lyric_panel)
"""playback menu"""
self.set_update_menu_item("linea_menu", "play_ordering", const.ORDER_LINEAR)
self.set_update_menu_item("random_menu", "play_ordering", const.ORDER_RANDOM)
self.set_update_menu_item("loop_all_menu", "play_looping", const.LOPPING_LOOP_ALL)
self.set_update_menu_item("loop_single_menu", "play_looping", const.LOPPING_SINGLE)
self.set_update_menu_item("dont_loop_menu", "play_looping", const.LOPPING_DONT_LOOP)
self.statusbar = gxMain.get_widget("statusbar")
navigationEvents = {
"on_play_button_clicked" :self.onPlayButton,
"on_stop_button_clicked" :self.onStopButton,
"on_pause_button_clicked" :self.onPauseButton,
"on_prev_button_clicked" :self.onPrevButton,
"on_next_button_clicked": self.onNextButton,
}
gxMain.signal_autoconnect(navigationEvents)
self.show_info_panel(None, FConfiguration().view_info_panel)
self.show_search_panel(None, FConfiguration().view_search_panel)
self.show_tree_panel(None, FConfiguration().view_tree_panel)
self.show_lyric_panel(None, FConfiguration().view_lyric_panel)
def set_update_menu_item(self, menu_item, conf_constant, value):
def set_value(a, b):
if a == "play_looping":
FConfiguration().play_looping = b
elif a == "play_ordering":
FConfiguration().play_ordering = b
liner = self.gxMain.get_widget(menu_item)
liner.connect("toggled", lambda * a: set_value(conf_constant, value))
if conf_constant == "play_ordering":
if FConfiguration().play_ordering == value:
liner.set_active(True)
elif conf_constant == "play_looping":
if FConfiguration().play_looping == value:
liner.set_active(True)
def show_info_panel(self, w, flag=True):
if w:
flag = w.get_active()
if flag:
self.lyric_panel.hide()
FConfiguration().view_lyric_panel = False
self.view_lyric_panel.set_active(False)
self.vpanel.set_position(FConfiguration().vpanelPostition)
self.hpanel2.set_position(FConfiguration().hpanel2Postition)
self.hpanel2.max_pos = False
self.info_panel.show()
else:
self.info_panel.hide()
if not FConfiguration().view_lyric_panel:
self.hpanel2.set_position(99999)
self.hpanel2.max_pos = True
else:
self.hpanel2.set_position(FConfiguration().hpanel2Postition)
self.hpanel2.max_pos = False
FConfiguration().view_info_panel = flag
self.view_info_panel.set_active(flag)
def show_search_panel(self, w, flag=True):
if w:
flag = w.get_active()
if flag:
self.search_panel.show()
else:
self.search_panel.hide()
FConfiguration().view_search_panel = flag
self.view_search_panel.set_active(flag)
def show_lyric_panel(self, w, flag=True):
if w:
flag = w.get_active()
if flag:
self.info_panel.hide()
FConfiguration().view_info_panel = False
self.view_info_panel.set_active(False)
self.hpanel2.set_position(FConfiguration().hpanel2Postition)
self.hpanel2.max_pos = False
self.lyric_panel.show()
else:
self.lyric_panel.hide()
if not FConfiguration().view_info_panel:
self.hpanel2.set_position(99999)
self.hpanel2.max_pos = True
else:
self.hpanel2.set_position(FConfiguration().hpanel2Postition)
self.hpanel2.max_pos = False
FConfiguration().view_lyric_panel = flag
self.view_lyric_panel.set_active(flag)
def show_tree_panel(self, w, flag=True):
if w:
flag = w.get_active()
if flag:
self.hpanel.set_position(FConfiguration().hpanelPostition)
else:
self.hpanel.set_position(0)
FConfiguration().view_tree_panel = flag
self.view_tree_panel.set_active(flag)
def on_show_hide_paned(self, w, e):
#TODO: Matik, could you view, this signal rise on any paned double click.
if is_double_click(e):
LOG.debug("double click", w)
if w.get_position() == 0:
self.on_full_view(w, e)
else:
self.on_compact_view(w, e)
time.sleep(0.2)
def setStatusText(self, text):
if text:
self.statusbar.push(0, text)
def setLiric(self, song):
pass
#thread.start_new_thread(self._setLiricThread, (song,))
def _setLiricThread(self, song):
self.tr_textbuffer.set_text("")
title = "" + song.getTitle()
for extension in FConfiguration().supportTypes:
if title.endswith(extension):
title = title.replace(extension, "")
break
LOG.info("Get lirics for:", song.getArtist(), title)
if song.getArtist() and song.getTitle():
try:
text = get_lyrics(song.getArtist(), title)
except:
self.setStatusText(_("Connection lyrics error"))
LOG.error("Connection lyrics error")
return None
if text:
header = " *** " + song.getArtist() + " - " + title + " *** "
self.textbuffer.set_text(header + "\n" + text)
LOG.info("try to translate")
text_tr = self.getTranstalted(text)
self.tr_textbuffer.set_text("*** " + song.getArtist() + " - " + title + " *** \n" + text_tr)
else:
self.textbuffer.set_text("Not Found lyrics for " + song.getArtist() + " - " + title + "\n")
def getTranstalted(self, text):
input = ""
result = ""
for line in text.rsplit("\n"):
line = line + "#";
input += line
res = translate(input, src="", to="ru")
for line in res.rsplit("#"):
result = result + line + "\n"
return result
def is_ascii(self, s):
return all(ord(c) < 128 for c in s)
def onPlayButton(self, *a):
self.playerCntr.playState()
def onStopButton(self, *a):
self.playerCntr.stopState()
def onPauseButton(self, *a):
self.playerCntr.pauseState()
def onPrevButton(self, *a):
self.playerCntr.prev()
def onNextButton(self, *a):
self.playerCntr.next()
def onSeek(self, widget, event):
if event.button == 1:
width = self.seek.allocation.width
x = event.x
seekValue = (x + 0.0) / width * 100
LOG.info(seekValue)
self.playerCntr.setSeek(seekValue);
def onVolumeChange(self, widget, obj3, volume):
self.playerCntr.setVolume(volume / 100)
pass # end of class
| Python |
'''
Created on Mar 11, 2010
@author: ivan
'''
import os
import gst
import gtk
import time
import urllib
import thread
from foobnix.util.time_utils import convert_ns
from foobnix.model.entity import CommonBean
from foobnix.util import LOG
from foobnix.base import BaseController
from foobnix.base import SIGNAL_RUN_FIRST, TYPE_NONE, TYPE_PYOBJECT
from foobnix.online.dowload_util import dowload_song_thread
from foobnix.util.plsparser import get_radio_source
from foobnix.util.configuration import FConfiguration
from foobnix.util.image_util import get_image_by_path
class PlayerController(BaseController):
MODE_RADIO = "RADIO"
MODE_PLAY_LIST = "PLAY_LIST"
MODE_ONLINE_LIST = "ONLINE_LIST"
__gsignals__ = {
'song_playback_started' : (SIGNAL_RUN_FIRST, TYPE_NONE, (TYPE_PYOBJECT,))
}
def __init__(self, last_fm_connector):
BaseController.__init__(self)
self.last_fm_scrobler = last_fm_connector
self.player = None
self.player = self.playerLocal()
self.songs = []
self.cIndex = 0
self.time_format = gst.Format(gst.FORMAT_TIME)
self.volume = 0
self.mode = self.MODE_PLAY_LIST
# TODO: rename playState() to play() and remove this hack
self.play = self.playState
self.pause = self.pauseState
self.erros = 0
self.prev_title = ""
self.prev_path = ""
def set_mode(self, mode):
self.mode = mode
def registerPlaylistCntr(self, playlistCntr):
self.playlistCntr = playlistCntr
def registerOnlineCntr(self, onlineCntr):
self.onlineCntr = onlineCntr
def registerWidgets(self, widgets):
self.widgets = widgets
count = 0
def playSong(self, song):
self.song = song
LOG.info("play song", song.name, song.getArtist(), song.getTitle())
if song.path != self.prev_path:
self.stopState()
if not song:
LOG.info("NULL song can't playing")
return
LOG.info("Path before", song.path)
#Try to set resource
LOG.info("Path after", song.path)
if song.path == None or song.path == "":
self.count += 1
LOG.info("SONG NOT FOUND", song.name)
LOG.info("Count is", self.count)
if self.count > 5:
return
return self.next()
self.count = 0
self.widgets.setLiric(song)
LOG.info("Type", song.type)
LOG.info("MODE", self.mode)
LOG.info("Name", song.name)
self.widgets.setStatusText("")
if song.type == CommonBean.TYPE_MUSIC_FILE:
if song.path != self.prev_path:
song.image = get_image_by_path(song.path)
self.prev_path = song.path
self.player = self.playerLocal()
uri = 'file://' + urllib.pathname2url(song.path)
if os.name == 'nt':
uri = 'file:' + urllib.pathname2url(song.path)
self.widgets.setStatusText(song.info)
self.player.set_property("uri", uri)
self.playerThreadId = thread.start_new_thread(self.playThread, (song,))
elif song.type == CommonBean.TYPE_RADIO_URL:
LOG.info("URL PLAYING", song.path)
path = get_radio_source(song.path)
self.get_player(path)
self.widgets.setStatusText(path)
self.widgets.seekBar.set_text("Url Playing...")
elif song.type == CommonBean.TYPE_MUSIC_URL:
LOG.info("URL PLAYING", song.path)
self.get_player(song.path)
#self.widgets.setStatusText(song.)
self.playerThreadId = thread.start_new_thread(self.playThread, (song,))
else:
self.widgets.seekBar.set_text("Error playing...")
return
self.playState()
print "SONG START", song.start_at
if song.start_at > 0:
self.set_seek_sec(song.start_at)
self.setVolume(self.volume)
self.onlineCntr.info.show_song_info(song)
self.emit('song_playback_started', song)
def get_player(self, path):
if FConfiguration().proxy_enable and FConfiguration().proxy_url:
LOG.info("=Proxy player=")
self.player = self.playerHTTP_Proxy()
self.player.get_by_name("source").set_property("location", path)
else:
LOG.info("=Local http player=")
self.player = self.playerHTTP()
self.player.set_property("uri", path)
def pauseState(self, *args):
self.player.set_state(gst.STATE_PAUSED)
def playState(self, *args):
self.player.set_state(gst.STATE_PLAYING)
def stopState(self):
if not self.player:
return None
self.setSeek(0.0)
self.widgets.seekBar.set_fraction(0.0)
self.widgets.seekBar.set_text("00:00 / 00:00")
self.playerThreadId = None
self.player.set_state(gst.STATE_NULL)
def volume_up(self, *args):
self.widgets.volume.set_value(self.getVolume() * 100)
self.setVolume(self.getVolume() + 0.05)
def volume_down(self, *args):
self.widgets.volume.set_value(self.getVolume() * 100)
self.setVolume(self.getVolume() - 0.05)
def setVolume(self, volumeValue):
self.volume = volumeValue
if FConfiguration().proxy_enable and self.player.get_by_name("volume"):
self.player.get_by_name("volume").set_property('volume', volumeValue + 0.0)
else:
self.player.set_property('volume', volumeValue + 0.0)
def getVolume(self):
if self.volume < 0:
return 0.05
if self.volume > 1.2:
return 1.2
return self.volume
def playerHTTP_Proxy(self):
self.stopState()
LOG.info("Proxy player")
self.playbin = gst.Pipeline("player")
source = gst.element_factory_make("souphttpsrc", "source")
source.set_property("user-agent", "Fooobnix music player")
source.set_property("automatic-redirect", "false")
source.set_property("proxy", FConfiguration().proxy_url)
if FConfiguration().proxy_user:
source.set_property("user-id", FConfiguration().proxy_user)
if FConfiguration().proxy_password:
source.set_property("user-pw", FConfiguration().proxy_password)
volume = gst.element_factory_make("volume", "volume")
#self.equ = gst.element_factory_make("equalizer-10bands")
mad = gst.element_factory_make("mad", "mad")
audioconvert = gst.element_factory_make("audioconvert", "audioconvert")
audioresample = gst.element_factory_make("audioresample", "audioresample")
alsasink = gst.element_factory_make("alsasink", "alsasink")
#self.playbin.add(source, mad, volume, audioconvert, self.equ,audioresample, alsasink)
#gst.element_link_many(source, mad, volume,audioconvert, self.equ,audioresample, alsasink)
self.playbin.add(source, mad, volume, audioconvert, audioresample, alsasink)
gst.element_link_many(source, mad, volume, audioconvert, audioresample, alsasink)
return self.playbin
def playerHTTP(self):
self.stopState()
LOG.info("Player For remote files")
self.playerThreadId = None
try:
self.player.set_state(gst.STATE_NULL)
except:
pass
self.player = None
self.playbin = gst.element_factory_make("playbin", "player")
bus = self.playbin.get_bus()
bus.add_signal_watch()
bus.connect("message", self.onBusMessage)
return self.playbin
def playerLocal(self):
self.stopState()
LOG.info("Player Local Files")
self.playerThreadId = None
try:
self.player.set_state(gst.STATE_NULL)
except:
pass
self.player = None
self.playbin = gst.element_factory_make("playbin2", "player")
bus = self.playbin.get_bus()
bus.add_signal_watch()
bus.connect("message", self.onBusMessage)
return self.playbin
def next(self, *args):
if self.mode == self.MODE_ONLINE_LIST:
song = self.onlineCntr.getNextSong()
else:
song = self.playlistCntr.getNextSong()
if song:
self.playSong(song)
def prev(self, *args):
if self.mode == self.MODE_ONLINE_LIST:
song = self.onlineCntr.getPrevSong()
else:
song = self.playlistCntr.getPrevSong()
self.playSong(song)
def _isStatusNull(self):
return self.player.get_state()[1] == gst.STATE_NULL
def is_state_playing(self):
return self.player.get_state()[1] == gst.STATE_PLAYING
def _get_state(self):
if self.player:
return self.player.get_state()[1]
else:
return None
def setSeek(self, persentValue):
if self._isStatusNull():
self.playerThreadId = None
return None
pos_max = 1
try:
pos_max = self.player.query_duration(self.time_format, None)[0]
except:
LOG.error("Seek for new position error")
if self.song and self.song.duration > 0:
pos_max = int(self.song.duration) * 1000000000
seek_ns = pos_max * persentValue / 100;
if self.song and self.song.duration > 0:
seek_ns = seek_ns + int(self.song.start_at) * 1000000000
LOG.info("SEC SEEK persent", seek_ns)
self.player.seek_simple(self.time_format, gst.SEEK_FLAG_FLUSH, seek_ns)
def set_seek_sec(self, sec):
if self._isStatusNull():
self.playerThreadId = None
return None
seek_ns = int(sec) * 1000000000 ;
LOG.info("SEC SEEK SEC", seek_ns)
self.player.seek_simple(self.time_format, gst.SEEK_FLAG_FLUSH, seek_ns)
def playThread(self, song=None):
LOG.info("Starts playing thread")
flag = True
is_scrobled = False
play_thread_id = self.playerThreadId
gtk.gdk.threads_enter()#@UndefinedVariable
self.widgets.seekBar.set_text("00:00 / 00:00")
gtk.gdk.threads_leave() #@UndefinedVariable
sec = 0;
count = 0
while play_thread_id == self.playerThreadId:
try:
song = self.song
LOG.info("Try")
time.sleep(0.2)
dur_int = self.player.query_duration(self.time_format, None)[0]
if song.duration > 0:
dur_int = int(song.duration) * 1000000000
duration_sec = dur_int / 1000000000
dur_str = convert_ns(dur_int)
gtk.gdk.threads_enter() #@UndefinedVariable
self.widgets.seekBar.set_text("00:00 / " + dur_str)
gtk.gdk.threads_leave() #@UndefinedVariable
break
except Exception, e:
LOG.info("Error",e)
time.sleep(1)
count += 1
if count > 6:
self.stopState()
self.playerThreadId = None
break;
time.sleep(0.5)
start_time = str(int(time.time()));
while play_thread_id == self.playerThreadId:
pos_int = 0
try:
song = self.song
dur_int = self.player.query_duration(self.time_format, None)[0]
if song.duration > 0:
dur_int = int(song.duration) * 1000000000
duration_sec = dur_int / 1000000000
dur_str = convert_ns(dur_int)
pos_int = self.player.query_position(self.time_format, None)[0]
except gst.QueryError:
LOG.info("QueryError error...")
if song.duration > 0:
pos_int = pos_int - int(song.start_at) * 1000000000
pos_str = convert_ns(pos_int)
if play_thread_id == self.playerThreadId:
gtk.gdk.threads_enter() #@UndefinedVariable
timeStr = pos_str + " / " + dur_str
timePersent = (pos_int + 0.0) / (dur_int)
self.widgets.seekBar.set_text(timeStr)
self.widgets.seekBar.set_fraction(timePersent)
gtk.gdk.threads_leave() #@UndefinedVariable
if self._get_state() != gst.STATE_PAUSED:
sec += 1
if song.duration > 0 and pos_int > (int(song.duration) - 2) * 1000000000:
self.next()
time.sleep(1)
#self.on_notify_components(sec, pos_int, flag, is_scrobled, duration_sec, timePersent, start_time)
if sec % 10 == 0:
#thread.start_new_thread(self.on_notify_components, (sec, pos_int, flag, is_scrobled, duration_sec, timePersent, start_time,))
"""report now playing song"""
if song.getArtist() and song.getTitle():
self.erros = 0
if self.last_fm_scrobler.get_scrobler() and FConfiguration().enable_music_srobbler:
LOG.info("Now playing...", song.getArtist(), song.getTitle())
thread.start_new_thread(self.last_fm_reporting_thread, (song,))
#last_fm_scrobler.report_now_playing(song.getArtist(), song.getTitle())
"Download only if you listen this music"
if flag and song.type == CommonBean.TYPE_MUSIC_URL and timePersent > 0.35:
flag = False
dowload_song_thread(song)
if not is_scrobled and (sec >= duration_sec / 2 or (sec >= 45 and timePersent >= 0.9)):
is_scrobled = True
if song.getArtist() and song.getTitle():
try:
if self.last_fm_scrobler.get_scrobler() and FConfiguration().enable_music_srobbler:
self.last_fm_scrobler.get_scrobler().scrobble(song.getArtist(), song.getTitle(), start_time, "P", "", duration_sec)
LOG.debug("Song Successfully scrobbled", song.getArtist(), song.getTitle())
except:
LOG.error("Error reporting scobling", song.getArtist(), song.getTitle())
def last_fm_reporting_thread(self, song):
try:
self.last_fm_scrobler.get_scrobler().report_now_playing(song.getArtist(), song.getTitle())
except:
LOG.error("Error reporting now playing last.fm", song.getArtist(), song.getTitle())
def onBusMessage(self, bus, message):
#LOG.info(message
"""Show radio info"""
type = message.type
if self.song.type == CommonBean.TYPE_RADIO_URL and type == gst.MESSAGE_TAG and message.parse_tag():
try:
LOG.info(message, message.structure)
self.erros = 0
title = message.structure['title']
self.widgets.seekBar.set_text("Radio: " + title)
LOG.info("show title!", title)
self.song.name = title
self.song.artist = None
self.song.title = None
print self.prev_title, title
if title and self.song.type == CommonBean.TYPE_RADIO_URL and self.prev_title != title:
start_time = str(int(time.time()));
self.prev_title = title
LOG.info("show info!", self.song.name)
self.onlineCntr.info.show_song_info(self.song)
if FConfiguration().enable_radio_srobbler:
LOG.debug("Enable radio scorbler", self.song.getArtist(), self.song.getTitle())
track = self.onlineCntr.info.get_track(self.song)
if track:
self.last_fm_scrobler.get_scrobler().scrobble(self.song.getArtist(), self.song.getTitle(), start_time, "P", "", track.get_duration())
LOG.debug("Track found and srobled radio scorbler", self.song.getArtist(), self.song.getTitle())
else:
LOG.debug("Track not found and not scrobled", self.song.getArtist(), self.song.getTitle())
except:
LOG.warn("Messege info error appear")
pass
#LOG.info(message.parse_tag()['title']
elif type == gst.MESSAGE_EOS:
LOG.info("MESSAGE_EOS")
self.stopState()
self.playerThreadId = None
self.next()
elif type == gst.MESSAGE_ERROR:
LOG.info("MESSAGE_ERROR")
err, debug = message.parse_error()
LOG.info("Error: %s" % err, debug, err.domain, err.code)
if message.structure:
name = message.structure.get_name()
LOG.info("Structure name:", name)
# name == "missing-plugin" or
#in all cases we break playing, retry only if it paused.
if err.code != 1:
self.widgets.seekBar.set_text(str(err))
self.playerThreadId = None
self.player.set_state(gst.STATE_NULL)
#self.player = None
return None
self.widgets.seekBar.set_text(str(err))
if self.song.path != self.prev_path:
self.playerThreadId = None
self.player.set_state(gst.STATE_NULL)
#self.player = None
time.sleep(4)
self.player.set_state(gst.STATE_NULL)
if self.song.type == CommonBean.TYPE_RADIO_URL and self.erros <= 1:
LOG.error("Error Num", self.erros)
self.erros = self.erros + 1;
self.playSong(self.song)
"""Try to play next"""
else:
#LOG.info(message
pass
| Python |
'''
Created on Mar 11, 2010
@author: ivan
'''
import gtk
from foobnix.model.entity import CommonBean
from foobnix.util import LOG
class PlaylistModel:
POS_ICON = 0
POS_TRACK_NUMBER = 1
POS_NAME = 2
POS_PATH = 3
POS_COLOR = 4
POS_INDEX = 5
POS_TYPE = 6
def __init__(self, widget):
self.widget = widget
self.current_list_model = gtk.ListStore(str, str, str, str, str, int, str)
cellpb = gtk.CellRendererPixbuf()
cellpb.set_property('cell-background', 'yellow')
iconColumn = gtk.TreeViewColumn(_('Icon'), cellpb, stock_id=0, cell_background=4)
numbetColumn = gtk.TreeViewColumn(_('N'), gtk.CellRendererText(), text=1, background=4)
descriptionColumn = gtk.TreeViewColumn(_("Music List"), gtk.CellRendererText(), text=2, background=4)
widget.append_column(iconColumn)
widget.append_column(numbetColumn)
widget.append_column(descriptionColumn)
widget.set_model(self.current_list_model)
def getBeenByPosition(self, position):
if position >= len(self.current_list_model):
LOG.error("Song index too much", position)
return None
bean = CommonBean()
bean.icon = self.current_list_model[position][ self.POS_ICON]
bean.tracknumber = self.current_list_model[position][ self.POS_TRACK_NUMBER]
bean.name = self.current_list_model[position][ self.POS_NAME]
bean.path = self.current_list_model[position][ self.POS_PATH]
bean.color = self.current_list_model[position][ self.POS_COLOR]
bean.index = self.current_list_model[position][ self.POS_INDEX]
bean.type = self.current_list_model[position][ self.POS_TYPE]
return bean
def get_all_beans(self):
beans = []
for i in xrange(len(self.current_list_model)):
beans.append(self.getBeenByPosition(i))
return beans
def set_all_beans(self, beans):
self.clear()
for bean in beans:
self.append(bean)
def append_all_beans(self, beans):
for bean in beans:
self.append(bean)
def getSelectedBean(self):
selection = self.widget.get_selection()
model, selected = selection.get_selected()
if selected:
bean = CommonBean()
bean.icon = model.get_value(selected, self.POS_ICON)
bean.tracknumber = model.get_value(selected, self.POS_TRACK_NUMBER)
bean.name = model.get_value(selected, self.POS_NAME)
bean.path = model.get_value(selected, self.POS_PATH)
bean.color = model.get_value(selected, self.POS_COLOR)
bean.index = model.get_value(selected, self.POS_INDEX)
bean.type = model.get_value(selected, self.POS_TYPE)
return bean
def clear(self):
self.current_list_model.clear()
def append(self, bean):
self.current_list_model.append([bean.icon, bean.tracknumber, bean.name, bean.path, bean.color, bean.index, bean.type])
def __del__(self, *a):
LOG.info("del")
| Python |
'''
Created on Mar 11, 2010
@author: ivan
'''
from foobnix.playlist.playlist_model import PlaylistModel
from foobnix.model.entity import CommonBean
from foobnix.util.mouse_utils import is_double_click
from foobnix.player.player_controller import PlayerController
from random import randint
from foobnix.util.configuration import FConfiguration
from foobnix.directory.directory_controller import DirectoryCntr
from foobnix.util import LOG
class PlaylistCntr():
def __init__(self, widget, playerCntr):
self.current_list_model = PlaylistModel(widget)
self.playerCntr = playerCntr
widget.connect("button-press-event", self.onPlaySong)
self.index = 0;
widget.connect("drag-end", self.onDrugBean)
def registerDirectoryCntr(self, directoryCntr):
self.directoryCntr = directoryCntr
def onDrugBean(self, *ars):
selected = self.current_list_model.get_selected_bean()
LOG.info("Drug song", selected, selected.type)
self.directoryCntr.set_active_view(DirectoryCntr.VIEW_VIRTUAL_LISTS)
if selected.type in [CommonBean.TYPE_MUSIC_URL, CommonBean.TYPE_MUSIC_FILE, CommonBean.TYPE_RADIO_URL]:
selected.parent = None
self.directoryCntr.append_virtual([selected])
self.directoryCntr.leftNoteBook.set_current_page(0)
def getState(self):
return [self.get_playlist_beans(), self.index]
def get_playlist_beans(self):
return self.current_list_model.get_all_beans()
def set_playlist_beans(self, beans):
return self.current_list_model.set_all_beans(beans)
def setState(self, state):
self.set_playlist_beans(state[0])
self.index = state[1]
if self.get_playlist_beans():
self.repopulate(self.get_playlist_beans(), self.index);
#self.playerCntr.playSong(self.get_playlist_beans()[self.index])
def clear(self):
self.current_list_model.clear()
def onPlaySong(self, w, e):
if is_double_click(e):
playlistBean = self.current_list_model.get_selected_bean()
self.repopulate(self.get_playlist_beans(), playlistBean.index);
self.index = playlistBean.index
self.playerCntr.set_mode(PlayerController.MODE_PLAY_LIST)
self.playerCntr.playSong(playlistBean)
def getNextSong(self):
if FConfiguration().isRandom:
self.index = randint(0, len(self.get_playlist_beans()))
else:
self.index += 1
if self.index >= len(self.get_playlist_beans()):
self.index = 0
if not FConfiguration().isRepeat:
self.index = len(self.get_playlist_beans())
return None
playlistBean = self.current_list_model.getBeenByPosition(self.index)
if not playlistBean:
return None
self.repopulate(self.get_playlist_beans(), playlistBean.index);
return playlistBean
def getPrevSong(self):
if FConfiguration().isRandom:
self.index = randint(0, len(self.get_playlist_beans()))
else:
self.index -= 1
if self.index < 0:
self.index = len(self.get_playlist_beans()) - 1
playlistBean = self.current_list_model.getBeenByPosition(self.index)
self.repopulate(self.get_playlist_beans(), playlistBean.index);
return playlistBean
def setPlaylist(self, entityBeans):
LOG.info("Set play list")
self.clear()
self.set_playlist_beans(entityBeans)
self.index = 0
if entityBeans:
self.playerCntr.playSong(entityBeans[0])
self.repopulate(entityBeans, self.index);
def appendPlaylist(self, entityBeans):
LOG.info("Append play list")
self.current_list_model.append_all_beans(entityBeans)
#if self.get_playlist_beans():
#self.playerCntr.playSong(self.get_playlist_beans()[index])
self.repopulate(self.get_playlist_beans(), self.index);
def repopulate(self, entityBeans, index):
self.current_list_model.clear()
for i in range(len(entityBeans)):
songBean = entityBeans[i]
songBean.name = songBean.getPlayListDescription()
songBean.color = self.getBackgroundColour(i)
songBean.index = i
if i == index:
songBean.setIconPlaying()
self.current_list_model.append(songBean)
else:
songBean.setIconNone()
self.current_list_model.append(songBean)
def getBackgroundColour(self, i):
if i % 2 :
return "#F2F2F2"
else:
return "#FFFFE5"
| Python |
'''
Created on Sep 22, 2010
@author: ivan
'''
import gtk
from foobnix.util import LOG, const
import sys
from foobnix.util.fc import FC
from foobnix.regui.model.signal import FControl
from foobnix.regui.about import about
class MenuWidget(FControl):
def __init__(self, controls):
FControl.__init__(self, controls)
"""TOP menu constructor"""
top = TopMenu()
"""File"""
file = top.append("File")
file.add_image_item("Add File(s)", gtk.STOCK_OPEN)
file.add_image_item("Add Folder(s)", gtk.STOCK_OPEN)
file.separator()
file.add_image_item("Quit", gtk.STOCK_QUIT, self.controls.quit)
"""View"""
view = top.append("View")
self.view_music_tree = view.add_ckeck_item("Music Tree", FC().is_view_music_tree_panel)
self.view_music_tree.connect("activate", lambda w: controls.set_visible_musictree_panel(w.get_active()))
self.view_search_panel = view.add_ckeck_item("Search Panel", FC().is_view_info_panel)
self.view_search_panel.connect("activate", lambda w: controls.set_visible_search_panel(w.get_active()))
view.separator()
#view.add_ckeck_item("Lyric Panel", FC().is_view_lyric_panel)
self.view_info_panel = view.add_ckeck_item("Info Panel", FC().is_view_info_panel)
self.view_info_panel.connect("activate", lambda w: controls.set_visible_info_panel(w.get_active()))
view.separator()
view.add_image_item("Equalizer", None, self.controls.eq.show)
view.add_image_item("Download", None, self.controls.dm.show)
view.separator()
view.add_image_item("Preferences", gtk.STOCK_PREFERENCES, self.controls.show_preferences)
"""Playback"""
playback = top.append("Playback")
"""Playback - Order"""
order = playback.add_text_item("Order")
self.playback_order_linear = order.add_radio_item("Linear", None, not FC().is_order_random)
self.playback_order_random = order.add_radio_item("Random", self.playback_order_linear, FC().is_order_random)
self.playback_order_random.connect("activate", lambda w: controls.set_playback_random(w.get_active()))
order.separator()
order.add_image_item("Shuffle", gtk.STOCK_UNDELETE)
"""Playback - Repeat"""
repeat = playback.add_text_item("Repeat")
self.lopping_all = repeat.add_radio_item("All", None, FC().lopping == const.LOPPING_LOOP_ALL)
self.lopping_single = repeat.add_radio_item("Single", self.lopping_all, FC().lopping == const.LOPPING_SINGLE)
self.lopping_disable = repeat.add_radio_item("Disable", self.lopping_all, FC().lopping == const.LOPPING_DONT_LOOP)
self.lopping_all.connect("activate", lambda w: w.get_active() and controls.set_lopping_all())
self.lopping_single.connect("activate", lambda w: w.get_active() and controls.set_lopping_single())
self.lopping_disable.connect("activate", lambda w: w.get_active() and controls.set_lopping_disable())
"""Playlist View"""
playlist = playback.add_text_item("Playlist")
self.playlist_plain = playlist.add_radio_item("Plain (normal style)", None, FC().playlist_type == const.PLAYLIST_PLAIN)
self.playlist_tree = playlist.add_radio_item("Tree (apollo style)", self.playlist_plain , FC().playlist_type == const.PLAYLIST_TREE)
self.playlist_plain.connect("activate", lambda w: w.get_active() and controls.set_playlist_plain())
self.playlist_tree.connect("activate", lambda w: w.get_active() and controls.set_playlist_tree())
"""Help"""
help = top.append("Help")
help.add_image_item("About", gtk.STOCK_ABOUT,self.show_about)
help.add_image_item("Help", gtk.STOCK_HELP)
top.decorate()
self.widget = top.widget
self.on_load()
def show_about(self, *a):
about.about.show_all()
def on_load(self):
self.view_music_tree.set_active(FC().is_view_music_tree_panel)
self.view_search_panel.set_active(FC().is_view_search_panel)
self.view_info_panel.set_active(FC().is_view_info_panel)
def on_save(self):
FC().is_view_music_tree_panel = self.view_music_tree.get_active()
FC().is_view_search_panel = self.view_search_panel.get_active()
FC().is_view_info_panel = self.view_info_panel.get_active()
"""My custom menu class for helping buildings"""
class MyMenu(gtk.Menu):
def __init__(self):
gtk.Menu.__init__(self)
def add_image_item(self, title, gtk_stock, func=None, param=None):
item = gtk.ImageMenuItem(title)
item.show()
if gtk_stock:
img = gtk.image_new_from_stock(gtk_stock, gtk.ICON_SIZE_MENU)
item.set_image(img)
LOG.debug("Menu-Image-Activate", title, gtk_stock, func, param)
if param:
item.connect("activate", lambda * a: func(param))
else:
item.connect("activate", lambda * a: func())
self.append(item)
def separator(self):
separator = gtk.SeparatorMenuItem()
separator.show()
self.append(separator)
def add_ckeck_item(self, title, active=False, func=None, param=None):
check = gtk.CheckMenuItem(title)
if param and func:
check.connect("activate", lambda * a: func(param))
elif func:
check.connect("activate", lambda * a: func())
check.show()
check.set_active(active)
self.append(check)
return check
def add_radio_item(self, title, group, active):
check = gtk.RadioMenuItem(group, title)
check.show()
check.set_active(active)
self.append(check)
return check
def add_text_item(self, title):
sub = gtk.MenuItem(title)
sub.show()
self.append(sub)
menu = MyMenu()
menu.show()
sub.set_submenu(menu)
return menu
"""My top menu bar helper"""
class TopMenu():
def __init__(self):
rc_st = '''
style "menubar-style" {
GtkMenuBar::shadow_type = none
GtkMenuBar::internal-padding = 0
}
class "GtkMenuBar" style "menubar-style"
'''
gtk.rc_parse_string(rc_st)
self.menu_bar = gtk.MenuBar()
self.menu_bar.show()
self.widget = self.menu_bar
def decorate(self):
label = gtk.Label()
style = label.get_style()
background_color = style.bg[gtk.STATE_NORMAL]
text_color = style.fg[gtk.STATE_NORMAL]
self.menu_bar.modify_bg(gtk.STATE_NORMAL, background_color)
# making main menu look a bit better
for item in self.menu_bar.get_children():
current = item.get_children()[0]
current.modify_fg(gtk.STATE_NORMAL, text_color)
def append(self, title):
menu = MyMenu()
menu.show()
file_item = gtk.MenuItem(title)
file_item.show()
file_item.set_submenu(menu)
self.menu_bar.append(file_item)
return menu
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.