From 8a51bc2de5f13f370835d138773f1ade755c11eb Mon Sep 17 00:00:00 2001 From: pat1 Date: Sat, 21 Jul 2018 10:21:21 +0200 Subject: [PATCH 1/8] sure you specify the proper version support in your setup.py file --- setup.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/setup.py b/setup.py index edc1742..9be2a46 100644 --- a/setup.py +++ b/setup.py @@ -301,6 +301,11 @@ def run(self): author_email='p.patruno@iperbole.bologna.it', platforms = ["any"], url='http://autoradiobc.sf.net', + classifiers=( + "Programming Language :: Python :: 3", + "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", + "Operating System :: OS Independent", + ), cmdclass={'build': build,'compilemessages':compilemessages,'createmanpages':createmanpages,"distclean":distclean,"haxecompileanoggplayer":haxecompileanoggplayer,"installbin":installbin,"buildall":buildall,"djangocollectstatic":djangocollectstatic}, packages=['autoradio', 'autoradio.playlists','autoradio.spots', 'autoradio.jingles', 'autoradio.programs', From 3f23fdc5558832b4284e9d9b6aaa807f5e2c042e Mon Sep 17 00:00:00 2001 From: pat1 Date: Sat, 21 Jul 2018 11:10:20 +0200 Subject: [PATCH 2/8] porting to python3 with futurize --- autoradio/audaciousweb.py | 14 +- autoradio/autoaudacious.py | 8 +- autoradio/autoepris.py | 15 +- autoradio/autompris.py | 13 +- autoradio/autompris2.py | 49 ++-- autoradio/autoplayer/mpris2client.py | 17 +- autoradio/autoplayer/player.py | 44 ++-- autoradio/autoplayer/player_gstreamer0.py | 44 ++-- autoradio/autoplayer/playlist.py | 78 ++++--- autoradio/autoradio_config.py | 3 +- autoradio/autoradio_core.py | 64 +++--- autoradio/autoxmms.py | 5 +- autoradio/daemon.py | 11 +- autoradio/dir2ogg.py | 92 ++++---- autoradio/gest_jingle.py | 43 ++-- autoradio/gest_palimpsest.py | 23 +- autoradio/gest_playlist.py | 40 ++-- autoradio/gest_program.py | 23 +- autoradio/gest_spot.py | 33 +-- autoradio/jingles/admin.py | 6 +- autoradio/jingles/models.py | 87 ++++---- autoradio/manageamarok.py | 8 +- autoradio/manageaudacious.py | 21 +- autoradio/managempris.py | 25 ++- autoradio/managepytone.py | 26 ++- autoradio/managexmms.py | 19 +- autoradio/mkplaylist.py | 40 ++-- autoradio/mpris2/__init__.py | 30 +-- autoradio/mpris2/interfaces.py | 1 + autoradio/mpris2/loop_status.py | 9 +- autoradio/mpris2/mediaplayer2.py | 6 +- autoradio/mpris2/metada_map.py | 3 +- autoradio/mpris2/playback_rate.py | 3 +- autoradio/mpris2/player.py | 12 +- autoradio/mpris2/playlist.py | 2 +- autoradio/mpris2/playlists.py | 16 +- autoradio/mpris2/some_players.py | 1 + autoradio/mpris2/time_in_us.py | 3 +- autoradio/mpris2/tracklist.py | 8 +- autoradio/mpris2/types.py | 46 ++-- autoradio/mpris2/uri.py | 3 +- autoradio/mpris2/utils.py | 14 +- autoradio/mpris2/volume.py | 8 +- autoradio/mprisweb.py | 19 +- autoradio/player/urls.py | 19 +- autoradio/playlists/admin.py | 3 +- autoradio/playlists/models.py | 33 +-- autoradio/programs/admin.py | 6 +- autoradio/programs/migrations/0002_fixture.py | 3 +- autoradio/programs/models.py | 135 +++++------ autoradio/programs/urls.py | 3 +- autoradio/programs/urls_podcast.py | 3 +- autoradio/programs/views.py | 25 ++- autoradio/programs/widgets.py | 6 +- autoradio/pydbusdecorator/__init__.py | 13 +- autoradio/pydbusdecorator/dbus_attr.py | 9 +- autoradio/pydbusdecorator/dbus_decorator.py | 1 + autoradio/pydbusdecorator/dbus_interface.py | 6 +- autoradio/pydbusdecorator/dbus_method.py | 10 +- autoradio/pydbusdecorator/dbus_signal.py | 5 +- autoradio/pydbusdecorator/undefined_param.py | 6 +- autoradio/settings.py | 5 +- autoradio/spots/admin.py | 6 +- autoradio/spots/models.py | 209 +++++++++--------- autoradio/urls.py | 3 +- autoradio/xmmsweb.py | 7 +- setup.py | 21 +- 67 files changed, 874 insertions(+), 698 deletions(-) diff --git a/autoradio/audaciousweb.py b/autoradio/audaciousweb.py index a7ae7f7..fa530ca 100644 --- a/autoradio/audaciousweb.py +++ b/autoradio/audaciousweb.py @@ -4,7 +4,11 @@ """ Show audacious playlist on a simple web server. """ +from __future__ import print_function +from builtins import str +from builtins import range +from builtins import object maxplele=100 # max number of elements in playlist port=8888 # server port @@ -57,7 +61,7 @@ ''' -class HomePage: +class HomePage(object): # def Main(self): # # Let's link to another method here. @@ -141,7 +145,7 @@ def index(self): htmlresponse+='' htmlresponse+='' - for pos in xrange(0,min(len,maxplele)): + for pos in range(0,min(len,maxplele)): htmlresponse+='' metadata=tracklist.GetMetadata(pos) @@ -185,7 +189,7 @@ def index(self): col="#00FF00" toend="" - print artist,title + print(artist,title) if (artist is not None) or (title is not None): htmlresponse+='' % \ (col,pos+1,str(timelength),str(toend),file,artist,title) @@ -262,8 +266,8 @@ def start_http_server(iht=False): try: start_http_server(iht=True) except: - print "Error" + print("Error") raise finally: - print "Terminated" + print("Terminated") diff --git a/autoradio/autoaudacious.py b/autoradio/autoaudacious.py index 397dba0..b3cff85 100644 --- a/autoradio/autoaudacious.py +++ b/autoradio/autoaudacious.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # GPL. (C) 2007-2009 Paolo Patruno. +from builtins import range +from builtins import object import dbus import time import datetime @@ -9,7 +11,7 @@ # ------- dbus interface --------- import dbus -class audacious: +class audacious(object): def __init__(self,session=0): @@ -107,7 +109,7 @@ def playlist_clear_up(self,atlast=10): # delete the old ones if pos > atlast : - for prm in xrange(0,pos-atlast): + for prm in range(0,pos-atlast): self.tracklist.DelTrack(0) return True @@ -135,7 +137,7 @@ def playlist_clear_down(self,atlast=500): #elimino il troppo if length-pos > atlast : - for prm in xrange(length,pos+atlast,-1): + for prm in range(length,pos+atlast,-1): self.tracklist.DelTrack(prm) return True diff --git a/autoradio/autoepris.py b/autoradio/autoepris.py index bddb2e5..eb9b1a7 100644 --- a/autoradio/autoepris.py +++ b/autoradio/autoepris.py @@ -1,6 +1,9 @@ #!/usr/bin/env python # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from builtins import range +from builtins import object import dbus import time import datetime @@ -10,7 +13,7 @@ import dbus -class mediaplayer: +class mediaplayer(object): def __init__(self,session=0): @@ -40,8 +43,8 @@ def play_ifnot(self): ''' # I check if mediaplayer is playing .... otherside I try to play - print self.tracklist.ListTracks() - print self.tracklist.Current + print(self.tracklist.ListTracks()) + print(self.tracklist.Current) # if (not self.player.PlaybackStatus == "Playing"): @@ -108,7 +111,7 @@ def playlist_clear_up(self,atlast=10): # delete the old ones if pos > atlast : - for prm in xrange(0,pos-atlast): + for prm in range(0,pos-atlast): self.tracklist.DelTrack(0) return True @@ -137,7 +140,7 @@ def playlist_clear_down(self,atlast=500): #elimino il troppo if length-pos > atlast : - for prm in xrange(length,pos+atlast,-1): + for prm in range(length,pos+atlast,-1): self.tracklist.DelTrack(prm) return True @@ -201,7 +204,7 @@ def get_playlist_pos(self): def main(): mp=mediaplayer() - print mp + print(mp) mp.play_ifnot() diff --git a/autoradio/autompris.py b/autoradio/autompris.py index eb52cbe..b9f7b50 100644 --- a/autoradio/autompris.py +++ b/autoradio/autompris.py @@ -9,6 +9,9 @@ # Audacious provide non standard interface to do this # ---------------------------------------- +from builtins import str +from builtins import range +from builtins import object import dbus import time import datetime @@ -17,7 +20,7 @@ import dbus -class mediaplayer: +class mediaplayer(object): def __init__(self,player="audacious",session=0): @@ -160,7 +163,7 @@ def playlist_clear_up(self,atlast=10): # delete the old ones if pos > atlast : - for prm in xrange(0,pos-atlast): + for prm in range(0,pos-atlast): self.tracklist.DelTrack(0) return True @@ -188,7 +191,7 @@ def playlist_clear_down(self,atlast=500): #elimino il troppo if length-pos > atlast : - for prm in xrange(length,pos+atlast,-1): + for prm in range(length,pos+atlast,-1): self.tracklist.DelTrack(prm) return True @@ -218,7 +221,7 @@ def get_playlist_posauto(self,autopath,securesec=10): try: #Fix how older versions of Audacious misreport the URI of the song. if metadata is not None: - if metadata.has_key ("URI") and not metadata.has_key ("location"): + if "URI" in metadata and "location" not in metadata: metadata["location"] = metadata["URI"] file=metadata["location"] @@ -241,7 +244,7 @@ def get_playlist_posauto(self,autopath,securesec=10): #Fix how older versions of Audacious misreport the URI of the song. if metadata is not None: - if metadata.has_key ("URI") and not metadata.has_key ("location"): + if "URI" in metadata and "location" not in metadata: metadata["location"] = metadata["URI"] file=metadata["location"] diff --git a/autoradio/autompris2.py b/autoradio/autompris2.py index 0ead742..0f95619 100644 --- a/autoradio/autompris2.py +++ b/autoradio/autompris2.py @@ -1,11 +1,20 @@ #!/usr/bin/env python # GPL. (C) 2007-2012 Paolo Patruno. +from __future__ import division +from __future__ import print_function +from builtins import str +from builtins import range +from builtins import object +from past.utils import old_div import dbus import time import datetime -import os -import gobject +import os,sys +if sys.version_info[0] == 3: + from gi.repository import GObject as gobject +else: + import gobject import autoradio.settings from dbus.mainloop.glib import DBusGMainLoop from autoradio.mpris2.mediaplayer2 import MediaPlayer2 @@ -60,7 +69,7 @@ #----------------------------------------------------------------------- -class mediaplayer: +class mediaplayer(object): def __init__(self,player="AutoPlayer",session=0, busaddress=autoradio.settings.busaddressplayer): @@ -85,7 +94,7 @@ def __init__(self,player="AutoPlayer",session=0, busaddress=autoradio.settings.b self.mp2 = MediaPlayer2(dbus_interface_info={'dbus_uri': uri,'dbus_session':self.bus}) self.play = Player(dbus_interface_info={'dbus_uri': uri,'dbus_session':self.bus}) else: - print "No players availables" + print("No players availables") return if self.mp2.HasTrackList: @@ -176,7 +185,7 @@ def playlist_clear_up(self,atlast=10): op=self.get_playlist() - for prm in xrange(0,pos-atlast): + for prm in range(0,pos-atlast): #print "remove up: ",op[prm] self.tl.RemoveTrack( str(op[prm])) @@ -208,7 +217,7 @@ def playlist_clear_down(self,atlast=500): op=self.get_playlist() - for prm in xrange(length-1,pos+atlast,-1): + for prm in range(length-1,pos+atlast,-1): #print "remove down: ",op[prm] self.tl.RemoveTrack( str(op[prm]) ) @@ -353,8 +362,8 @@ def get_metadata(self,pos=None): "file": file, "title": title, "artist": artist, - "mtimelength": long(round(mtimelength/1000.)), - "mtimeposition": long(round(mtimeposition/1000.)) + "mtimelength": int(round(old_div(mtimelength,1000.))), + "mtimeposition": int(round(old_div(mtimeposition,1000.))) } return mymeta @@ -396,7 +405,7 @@ def main(): # DBusGMainLoop(set_as_default=True, mp=mediaplayer(player="AutoPlayer") - print "status",mp + print("status",mp) # mp.play_ifnot() # print mp @@ -406,18 +415,18 @@ def main(): #mp.connect() #print "connected" #mp.loop() - print "pos",mp.get_playlist_pos() - print "securepos" - print mp.get_playlist_securepos() - print "clear_up" - print mp.playlist_clear_up(atlast=2) - print "clear_down" - print mp.playlist_clear_down(atlast=3) - print "playlist" - print mp.get_playlist() + print("pos",mp.get_playlist_pos()) + print("securepos") + print(mp.get_playlist_securepos()) + print("clear_up") + print(mp.playlist_clear_up(atlast=2)) + print("clear_down") + print(mp.playlist_clear_down(atlast=3)) + print("playlist") + print(mp.get_playlist()) posauto=mp.get_playlist_posauto(autopath="/casa") - print "posauto",posauto - print "add_atpos" + print("posauto",posauto) + print("add_atpos") mp.playlist_add_atpos("file:///home",posauto) ##mp.playlist_add_atpos("file:///home",3) diff --git a/autoradio/autoplayer/mpris2client.py b/autoradio/autoplayer/mpris2client.py index 5685796..3a68fe6 100755 --- a/autoradio/autoplayer/mpris2client.py +++ b/autoradio/autoplayer/mpris2client.py @@ -3,6 +3,7 @@ # GPL. (C) 2013 Paolo Patruno. #Connect to player +from __future__ import print_function from autoradio.mpris2.mediaplayer2 import MediaPlayer2 from autoradio.mpris2.player import Player from autoradio.mpris2.tracklist import TrackList @@ -18,13 +19,13 @@ def playhandler( *args, **kw): playbackstatus = args[2].get("PlaybackStatus",None) position = args[2].get("Position",None) if playbackstatus is not None: - print "PlaybackStatus",playbackstatus + print("PlaybackStatus",playbackstatus) if position is not None: - print "Position", position + print("Position", position) def trackhandler( *args, **kw): - print args, kw + print(args, kw) DBusGMainLoop(set_as_default=True) @@ -42,7 +43,7 @@ def trackhandler( *args, **kw): #uri = Interfaces.MEDIA_PLAYER + '.' + Some_Players.AUTOPLAYER #uri = Interfaces.MEDIA_PLAYER + '.' +'AutoPlayer' - print uri + print(uri) if busaddress is None: bus = dbus.SessionBus() @@ -57,7 +58,7 @@ def trackhandler( *args, **kw): #Get attributes #print play.Metadata #current media data - print play.PlaybackStatus + print(play.PlaybackStatus) play.PropertiesChanged = playhandler @@ -66,15 +67,15 @@ def trackhandler( *args, **kw): tl = TrackList(dbus_interface_info={'dbus_uri': uri}) # attributes and methods together for track in tl.GetTracksMetadata( tl.Tracks): - print track.get(u'mpris:trackid',None),track.get(u'mpris:length',None),track.get(u'xesam:artist',None), track.get(u'xesam:title',None) + print(track.get(u'mpris:trackid',None),track.get(u'mpris:length',None),track.get(u'xesam:artist',None), track.get(u'xesam:title',None)) tl.PropertiesChanged = trackhandler except: - print "mmm audacious mpris2 interface is buggy" + print("mmm audacious mpris2 interface is buggy") mloop.run() else: - print "No players availables" + print("No players availables") #s = get_session() diff --git a/autoradio/autoplayer/player.py b/autoradio/autoplayer/player.py index 9ab62ac..dcb061e 100644 --- a/autoradio/autoplayer/player.py +++ b/autoradio/autoplayer/player.py @@ -27,7 +27,15 @@ # everywhere we change the tracklist # we use this in autoplayergui to update the tracklist -import sys, time, thread +from __future__ import division +from __future__ import print_function +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import object +from past.utils import old_div +import sys, time, _thread import tempfile,os #import pygst @@ -39,7 +47,7 @@ gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst -import playlist +from . import playlist import dbus import dbus.service import dbus.mainloop.glib @@ -352,7 +360,7 @@ def Set(self, interface, prop, value): def GetAll(self, interface): read_props = {} props = self.__prop_mapping[interface] - for key, (getter, setter) in props.iteritems(): + for key, (getter, setter) in props.items(): if callable(getter): getter = getter(self) read_props[key] = getter @@ -419,7 +427,7 @@ def Quit(self): @dbus.service.method(PLAYER_IFACE) def Next(self): - self.player.next() + next(self.player) @dbus.service.method(PLAYER_IFACE) def Previous(self): @@ -515,7 +523,7 @@ def GetTracksMetadata(self,trackids): myattr=None if myattr is not None: if key == "mpris:length": - myattr=long(round(myattr/1000.)) + myattr=int(round(old_div(myattr,1000.))) meta[key]=myattr metadata.append(dbus.Dictionary(meta, signature='sv')) @@ -536,7 +544,7 @@ def handle_sigint(self,signum, frame): self.Quit() -class Player: +class Player(object): def __init__(self,myplaylist=None,loop=None,starttoplay=False,myaudiosink=None): self.playlist=myplaylist @@ -695,7 +703,7 @@ def on_message_eos(self, bus, message): #self.player.set_state(Gst.State.NULL) #self.playmode = "Stopped" #self.statuschanged = True - self.next() + next(self) def on_message_error(self, bus, message): @@ -711,7 +719,7 @@ def on_message_error(self, bus, message): logging.warning("current media: %s" % currenturi) self.playmode= self.recoverplaymode - self.next() + next(self) # if err.domain == gst.RESOURCE_ERROR : # logging.warning("restart to play after an RESOURCE_ERROR") @@ -756,9 +764,9 @@ def on_message_state_changed(self, bus, message): self.playmode = "Playing" self.statuschanged = True - def next(self): + def __next__(self): logging.info( "next") - self.playlist.next() + next(self.playlist) if self.playlist.current is None: logging.info( "end playlist") self.stop() @@ -804,7 +812,7 @@ def seek(self,t): logging.info("seek") try: pos_int = self.player.query_position(Gst.Format.TIME)[1] - pos_int =pos_int/1000 + t + pos_int =old_div(pos_int,1000) + t logging.info("seek %s" % str(pos_int)) self.setposition(self.playlist.current,pos_int) return pos_int @@ -835,7 +843,7 @@ def setposition(self,trackid,t): res = self.player.send_event(event) if res: #self.player.set_new_stream_time(0L) - self.player.set_start_time(0L) + self.player.set_start_time(0) #if wait: self.playbin.get_state(timeout=50*gst.MSECOND) # this cause a doble seek with playbin2 @@ -848,8 +856,8 @@ def loaduri(self): logging.info( "loaduri") if self.playlist.current is None: - if len(self.playlist.keys()) > 0: - self.playlist.set_current(self.playlist.keys()[0]) + if len(list(self.playlist.keys())) > 0: + self.playlist.set_current(list(self.playlist.keys())[0]) uri = self.playlist.get_current().path if uri is not None: @@ -920,7 +928,7 @@ def position(self): logging.warning( "in query_position:"+str(e) ) return None - return int(round(pos_int/1000.)) + return int(round(old_div(pos_int,1000.))) def printinfo(self): @@ -929,7 +937,7 @@ def printinfo(self): dur_int = self.player.query_duration(Gst.Format.TIME)[1] # if dur_int == -1: # print "bho" - print self.playmode,self.convert_ns(pos_int)+"//"+self.convert_ns(dur_int) + print(self.playmode,self.convert_ns(pos_int)+"//"+self.convert_ns(dur_int)) except(Gst.QueryError): #print "error printinfo" @@ -981,8 +989,8 @@ def recoverstatus(self): time.sleep(1) logging.info ( "recover last status from disk: position %s" % self.playlist.position) if self.playlist.position is not None: - logging.info ( "set current %s and position %s " % (self.playlist.current,int(round(self.playlist.position/1000.)))) - self.setposition(self.playlist.current,int(round(self.playlist.position/1000.))) + logging.info ( "set current %s and position %s " % (self.playlist.current,int(round(old_div(self.playlist.position,1000.))))) + self.setposition(self.playlist.current,int(round(old_div(self.playlist.position,1000.)))) if self.starttoplay: time.sleep(1) self.play() diff --git a/autoradio/autoplayer/player_gstreamer0.py b/autoradio/autoplayer/player_gstreamer0.py index 73939d9..74aca7a 100644 --- a/autoradio/autoplayer/player_gstreamer0.py +++ b/autoradio/autoplayer/player_gstreamer0.py @@ -22,12 +22,20 @@ # TrackRemoved (o: TrackId) # TrackMetadataChanged (o: TrackId, a{sv}: Metadata) -import sys, time, thread +from __future__ import division +from __future__ import print_function +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import object +from past.utils import old_div +import sys, time, _thread import gobject import pygst pygst.require("0.10") import gst -import playlist +from . import playlist import dbus import dbus.service import dbus.mainloop.glib @@ -342,7 +350,7 @@ def Set(self, interface, prop, value): def GetAll(self, interface): read_props = {} props = self.__prop_mapping[interface] - for key, (getter, setter) in props.iteritems(): + for key, (getter, setter) in props.items(): if callable(getter): getter = getter(self) read_props[key] = getter @@ -406,7 +414,7 @@ def Quit(self): @dbus.service.method(PLAYER_IFACE) def Next(self): - self.player.next() + next(self.player) @dbus.service.method(PLAYER_IFACE) def Previous(self): @@ -491,7 +499,7 @@ def GetTracksMetadata(self,trackids): myattr= getattr(self.player.playlist[id],attr,None) if myattr is not None: if key == "mpris:length": - myattr=long(round(myattr/1000.)) + myattr=int(round(old_div(myattr,1000.))) meta[key]=myattr metadata.append(dbus.Dictionary(meta, signature='sv')) @@ -512,7 +520,7 @@ def handle_sigint(self,signum, frame): self.Quit() -class Player: +class Player(object): def __init__(self,myplaylist=None,loop=None,starttoplay=False,myaudiosink=None): self.playlist=myplaylist @@ -602,7 +610,7 @@ def on_message_eos(self, bus, message): #self.player.set_state(gst.STATE_NULL) #self.playmode = "Stopped" #self.statuschanged = True - self.next() + next(self) def on_message_error(self, bus, message): @@ -615,7 +623,7 @@ def on_message_error(self, bus, message): logging.warning("restart to play after an ERROR skipping current media") self.playmode= self.recoverplaymode - self.next() + next(self) # if err.domain == gst.RESOURCE_ERROR : # logging.warning("restart to play after an RESOURCE_ERROR") @@ -659,9 +667,9 @@ def on_message_state_changed(self, bus, message): self.playmode = "Playing" self.statuschanged = True - def next(self): + def __next__(self): logging.info( "next") - self.playlist.next() + next(self.playlist) if self.playlist.current is None: logging.info( "end playlist") self.stop() @@ -707,7 +715,7 @@ def seek(self,t): logging.info("seek") try: pos_int = self.player.query_position(gst.FORMAT_TIME, None)[0] - pos_int =pos_int/1000 + t + pos_int =old_div(pos_int,1000) + t logging.info("seek %s" % str(pos_int)) self.setposition(self.playlist.current,pos_int) return pos_int @@ -736,7 +744,7 @@ def setposition(self,trackid,t): gst.SEEK_TYPE_SET, tnano, gst.SEEK_TYPE_NONE, 0) res = self.player.send_event(event) if res: - self.player.set_new_stream_time(0L) + self.player.set_new_stream_time(0) #if wait: self.playbin.get_state(timeout=50*gst.MSECOND) # this cause a doble seek with playbin2 @@ -749,8 +757,8 @@ def loaduri(self): logging.info( "loaduri") if self.playlist.current is None: - if len(self.playlist.keys()) > 0: - self.playlist.set_current(self.playlist.keys()[0]) + if len(list(self.playlist.keys())) > 0: + self.playlist.set_current(list(self.playlist.keys())[0]) uri = self.playlist.get_current().path if uri is not None: @@ -816,7 +824,7 @@ def position(self): logging.warning( "gst.QueryError in query_position" ) return None - return int(round(pos_int/1000.)) + return int(round(old_div(pos_int,1000.))) def printinfo(self): @@ -825,7 +833,7 @@ def printinfo(self): dur_int = self.player.query_duration(gst.FORMAT_TIME, None)[0] # if dur_int == -1: # print "bho" - print self.playmode,self.convert_ns(pos_int)+"//"+self.convert_ns(dur_int) + print(self.playmode,self.convert_ns(pos_int)+"//"+self.convert_ns(dur_int)) except(gst.QueryError): #print "error printinfo" @@ -865,8 +873,8 @@ def recoverstatus(self): time.sleep(1) logging.info ( "recover last status from disk: position %s" % self.playlist.position) if self.playlist.position is not None: - logging.info ( "set current %s and position %s " % (self.playlist.current,int(round(self.playlist.position/1000.)))) - self.setposition(self.playlist.current,int(round(self.playlist.position/1000.))) + logging.info ( "set current %s and position %s " % (self.playlist.current,int(round(old_div(self.playlist.position,1000.))))) + self.setposition(self.playlist.current,int(round(old_div(self.playlist.position,1000.)))) if self.starttoplay: time.sleep(1) self.play() diff --git a/autoradio/autoplayer/playlist.py b/autoradio/autoplayer/playlist.py index 3f075df..3f602b5 100644 --- a/autoradio/autoplayer/playlist.py +++ b/autoradio/autoplayer/playlist.py @@ -2,13 +2,19 @@ # -*- coding: utf-8 -*- # GPL. (C) 2013 Paolo Patruno. +from __future__ import division +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import str +from past.utils import old_div import logging import collections import mutagen import sys from xml.sax import make_parser, handler, SAXParseException from xml.dom.minidom import Document -import urllib, urlparse +import urllib.request, urllib.parse, urllib.error, urllib.parse class Track(collections.namedtuple('Track',("path","time","artist","album","title","id"))): __slots__ = () @@ -137,11 +143,11 @@ def endElement(s, name): ##s.track['location'] = urllib.unquote(s.content) #s.track['location'] = urllib.unquote(s.content.encode("UTF-8")) - url=urlparse.urlsplit(s.content) + url=urllib.parse.urlsplit(s.content) if (url.scheme == "http"): s.track['location']=url.geturl() else: - s.track['location']=urlparse.urljoin("file://",urllib.unquote(url.path.encode("UTF-8"))) + s.track['location']=urllib.parse.urljoin("file://",urllib.parse.unquote(url.path.encode("UTF-8"))) elif s.path == "/playlist/trackList/track/title": s.track['title'] = s.content @@ -176,7 +182,7 @@ def __init__(self,media=None,tracks=None,current=None,position=None): else: track_meta=Track(ele,None,None,None,None,None) #print track_meta.get_metadata().values() - tr=Track._make(track_meta.get_metadata().values()) + tr=Track._make(list(track_meta.get_metadata().values())) self.append(tr) if tracks is not None: @@ -186,7 +192,7 @@ def __init__(self,media=None,tracks=None,current=None,position=None): def read(s, path): try: - with open(urlparse.urlsplit(path).path, "r") as f: + with open(urllib.parse.urlsplit(path).path, "r") as f: data = f.read() except IOError : @@ -204,8 +210,8 @@ def read(s, path): except: lines = data.split('\n') - lines = map(lambda line: line.strip().rstrip(), lines) - lines = filter(lambda line: line if line != "" and line[0] != '#' else None, lines) + lines = [line.strip().rstrip() for line in lines] + lines = [line for line in lines if line if line != "" and line[0] != '#' else None] if lines == []: return @@ -216,16 +222,16 @@ def read(s, path): for location in lines: - url=urlparse.urlsplit(location) + url=urllib.parse.urlsplit(location) # mmmmmm encode / decode every time do not work ! #location=urlparse.urljoin("file://",urllib.unquote(url.path.encode("UTF-8"))) if (url.scheme == "http"): location=url.geturl() else: - location=urlparse.urljoin("file://",urllib.unquote(url.path)) + location=urllib.parse.urljoin("file://",urllib.parse.unquote(url.path)) - track=Track._make(Track(location,None,None,None,None,None).get_metadata().values()) + track=Track._make(list(Track(location,None,None,None,None,None).get_metadata().values())) s.append(track) else: @@ -235,8 +241,8 @@ def read(s, path): logging.debug( "PLAYLIST: xspf parsed") for ele in p.tracks: - track=Track._make(Track(ele.get('location',None),ele.get('time',None),ele.get('creator',None), - ele.get('album',None),ele.get('title',None),ele.get('id',None)).get_metadata().values()) + track=Track._make(list(Track(ele.get('location',None),ele.get('time',None),ele.get('creator',None), + ele.get('album',None),ele.get('title',None),ele.get('id',None)).get_metadata().values())) s.append(track) @@ -304,7 +310,7 @@ def write(s,path): if track.get('tracknum') not in ['', None]: if type(track['tracknum']) == int: no = track['tracknum'] - elif type(track['tracknum']) in [unicode, str]: + elif type(track['tracknum']) in [str, str]: cnum=track['tracknum'].split("/")[0].lstrip('0') if cnum != "": no = int( track['tracknum'].split("/")[0].lstrip('0') ) @@ -320,7 +326,7 @@ def write(s,path): if type(track.get('time')) == float: tm = track['time']*1000000 elif type(track.get('time')) == int: - tm = track['time']/1000000. + tm = old_div(track['time'],1000000.) else: tm= None @@ -332,16 +338,16 @@ def write(s,path): #make valid quoted location location = track['path'] - url=urlparse.urlsplit(location) + url=urllib.parse.urlsplit(location) if (url.scheme == "http"): location=url.geturl() else: #here problem when file name come fron gtk or command line try: - location=urlparse.urljoin("file://",urllib.quote(url.path)) + location=urllib.parse.urljoin("file://",urllib.parse.quote(url.path)) except: - location=urlparse.urljoin("file://",urllib.quote(url.path.encode("UTF-8"))) + location=urllib.parse.urljoin("file://",urllib.parse.quote(url.path.encode("UTF-8"))) ##location = location.encode("utf-8") #if not 'http://' in location.lower() and \ @@ -367,13 +373,13 @@ def write(s,path): if track[k] != None: v = track[k] t = type(v) - if t in [str, unicode]: + if t in [str, str]: t = "str" - v = unicode(v) + v = str(v) elif t == bool: t = "bool" v = '1' if v else '0' - elif t in [int, long]: + elif t in [int, int]: t = "int" v = str(v).encode("utf-8") elif t == float: @@ -415,7 +421,7 @@ def __init__(self,playlist=Playlist([]),current=None,position=None): if len (self) == 0 : self.current = None else: - self.current = self.keys()[0] + self.current = list(self.keys())[0] else: self.current=playlist.current @@ -436,12 +442,12 @@ def get_current(self): return Track(None,None,None,None,None,None) def set_current(self,id): - if id in self.keys(): + if id in list(self.keys()): self.current=id else: logging.warning ("set_current: invalid id") - def next(self): + def __next__(self): self.current = self.nextid(self.current) logging.info ( "current: %s" % self.current) @@ -451,7 +457,7 @@ def nextid(self,id): if id is None: return None - keys=self.keys() + keys=list(self.keys()) ind = keys.index(id) if len(keys)-1 <= ind : @@ -471,7 +477,7 @@ def previousid(self,id): if id is None: return None - keys=self.keys() + keys=list(self.keys()) ind = keys.index(id) if ind == 0 : @@ -482,7 +488,7 @@ def previousid(self,id): def addtrack(self,uri,aftertrack=None,setascurrent=False): - keys=self.keys() + keys=list(self.keys()) if aftertrack is None: ind = max(len(keys)-1,0) @@ -504,7 +510,7 @@ def addtrack(self,uri,aftertrack=None,setascurrent=False): # here we have empty new list were copy old and new - for id,track in self.iteritems(): + for id,track in self.items(): newself[id]=track if id == aftertrack: p=Playlist([uri]) @@ -533,7 +539,7 @@ def removetrack(self,trackid): def write(self,path): - Playlist(tracks=self.values(),current=self.current,position=self.position).write(path) + Playlist(tracks=list(self.values()),current=self.current,position=self.position).write(path) def main(): @@ -548,34 +554,34 @@ def main(): uri=u"file:///home/pat1/Musica/Paolo Benvegnù/Piccoli fragilissimi film/2 - Cerchi nell'acqua.flac" - print "-------------- playlist ------------------" + print("-------------- playlist ------------------") p=Playlist(media) - print "--------- playlist ord dict -----------------------" + print("--------- playlist ord dict -----------------------") op=Playlist_mpris2(p) op.write("/tmp/tmp.xspf") - print "--------- playlist from file -----------------------" + print("--------- playlist from file -----------------------") p=Playlist(["/tmp/tmp.xspf"]) - print "--------- playlist from file ord dict -----------------------" + print("--------- playlist from file ord dict -----------------------") op=Playlist_mpris2(p) op=op.addtrack(uri,aftertrack="1") op=op.addtrack(uri,aftertrack="1",setascurrent=True) - print op + print(op) op.write("/tmp/tmpout.xspf") - print "--------- reread playlist from file ord dict -----------------------" + print("--------- reread playlist from file ord dict -----------------------") p=Playlist(["/tmp/tmpout.xspf"]) op=Playlist_mpris2(p) - print "remove ",op.current + print("remove ",op.current) op=op.removetrack("0") - print op + print(op) op.write("/tmp/tmpout2.xspf") if __name__ == '__main__': diff --git a/autoradio/autoradio_config.py b/autoradio/autoradio_config.py index b85b44f..1ad0990 100644 --- a/autoradio/autoradio_config.py +++ b/autoradio/autoradio_config.py @@ -1,6 +1,7 @@ #!/usr/bin/python # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function import os from configobj import ConfigObj,flatten_errors from validate import Validator @@ -44,7 +45,7 @@ section_string = ', '.join(section_list) if error == False: error = 'Missing value or section.' - print section_string, ' = ', error + print(section_string, ' = ', error) raise error # section autoradiod diff --git a/autoradio/autoradio_core.py b/autoradio/autoradio_core.py index 6877372..8e578f4 100644 --- a/autoradio/autoradio_core.py +++ b/autoradio/autoradio_core.py @@ -2,16 +2,24 @@ # -*- coding: utf-8 -*- # GPL. (C) 2007-2009 Paolo Patruno. -from autoradio_config import * - -from gest_program import * -from gest_spot import * -from gest_jingle import * -from gest_playlist import * -from gest_palimpsest import * - - -class schedule: +from __future__ import division +from __future__ import print_function +from __future__ import absolute_import +from builtins import zip +from builtins import str +from builtins import range +from past.utils import old_div +from builtins import object +from .autoradio_config import * + +from .gest_program import * +from .gest_spot import * +from .gest_jingle import * +from .gest_playlist import * +from .gest_palimpsest import * + + +class schedule(object): """ Single schedule object attributes: @@ -142,7 +150,7 @@ def districa(self): length=schedule.length type=schedule.type endscheduledatetime=scheduledatetime+timedelta(seconds=length) - halfscheduledatetime=scheduledatetime+timedelta(seconds=length/2) + halfscheduledatetime=scheduledatetime+timedelta(seconds=old_div(length,2)) if (type == "spot" or type == "playlist" or type == "jingle" ): continue @@ -222,7 +230,7 @@ def districa(self): length=schedule.adjustedlength type=schedule.type endscheduledatetime=scheduledatetime+timedelta(seconds=length) - halfscheduledatetime=scheduledatetime+timedelta(seconds=length/2) + halfscheduledatetime=scheduledatetime+timedelta(seconds=old_div(length,2)) if (type == "spot" or type == "playlist" or type == "jingle" ): continue @@ -308,8 +316,8 @@ def districa(self): def purge(self): - from itertools import izip - reverse_enumerate = lambda l: izip(xrange(len(l)-1, -1, -1), reversed(l)) + + reverse_enumerate = lambda l: zip(range(len(l)-1, -1, -1), reversed(l)) for ind,schedula in reverse_enumerate(self): if not schedula.filter(): @@ -334,7 +342,7 @@ def get_all(self,now=None,genfile=True): emission_done=spots.ar_emission_done number=spots.ar_spots_in_fascia #print scheduledatetime,media,length,number,emission_done - if (number <> 0 ): + if (number != 0 ): self.append(schedule(fascia,scheduledatetime,media,filename,length,"spot",emission_done,title=str(fascia))) @@ -401,7 +409,7 @@ def get_all_refine(self,now=None,genfile=True): -class palimpsest: +class palimpsest(object): def __init__ (self,title=None,datetime_start=None,datetime_end=None, @@ -484,7 +492,7 @@ def __iter__(self): -class dates: +class dates(object): def __init__(self,datetime_start, datetime_end,step): @@ -498,7 +506,7 @@ def __iter__(self): return self - def next(self): + def __next__(self): self.datetime_start=self.datetime_start+self.step if self.datetime_start <= self.datetime_end: @@ -574,7 +582,7 @@ def get_palimpsest(self,datetime_start,datetime_end): if self[i].datetime_end != self[i+1].datetime_start: - dtmean=self[i].datetime_end+((self[i+1].datetime_start-self[i].datetime_end)/2) + dtmean=self[i].datetime_end+(old_div((self[i+1].datetime_start-self[i].datetime_end),2)) self[i].datetime_end=dtmean self[i+1].datetime_start=dtmean @@ -624,7 +632,7 @@ def get_palimpsest(self,datetime_start,datetime_end): note="%d Spot" % number #if (number <> 0 and pdatetime_start.date() == dateelab): - if number <> 0 and pdatetime_start >= datetime_start and pdatetime_end < datetime_end : + if number != 0 and pdatetime_start >= datetime_start and pdatetime_end < datetime_end : self.append(palimpsest(title,pdatetime_start,pdatetime_end, type,subtype,production,note)) @@ -654,20 +662,20 @@ def main(): # get the schedule of my insterest # I do a list - print "------- schedules --------" + print("------- schedules --------") for sched in scheds.get_all_refine(): - print "------- schedule --------" + print("------- schedule --------") for elemento in sched: - print elemento + print(elemento) - print sched.type - print sched.media - print sched.scheduledatetime - print sched.shuffle - print sched.length + print(sched.type) + print(sched.media) + print(sched.scheduledatetime) + print(sched.shuffle) + print(sched.length) diff --git a/autoradio/autoxmms.py b/autoradio/autoxmms.py index eca4827..5d260f6 100644 --- a/autoradio/autoxmms.py +++ b/autoradio/autoxmms.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # GPL. (C) 2007-2009 Paolo Patruno. +from builtins import range import xmms import time import datetime @@ -72,7 +73,7 @@ def playlist_clear_up(atlast=10,session=0): # delete the old ones if pos > atlast : - for prm in xrange(0,pos-atlast): + for prm in range(0,pos-atlast): xmms.control.playlist_delete(0,session) return True @@ -100,7 +101,7 @@ def playlist_clear_down(atlast=500,session=0): #elimino il troppo if length-pos > atlast : - for prm in xrange(length,pos+atlast,-1): + for prm in range(length,pos+atlast,-1): xmms.control.playlist_delete(prm,session) return True diff --git a/autoradio/daemon.py b/autoradio/daemon.py index 4701926..07b0a1e 100644 --- a/autoradio/daemon.py +++ b/autoradio/daemon.py @@ -26,7 +26,7 @@ ## THE SOFTWARE. ## -ur""" +""" This module can be used on UNIX to fork a daemon process. It is based on `Jürgen Hermann's Cookbook recipe`__. @@ -77,6 +77,9 @@ def main(self): """ +from builtins import str +from past.builtins import basestring +from builtins import object import sys, os, signal, pwd, grp, optparse @@ -238,7 +241,7 @@ def start(self): pid = os.fork() if pid > 0: sys.exit(0) # Exit first parent - except OSError, exc: + except OSError as exc: sys.exit("%s: fork #1 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) # Decouple from parent environment @@ -251,7 +254,7 @@ def start(self): pid = os.fork() if pid > 0: sys.exit(0) # Exit second parent - except OSError, exc: + except OSError as exc: sys.exit("%s: fork #2 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) # Now I am a daemon! @@ -281,7 +284,7 @@ def stop(self): sys.exit("no pidfile specified") try: pidfile = open(self.options.pidfile, "rb") - except IOError, exc: + except IOError as exc: sys.exit("can't open pidfile %s: %s" % (self.options.pidfile, str(exc))) data = pidfile.read() try: diff --git a/autoradio/dir2ogg.py b/autoradio/dir2ogg.py index fda5175..3fdc694 100755 --- a/autoradio/dir2ogg.py +++ b/autoradio/dir2ogg.py @@ -32,7 +32,15 @@ m4a conversions require faad. Id3 tag support requires mutagen for mp3s. Scratch tags using the filename will be written for wav files (and mp3s with no tags!) ''' - +from __future__ import division +from __future__ import print_function + +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import range +from past.utils import old_div +from builtins import object import sys import os, os.path import re @@ -55,9 +63,9 @@ def mmatch(names, patterns, rbool=True): '''names/patterns=str/list/tuple''' results = [] - if isinstance(names, (str, unicode)): + if isinstance(names, str): names = [names] - if isinstance(patterns, (str, unicode)): + if isinstance(patterns, str): patterns = [patterns] for pat in patterns: pat = pat.lower() @@ -111,7 +119,7 @@ def read_opts(): 'cd': ('cdparanoia', 'icedax','cdda2wav', 'mplayer'), } - for ext, dec in commands.items(): + for ext, dec in list(commands.items()): default, choices = None, [] for command in dec: in_path = [prefix for prefix in os.environ['PATH'].split(os.pathsep) if os.path.exists(os.path.join(prefix, command))] @@ -125,7 +133,7 @@ def read_opts(): options.convert_cd = options.cdda options.filters = [] - for ext, pat in FILTERS.items(): + for ext, pat in list(FILTERS.items()): # Activate Encoders for files on the commandline if options.convert_all or mmatch(args, pat): setattr(options, 'convert_' + ext, True) @@ -140,15 +148,15 @@ def read_opts(): return options, args def info(msg): - print 'Information: %s' % msg + print('Information: %s' % msg) def warn(msg): '''print errors to the screen (red)''' - print >> sys.stderr, "Warning: %s" % msg + print("Warning: %s" % msg, file=sys.stderr) def fatal(msg): '''Fatal error (error + exit)''' - print >> sys.stderr, "Error: %s" % msg + print("Error: %s" % msg, file=sys.stderr) sys.exit(1) def return_dirs(root): @@ -158,7 +166,7 @@ def return_dirs(root): mydirs[pdir] = files return mydirs -class Id3TagHandler: +class Id3TagHandler(object): '''Class for handling meta-tags. (Needs mutagen)''' accept = ['album', 'album_subtitle', 'albumartist', 'albumartistsort', 'albumsort', 'artist', 'artistsort', 'asin', 'bpm', 'comment', @@ -179,15 +187,15 @@ def grab_common(self, handler, convert=None, error=None): '''Common grabber, starts the handler and applies the tags to self.tags''' try: mydict = handler(self.song) - except error, msg: + except error as msg: import warnings,traceback; warn('Mutagen failed on %s, no tags available' % self.song) traceback.print_exc(0) - print >> sys.stderr + print(file=sys.stderr) return if convert: - convert = dict([(k.lower(), v.lower()) for k, v in convert.items()]) # Fix convert - for key, val in mydict.items(): + convert = dict([(k.lower(), v.lower()) for k, v in list(convert.items())]) # Fix convert + for key, val in list(mydict.items()): key = key.lower() key = convert and (key in convert and convert[key] or key) or key if not key in self.accept: @@ -201,13 +209,13 @@ def grab_common(self, handler, convert=None, error=None): if not isinstance(val, list): val = [val] for i in val: - if not isinstance(i, unicode): + if not isinstance(i, str): # Convert all invalid values to unicode try: - new_val.append(unicode(i)) + new_val.append(str(i)) except UnicodeDecodeError: warn('Ignoring UnicodeDecodeError in key %s' % key) - new_val.append(unicode(i, errors='ignore')) + new_val.append(str(i, errors='ignore')) else: new_val.append(i) val = new_val @@ -314,7 +322,7 @@ def grab_mp3_tags(self): def list_if_verbose(self): info('Meta-tags I will write:') - for key, val in self.tags.items(): + for key, val in list(self.tags.items()): if type(val) == list: info(key + ': ' + ','.join(val)) else: @@ -345,7 +353,7 @@ def __init__(self, song, conf): # (smartmp3) I have to remember default quality for next files original_quality = self.conf.quality - for ext, pat in FILTERS.items(): + for ext, pat in list(FILTERS.items()): if mmatch(self.song, pat) and ext != 'wav': self.decoder = getattr(self.conf, ext + '_decoder') getattr(self, 'grab_%s_tags' % ext)() @@ -380,7 +388,7 @@ def smart_mp3(self): self.conf.quality = round(5.383 * math.log(0.01616 * bitrate/1000.) - self.conf.smart_mp3_correction, 2) self.conf.quality = max(self.conf.quality, -1) # Lowest quality is -1 self.conf.quality = min(self.conf.quality, 6) # Highest quality is 6 - info("(smartmp3) Detected bitrate: %d kbps" % (bitrate/1000)) + info("(smartmp3) Detected bitrate: %d kbps" % (old_div(bitrate,1000))) info("(smartmp3) Assumed vorbis quality: %.02f" % self.conf.quality) def decode(self): @@ -490,7 +498,7 @@ def __init__(self, device, conf, track, tags): self.decoder = 'cd-' + self.conf.cd_decoder self.convert() -class ConvertDisc: +class ConvertDisc(object): '''Wrapper around ConvertTrack to Convert complete cds Currently uses MusicBrainz, but a CDDB fallback will be added, too.''' def __init__(self, dev, conf): @@ -527,20 +535,20 @@ def get_cddb(self): title['genre'] = read_info['DGENRE'] title['date'] = read_info['DYEAR'] title['title'] = read_info['TTITLE' + str(track)] - title['tracktotal'] = str(len(range(disc_id[1])) + 1) + title['tracktotal'] = str(len(list(range(disc_id[1]))) + 1) title['ntracknumber'] = '0' * (len(title['tracktotal'] ) - len(str(track+1)) ) + str(track+1) title['tracknumber'] = str(track+1) - for key, val in title.items(): - title[key] = unicode(str(val), "ISO-8859-1") + for key, val in list(title.items()): + title[key] = str(str(val), "ISO-8859-1") ConvertTrack(self.dev, self.conf, track+1, title) def get_mb(self): try: import musicbrainz2.disc as mbdisc import musicbrainz2.webservice as mbws - except ImportError, err: + except ImportError as err: warn('You need python-musicbrainz2 (or python-cddb) to convert cds. Please install it. Trying cddb.') - raise self.MBError, err + raise self.MBError(err) service = mbws.WebService() query = mbws.Query(service) @@ -548,7 +556,7 @@ def get_mb(self): # Read the disc in the drive try: disc = mbdisc.readDisc(self.dev) - except mbdisc.DiscError, err: + except mbdisc.DiscError as err: warn(err) raise self.MBError @@ -556,18 +564,18 @@ def get_mb(self): try: myfilter = mbws.ReleaseFilter(discId=discId) results = query.getReleases(myfilter) - except mbws.WebServiceError, err: + except mbws.WebServiceError as err: warn(err) raise self.MBError if len(results) == 0: - print "Disc is not yet in the MusicBrainz database." - print "Consider adding it via", mbdisc.getSubmissionUrl(disc) + print("Disc is not yet in the MusicBrainz database.") + print("Consider adding it via", mbdisc.getSubmissionUrl(disc)) raise self.MBError try: inc = mbws.ReleaseIncludes(artist=True, tracks=True, releaseEvents=True) release = query.getReleaseById(results[0].release.getId(), inc) - except mbws.WebServiceError, err: + except mbws.WebServiceError as err: warn(err) raise self.MBError @@ -576,7 +584,7 @@ def get_mb(self): try: # try to get the CDDB ID import DiscID - cddb_id = '%08lx' % long(DiscID.disc_id(DiscID.open(self.dev))[0]) + cddb_id = '%08lx' % int(DiscID.disc_id(DiscID.open(self.dev))[0]) except: cddb_id = False @@ -600,7 +608,7 @@ def get_mb(self): ConvertTrack(self.dev, self.conf, trackn, title) trackn+=1 -class ConvertDirectory: +class ConvertDirectory(object): ''' This class is just a wrapper for Convert. @@ -630,20 +638,20 @@ def print_if_verbose(self): ''' Echo files to be converted if verbose flag is set.''' info('In %s I am going to convert:' % self.directory) for song in self.songs: - print " ", song + print(" ", song) def show_banner(): - print 'dir2ogg %s (%s), converts audio files into ogg vorbis.\n' % (__version__, __date__) + print('dir2ogg %s (%s), converts audio files into ogg vorbis.\n' % (__version__, __date__)) def show_license(*args, **kwargs): - print 'Copyright (C) 2007-2008 Julian Andres Klode ' - print 'Copyright (C) 2003-2006 Darren Kirby \n' - print 'This program is distributed in the hope that it will be useful,' - print 'but WITHOUT ANY WARRANTY; without even the implied warranty of' - print 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the' - print 'GNU General Public License for more details.\n' - print 'Currently developed by Julian Andres Klode .' + print('Copyright (C) 2007-2008 Julian Andres Klode ') + print('Copyright (C) 2003-2006 Darren Kirby \n') + print('This program is distributed in the hope that it will be useful,') + print('but WITHOUT ANY WARRANTY; without even the implied warranty of') + print('MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the') + print('GNU General Public License for more details.\n') + print('Currently developed by Julian Andres Klode .') sys.exit(0) def main(): @@ -662,7 +670,7 @@ def main(): rdirs.update(return_dirs(path)) elif conf.directory: rdirs.update({path: os.listdir(path)}) - for directory, files in rdirs.items(): + for directory, files in list(rdirs.items()): try: ConvertDirectory(conf, directory, files) except: diff --git a/autoradio/gest_jingle.py b/autoradio/gest_jingle.py index 0ba1e66..445b762 100644 --- a/autoradio/gest_jingle.py +++ b/autoradio/gest_jingle.py @@ -2,6 +2,9 @@ # This Python file uses the following encoding: utf-8 # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from __future__ import absolute_import +from builtins import object import os os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings' from django.conf import settings @@ -9,7 +12,7 @@ import logging from datetime import * -from autoradio_config import * +from .autoradio_config import * from django.db.models import Q from django.core.exceptions import ObjectDoesNotExist @@ -17,9 +20,9 @@ from itertools import * import calendar -from jingles.models import Configure -from jingles.models import Jingle -from jingles.models import Giorno +from .jingles.models import Configure +from .jingles.models import Jingle +from .jingles.models import Giorno # used to get metadata from audio files import mutagen @@ -46,7 +49,7 @@ def time_iterator(datesched_min,datesched_max,emission_freq): yield datac -class gest_jingle: +class gest_jingle(object): def __init__ (self,now,minelab): """init of jingle application: @@ -122,22 +125,22 @@ def get_jingle(self): many_jingles=cycle(self.jingles) -# for datac in time_iterator(self.datesched_min,self.datesched_max,self.emission_freq): + # for datac in time_iterator(self.datesched_min,self.datesched_max,self.emission_freq): for datac in time_iterator(self.now,self.datesched_max,self.emission_freq): - jingle=many_jingles.next() + jingle=next(many_jingles) jingle.ar_filename=jingle.file.path.encode("utf8") jingle.ar_url=jingle.file.url -# jingle.ar_filename=jingle.get_file_filename() + # jingle.ar_filename=jingle.get_file_filename() jingle.ar_scheduledatetime=datac jingle.ar_emission_done=jingle.emission_done # elaborate the media time length - try: - jingle.ar_length=mutagen.File(jingle.ar_filename).info.length + try: + jingle.ar_length=mutagen.File(jingle.ar_filename).info.length logging.debug("JINGLE: time length: %s",jingle.ar_length) - except: + except: logging.error("JINGLE: error establish time length; use an estimation %s", jingle.ar_filename) - jingle.ar_length=30 + jingle.ar_length=30 yield jingle @@ -149,16 +152,16 @@ def main(): for jingle in jingles.get_jingle(): - print "----------------------------" - print jingle - print jingle.ar_url - print jingle.ar_filename - print jingle.ar_scheduledatetime - print jingle.ar_length - print jingle.ar_emission_done + print("----------------------------") + print(jingle) + print(jingle.ar_url) + print(jingle.ar_filename) + print(jingle.ar_scheduledatetime) + print(jingle.ar_length) + print(jingle.ar_emission_done) for giorno in jingle.giorni.all(): - print giorno + print(giorno) if __name__ == '__main__': main() # (this code was run as script) diff --git a/autoradio/gest_palimpsest.py b/autoradio/gest_palimpsest.py index ac6149c..1689c7f 100644 --- a/autoradio/gest_palimpsest.py +++ b/autoradio/gest_palimpsest.py @@ -1,6 +1,9 @@ #!/usr/bin/env python # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from __future__ import absolute_import +from builtins import object import os os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings' from django.conf import settings @@ -8,16 +11,16 @@ import logging from datetime import * -from autoradio_config import * +from .autoradio_config import * from django.db.models import Q -from programs.models import Configure -from programs.models import PeriodicSchedule -from programs.models import AperiodicSchedule +from .programs.models import Configure +from .programs.models import PeriodicSchedule +from .programs.models import AperiodicSchedule import os,calendar -class gest_palimpsest: +class gest_palimpsest(object): def __init__ (self,datetimeelab,minelab): """init of palimpsest application: @@ -166,16 +169,16 @@ def main(): pro=gest_palimpsest(datetimeelab,minelab) for info in pro.get_info(): - print "info: ",info + print("info: ",info) # I do a list for program in pro.get_program(): #pass - print program - print program.ar_scheduledatetime - print program.program.length - print "program",program.program + print(program) + print(program.ar_scheduledatetime) + print(program.program.length) + print("program",program.program) if __name__ == '__main__': main() # (this code was run as script) diff --git a/autoradio/gest_playlist.py b/autoradio/gest_playlist.py index ef31e3c..85d4e47 100644 --- a/autoradio/gest_playlist.py +++ b/autoradio/gest_playlist.py @@ -2,6 +2,10 @@ # -*- coding: utf-8 -*- # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from __future__ import absolute_import +from builtins import str +from builtins import object import os os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings' from django.conf import settings @@ -9,20 +13,20 @@ import logging import datetime -from autoradio_config import * +from .autoradio_config import * from django.db.models import Q -from playlists.models import Configure -from playlists.models import PeriodicSchedule -from playlists.models import Schedule -from playlists.models import Playlist +from .playlists.models import Configure +from .playlists.models import PeriodicSchedule +from .playlists.models import Schedule +from .playlists.models import Playlist if (player == "amarok") : from autoradiod import amarok import os,calendar -class gest_playlist: +class gest_playlist(object): def __init__ (self,now,minelab): """init of playlist application: @@ -80,8 +84,8 @@ def __init__ (self,now,minelab): # warning here we are around midnight logging.debug("PLAYLIST: around midnight") - ieri=unicode(calendar.day_name[self.datesched_min.weekday()], 'utf-8') - domani=unicode(calendar.day_name[self.datesched_max.weekday()], 'utf-8') + ieri=str(calendar.day_name[self.datesched_min.weekday()], 'utf-8') + domani=str(calendar.day_name[self.datesched_max.weekday()], 'utf-8') self.periodicschedule=PeriodicSchedule.objects.filter \ (Q(start_date__lte=self.oggi) | Q(start_date__isnull=True),\ @@ -193,8 +197,8 @@ def main(): for hour in (0,3,6,9,12,15,18,21): now=now.replace(hour=hour) - print - print "Runnig for date: ",now + print() + print("Runnig for date: ",now) # get the playlists of my insterest pla=gest_playlist(now,minelab) @@ -202,15 +206,15 @@ def main(): # I do a list for playlist in pla.get_playlist(): - print "--------------------------------" - print "found schedule: ",playlist - print playlist.ar_filename - print playlist.ar_url - print playlist.ar_scheduledatetime - print playlist.ar_length - print "playlist",playlist.playlist + print("--------------------------------") + print("found schedule: ",playlist) + print(playlist.ar_filename) + print(playlist.ar_url) + print(playlist.ar_scheduledatetime) + print(playlist.ar_length) + print("playlist",playlist.playlist) #.program.get_file_filename() - print "--------------------------------" + print("--------------------------------") if __name__ == '__main__': main() # (this code was run as script) diff --git a/autoradio/gest_program.py b/autoradio/gest_program.py index 382a6ea..99544e3 100644 --- a/autoradio/gest_program.py +++ b/autoradio/gest_program.py @@ -1,6 +1,9 @@ #!/usr/bin/env python # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from __future__ import absolute_import +from builtins import object import os os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings' from django.conf import settings @@ -8,18 +11,18 @@ import logging from datetime import * -from autoradio_config import * +from .autoradio_config import * -from programs.models import Schedule -from programs.models import ScheduleDone -from programs.models import Show -from programs.models import Configure +from .programs.models import Schedule +from .programs.models import ScheduleDone +from .programs.models import Show +from .programs.models import Configure # to get metadata from audio files import mutagen import os -class gest_program: +class gest_program(object): def __init__ (self,now,minelab): """init of program application: @@ -131,10 +134,10 @@ def main(): #pass - print programma.ar_filename - print programma.ar_url - print programma.ar_scheduledatetime - print programma.ar_length + print(programma.ar_filename) + print(programma.ar_url) + print(programma.ar_scheduledatetime) + print(programma.ar_length) #programma.program.get_file_filename() diff --git a/autoradio/gest_spot.py b/autoradio/gest_spot.py index e7798d3..9196c97 100644 --- a/autoradio/gest_spot.py +++ b/autoradio/gest_spot.py @@ -2,18 +2,21 @@ # This Python file uses the following encoding: utf-8 # GPL. (C) 2007-2009 Paolo Patruno. +from __future__ import print_function +from __future__ import absolute_import +from builtins import object import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings' from django.conf import settings import logging import datetime -from autoradio_config import * +from .autoradio_config import * from django.db.models import Q -from spots.models import Configure -from spots.models import Spot -from spots.models import Fascia -from spots.models import Giorno +from .spots.models import Configure +from .spots.models import Spot +from .spots.models import Fascia +from .spots.models import Giorno import time #used to get metadata from audio files @@ -21,7 +24,7 @@ import tempfile,shutil -class gest_spot: +class gest_spot(object): def __init__ (self,now,minelab,playlistdir): """init of spot application: @@ -193,22 +196,22 @@ def get_fascia_playlist_media(self,genfile=True): f.write("\n") # calcolo la lunghezza della fascia - try: + try: filename=filename.encode("utf8") onelength=mutagen.File(filename).info.length logging.debug("SPOT: computed the partial time length: %d",onelength) - length=length+onelength - except: + length=length+onelength + except: logging.error( "SPOT: error establish time length; use an estimation %s", filename) - length=length+30 + length=length+30 self.ar_length=length logging.debug("SPOT: computed total time length: %d",self.ar_length) if genfile : f.close() - os.chmod(tmpfile,0644) + os.chmod(tmpfile,0o644) #sometime I get: @@ -254,10 +257,10 @@ def main(): pass #print "fascia and spot ->",spots.fascia,spot - print spots.ar_filename - print spots.ar_scheduledatetime - print spots.ar_length - print spots.ar_spots_in_fascia + print(spots.ar_filename) + print(spots.ar_scheduledatetime) + print(spots.ar_length) + print(spots.ar_spots_in_fascia) if __name__ == '__main__': diff --git a/autoradio/jingles/admin.py b/autoradio/jingles/admin.py index e7df0bf..4510b11 100644 --- a/autoradio/jingles/admin.py +++ b/autoradio/jingles/admin.py @@ -1,4 +1,6 @@ -from models import Giorno, Configure, Jingle +from __future__ import absolute_import +from builtins import object +from .models import Giorno, Configure, Jingle from django.contrib import admin from django import forms from django.utils.translation import ugettext_lazy @@ -13,7 +15,7 @@ class MyJingleAdminForm(forms.ModelForm): """ Check file if it is a known media file. """ - class Meta: + class Meta(object): model = Jingle fields = '__all__' diff --git a/autoradio/jingles/models.py b/autoradio/jingles/models.py index 87ebe5d..3624e42 100644 --- a/autoradio/jingles/models.py +++ b/autoradio/jingles/models.py @@ -1,3 +1,4 @@ +from builtins import object from django.db import models from django.utils.translation import ugettext_lazy import calendar @@ -42,12 +43,12 @@ def delete_file(self, instance, sender, **kwargs): DeletingFileField=models.FileField def giorno_giorno(): - giorni=[] - for giorno in (calendar.day_name): - giorno=giorno.decode('utf-8') - giorni.append(( giorno, giorno)) - return giorni -# yield 'Tutti','Tutti' + giorni=[] + for giorno in (calendar.day_name): + #giorno=giorno.decode('utf-8') + giorni.append(( giorno, giorno)) + return giorni +# yield 'Tutti','Tutti' class Giorno(models.Model): @@ -57,13 +58,13 @@ class Giorno(models.Model): def __unicode__(self): return self.name - class Admin: - search_fields = ['name'] + class Admin(object): + search_fields = ['name'] class Configure(models.Model): sezione = models.CharField(max_length=50,unique=True,default='jingle',editable=False) - active = models.BooleanField(ugettext_lazy("Activate Jingle"),default=True, + active = models.BooleanField(ugettext_lazy("Activate Jingle"),default=True, help_text=ugettext_lazy("activate/deactivate the intere jingle class")) emission_freq = models.TimeField(ugettext_lazy('Frequency')) @@ -71,52 +72,52 @@ class Configure(models.Model): def __unicode__(self): return self.sezione+" "+self.active.__str__()+" "+self.emission_freq.isoformat() - class Admin: - list_display = ('sezione','active','emission_freq',) + class Admin(object): + list_display = ('sezione','active','emission_freq',) class Jingle(models.Model): - - jingle = models.CharField(ugettext_lazy("Jingle name"),max_length=80,unique=True) - file = DeletingFileField(ugettext_lazy('File'),upload_to='jingles',max_length=255,\ + + jingle = models.CharField(ugettext_lazy("Jingle name"),max_length=80,unique=True) + file = DeletingFileField(ugettext_lazy('File'),upload_to='jingles',max_length=255,\ help_text=ugettext_lazy("The jingle file to upload")) - rec_date = models.DateTimeField(ugettext_lazy('Recording date'),\ + rec_date = models.DateTimeField(ugettext_lazy('Recording date'),\ help_text=ugettext_lazy("When the jingle was done (for reference only)")) - active = models.BooleanField(ugettext_lazy("Active"),default=True,\ + active = models.BooleanField(ugettext_lazy("Active"),default=True,\ help_text=ugettext_lazy("Activate the jingle for emission")) - start_date = models.DateField(ugettext_lazy('Emission starting date'),null=True,blank=True,\ + start_date = models.DateField(ugettext_lazy('Emission starting date'),null=True,blank=True,\ help_text=ugettext_lazy("The jingle will be scheduled starting from this date")) - end_date = models.DateField(ugettext_lazy('Emission end date'),null=True,blank=True,\ + end_date = models.DateField(ugettext_lazy('Emission end date'),null=True,blank=True,\ help_text=ugettext_lazy("The jingle will be scheduled ending this date")) - start_time = models.TimeField(ugettext_lazy('Emission start time'),null=True,blank=True,\ + start_time = models.TimeField(ugettext_lazy('Emission start time'),null=True,blank=True,\ help_text=ugettext_lazy("The jingle will be scheduled starting from this date")) - end_time = models.TimeField(ugettext_lazy('Emission end time'),null=True,blank=True,\ + end_time = models.TimeField(ugettext_lazy('Emission end time'),null=True,blank=True,\ help_text=ugettext_lazy("The jingle will be scheduled ending this date")) - giorni = models.ManyToManyField(Giorno,verbose_name=ugettext_lazy('Scheduled days'),blank=True,\ + giorni = models.ManyToManyField(Giorno,verbose_name=ugettext_lazy('Scheduled days'),blank=True,\ help_text=ugettext_lazy("The jingle will be scheduled those weekdays")) - priorita = models.IntegerField(ugettext_lazy("Priority"),default=50,\ + priorita = models.IntegerField(ugettext_lazy("Priority"),default=50,\ help_text=ugettext_lazy("When there are more jingle that wait for emission from the same time, the emission will be ordered by this numer")) - emission_done = models.DateTimeField(ugettext_lazy('emission done'),null=True,editable=False ) + emission_done = models.DateTimeField(ugettext_lazy('emission done'),null=True,editable=False ) - - def was_recorded_today(self): - return self.rec_date.date() == datetime.date.today() + + def was_recorded_today(self): + return self.rec_date.date() == datetime.date.today() - was_recorded_today.short_description = ugettext_lazy('Recorded today?') - - def __unicode__(self): - return self.jingle - - class Admin: - fields = ( - (None, {'fields': ('jingle','file','rec_date','active')}), - ('Emission information', {'fields': ('start_date','end_date','start_time','end_time','giorni','priorita')}), - ) - list_display = ('jingle','file','rec_date','emission_done') - list_filter = ['start_date','end_date','start_time','end_time','giorni'] - date_hierarchy = 'rec_date' - search_fields = ['jingle'] - - #class Meta: - # unique_together = ("prologo", "epilogo","fasce") + was_recorded_today.short_description = ugettext_lazy('Recorded today?') + + def __unicode__(self): + return self.jingle + + class Admin(object): + fields = ( + (None, {'fields': ('jingle','file','rec_date','active')}), + ('Emission information', {'fields': ('start_date','end_date','start_time','end_time','giorni','priorita')}), + ) + list_display = ('jingle','file','rec_date','emission_done') + list_filter = ['start_date','end_date','start_time','end_time','giorni'] + date_hierarchy = 'rec_date' + search_fields = ['jingle'] + + #class Meta: + # unique_together = ("prologo", "epilogo","fasce") diff --git a/autoradio/manageamarok.py b/autoradio/manageamarok.py index 36d9542..c9d8f0c 100644 --- a/autoradio/manageamarok.py +++ b/autoradio/manageamarok.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # GPL. (C) 2007 Paolo Patruno. +from builtins import str +from builtins import object import logging from qt import * import dcopext @@ -24,7 +26,7 @@ def KdeInit(): KCmdLineArgs.init(aboutdata) return KApplication () -class Kde: +class Kde(object): def __init__ (self,kapp): "init of kde application" @@ -36,7 +38,7 @@ def connect(self,application): self.dcopapplication = dcopext.DCOPApp(application, self.dcopclient) -class ScheduleProgram: +class ScheduleProgram(object): def __init__ (self,kapp,function,operation,media,scheduledatetime,programma): "init schedule" @@ -124,7 +126,7 @@ def secondi(delta): -class dummy_programma: +class dummy_programma(object): def __init__(self): pass diff --git a/autoradio/manageaudacious.py b/autoradio/manageaudacious.py index 16d6695..593ec4f 100644 --- a/autoradio/manageaudacious.py +++ b/autoradio/manageaudacious.py @@ -1,14 +1,19 @@ #!/usr/bin/env python # GPL. (C) 2007 Paolo Patruno. +from __future__ import division +from __future__ import absolute_import +from builtins import str +from past.utils import old_div +from builtins import object import logging import dbus -import autoaudacious +from . import autoaudacious from datetime import * from threading import * from django.conf import settings import os -import autoradio_config +from . import autoradio_config class AudaciousError(Exception): @@ -18,7 +23,7 @@ def __str__(self): def shuffle_playlist(infile,shuffle=False,relative_path=False,length=None): - import mkplaylist + from . import mkplaylist import os,random,tempfile,codecs media_files=list(mkplaylist.read_playlist(infile, not relative_path)) @@ -51,7 +56,7 @@ def ar_emitted(self): self.save() -class ScheduleProgram: +class ScheduleProgram(object): ''' activate a schedule setting it for a time in the future ''' @@ -132,7 +137,7 @@ def ManageAudacious (session,schedule): ar_emitted(schedule.djobj) logging.info( "ManageAudacious: write in django: %s",schedule.djobj) - except AudaciousError, e: + except AudaciousError as e: logging.error(e) @@ -142,14 +147,14 @@ def ManageAudacious (session,schedule): def secondi(delta): secondi=float(delta.seconds) - secondi=secondi+(delta.microseconds/100000.) + secondi=secondi+(old_div(delta.microseconds,100000.)) if delta.days < 0 : secondi = secondi + (3600*24*delta.days) return secondi -class dummy_programma: +class dummy_programma(object): def __init__(self): pass @@ -232,7 +237,7 @@ def save_status(session): def main(): - import autoradio_core + from . import autoradio_core programma=dummy_programma() audacious_watchdog(0) diff --git a/autoradio/managempris.py b/autoradio/managempris.py index c3d26b2..ae699d2 100644 --- a/autoradio/managempris.py +++ b/autoradio/managempris.py @@ -1,14 +1,19 @@ #!/usr/bin/env python # GPL. (C) 2007-2012 Paolo Patruno. +from __future__ import division +from __future__ import absolute_import +from builtins import str +from past.utils import old_div +from builtins import object import logging import dbus -import autompris -import autompris2 +from . import autompris +from . import autompris2 from datetime import * from threading import * import os -import autoradio_config +from . import autoradio_config os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' @@ -23,7 +28,7 @@ def __str__(self): def shuffle_playlist(infile,shuffle=False,relative_path=False,length=None): - import mkplaylist + from . import mkplaylist import os,random,tempfile,codecs media_files=list(mkplaylist.read_playlist(infile, not relative_path)) @@ -56,7 +61,7 @@ def ar_emitted(self): self.save() -class ScheduleProgram: +class ScheduleProgram(object): ''' activate a schedule setting it for a time in the future ''' @@ -160,10 +165,10 @@ def ManagePlayer (player,session,schedule): aud.play_ifnot() - except PlayerError, e: + except PlayerError as e: logging.error(e) - except dbus.DBusException, e: + except dbus.DBusException as e: logging.error(e) except: @@ -175,14 +180,14 @@ def ManagePlayer (player,session,schedule): def secondi(delta): secondi=float(delta.seconds) - secondi=secondi+(delta.microseconds/100000.) + secondi=secondi+(old_div(delta.microseconds,100000.)) if delta.days < 0 : secondi = secondi + (3600*24*delta.days) return secondi -class dummy_programma: +class dummy_programma(object): def __init__(self): pass @@ -254,7 +259,7 @@ def save_status(session): def main(): - import autoradio_core + from . import autoradio_core player="AutoPlayer" session=0 diff --git a/autoradio/managepytone.py b/autoradio/managepytone.py index 5f07b57..cbcb375 100644 --- a/autoradio/managepytone.py +++ b/autoradio/managepytone.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from builtins import object import os,sys import events, network, requests, version, helper from datetime import * @@ -10,7 +12,7 @@ def ar_emitted(self): self.save() -class ScheduleProgram: +class ScheduleProgram(object): def __init__ (self,function,operation,media,scheduledatetime,programma): "init schedule" @@ -22,9 +24,9 @@ def __init__ (self,function,operation,media,scheduledatetime,programma): self.programma=programma scheduledatetime - print "differenza ",datetime.now(),self.scheduledatetime + print("differenza ",datetime.now(),self.scheduledatetime) delta=( self.scheduledatetime - datetime.now()) - print delta + print(delta) #self.deltasec=max(secondi(delta),1) self.deltasec=secondi(delta) @@ -43,14 +45,14 @@ def ManagePytone (operation,media,programma): unixsocketfile = os.path.expanduser("~/.pytone/pytonectl") networklocation = unixsocketfile - print networklocation + print(networklocation) try: channel = network.clientchannel(networklocation) - except Exception, e: + except Exception as e: - print "Error: cannot connect to PyTone server: %s" % e + print("Error: cannot connect to PyTone server: %s" % e) sys.exit(2) channel.start() @@ -68,7 +70,7 @@ def ManagePytone (operation,media,programma): medias=(media,) for mediasplit in medias: - print "invio ->",mediasplit + print("invio ->",mediasplit) if operation == "queueMedia": song = channel.request(\ requests.autoregisterer_queryregistersong("main", mediasplit)) @@ -77,10 +79,10 @@ def ManagePytone (operation,media,programma): channel.quit() - print "scrivo in django" - print programma + print("scrivo in django") + print(programma) ar_emitted(programma) - print "scritto in django" + print("scritto in django") def secondi(delta): @@ -90,13 +92,13 @@ def secondi(delta): secondi = secondi + (3600*24*delta.days) return secondi -class dummy_programma: +class dummy_programma(object): def __init__(self): pass def save(self): - print "faccio finta di salvarlo" + print("faccio finta di salvarlo") def main(): diff --git a/autoradio/managexmms.py b/autoradio/managexmms.py index df10637..1b8f2fa 100644 --- a/autoradio/managexmms.py +++ b/autoradio/managexmms.py @@ -1,13 +1,18 @@ #!/usr/bin/env python # GPL. (C) 2007 Paolo Patruno. +from __future__ import division +from __future__ import absolute_import +from builtins import str +from past.utils import old_div +from builtins import object import logging import xmms,autoxmms from datetime import * from threading import * from django.conf import settings import os -import autoradio_config +from . import autoradio_config #import signal class XmmsError(Exception): @@ -16,7 +21,7 @@ class XmmsError(Exception): def shuffle_playlist(infile,shuffle=False,relative_path=False,length=None): - import mkplaylist + from . import mkplaylist import os,random,tempfile,codecs media_files=list(mkplaylist.read_playlist(infile, not relative_path)) @@ -49,7 +54,7 @@ def ar_emitted(self): self.save() -class ScheduleProgram: +class ScheduleProgram(object): ''' activate a schedule setting it for a time in the future ''' @@ -143,7 +148,7 @@ def ManageXmms (session,schedule): ar_emitted(schedule.djobj) logging.info( "ManageXmms: write in django: %s",schedule.djobj) - except XmmsError, e: + except XmmsError as e: logging.error(e.message) #except: @@ -155,7 +160,7 @@ def ManageXmms (session,schedule): def secondi(delta): secondi=float(delta.seconds) - secondi=secondi+(delta.microseconds/100000.) + secondi=secondi+(old_div(delta.microseconds,100000.)) # correggo i viaggi che si fa seconds if delta.days < 0 : secondi = secondi + (3600*24*delta.days) @@ -163,7 +168,7 @@ def secondi(delta): -class dummy_programma: +class dummy_programma(object): def __init__(self): pass @@ -223,7 +228,7 @@ def save_status(session): def main(): - import autoradio_core + from . import autoradio_core programma=dummy_programma() diff --git a/autoradio/mkplaylist.py b/autoradio/mkplaylist.py index 357dd13..a24b5ea 100755 --- a/autoradio/mkplaylist.py +++ b/autoradio/mkplaylist.py @@ -28,6 +28,12 @@ It is not necessary to have the version of the vorbis library in ogg meta data for example. """ +from __future__ import print_function +from past.builtins import cmp +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import object import sys import os import os.path @@ -35,7 +41,7 @@ import logging from itertools import chain import mutagen -import urllib2 +import urllib.request, urllib.error, urllib.parse __author__ = "Marc 'BlackJack' Rintsch " __version__ = '0.6.0' @@ -108,7 +114,7 @@ def metadata_reader(path): #----------------------------------------------------------------------------- -class PlaylistEntry: +class PlaylistEntry(object): """A generic playlist entry with a `path` attribute and dictionary like behavior for meta data. @@ -168,7 +174,7 @@ def __unicode__(self): log.info("Could not decode UTF-8: %s ",self.path) return "" -class PlaylistEntryFactory: +class PlaylistEntryFactory(object): """A media file factory allows registritation of media file types, their file name extensions and functions for reading meta data from the files. @@ -257,7 +263,7 @@ def write_m3u(playlist, outfile,timelen=None): continue if totaltime < timelen or timelen is None : - print >> outfile, unicode(entry) + print(str(entry), file=outfile) i+=1 else: break @@ -269,7 +275,7 @@ def write_extm3u(playlist, outfile,timelen=None): totaltime=0. i=0 - print >> outfile, '#EXTM3U' + print('#EXTM3U', file=outfile) for entry in playlist: if not entry['TIME'] is None : totaltime += entry['TIME'] @@ -282,11 +288,11 @@ def write_extm3u(playlist, outfile,timelen=None): time=entry['TIME'] if time is None : time = -1 if entry['ARTIST'] and entry['TITLE']: - print >> outfile, '#EXTINF:%s,%s - %s' % (time, + print('#EXTINF:%s,%s - %s' % (time, entry['ARTIST'], - entry['TITLE']) + entry['TITLE']), file=outfile) - print >> outfile, unicode(entry) + print(str(entry), file=outfile) i+=1 else: @@ -301,8 +307,8 @@ def write_pls(playlist, outfile,timelen=None): :todo: Add command line option for playlist title. """ totaltime=0. - print >> outfile, '[playlist]' - print >> outfile, 'PlaylistName=Playlist' + print('[playlist]', file=outfile) + print('PlaylistName=Playlist', file=outfile) i = 0 for i, entry in enumerate(playlist): if not entry['TIME'] is None : @@ -314,17 +320,17 @@ def write_pls(playlist, outfile,timelen=None): if totaltime < timelen or timelen is None : i += 1 - print >> outfile, 'File%d=%s' % (i, entry) + print('File%d=%s' % (i, entry), file=outfile) title = entry['TITLE'] or os.path.basename(str(entry)) - print >> outfile, 'Title%d=%s' % (i, title) - print >> outfile, 'Length%d=%s' % (i, entry['TIME']) + print('Title%d=%s' % (i, title), file=outfile) + print('Length%d=%s' % (i, entry['TIME']), file=outfile) else: break - print >> outfile, 'NumberOfEntries=%d' % i - print >> outfile, 'Version=2' + print('NumberOfEntries=%d' % i, file=outfile) + print('Version=2', file=outfile) log.info("That's %d out file(s).", i) @@ -455,9 +461,9 @@ def main(): help="name of the output file or '-' for stdout (default)") parser.add_option("-f", "--output-format", type="choice", dest="output_format", default="extm3u", - choices=WRITERS.keys(), + choices=list(WRITERS.keys()), help="format of the output %r (default: %%default)" % - WRITERS.keys()) + list(WRITERS.keys())) parser.add_option("-r", "--relative-paths", action="store_true", dest="relative_paths", default=False, help="write relative paths. (default: absolute paths)") diff --git a/autoradio/mpris2/__init__.py b/autoradio/mpris2/__init__.py index 33c2145..90d8414 100644 --- a/autoradio/mpris2/__init__.py +++ b/autoradio/mpris2/__init__.py @@ -91,21 +91,23 @@ ''' +from __future__ import print_function +from __future__ import absolute_import -from interfaces import Interfaces -from mediaplayer2 import MediaPlayer2 -from player import Player -from playlists import Playlists -from tracklist import TrackList +from .interfaces import Interfaces +from .mediaplayer2 import MediaPlayer2 +from .player import Player +from .playlists import Playlists +from .tracklist import TrackList -import types as types -import utils as utils +from . import types as types +from . import utils as utils if __name__ == '__main__': - print Interfaces - print MediaPlayer2 - print Player - print Playlists - print TrackList - print types - print utils + print(Interfaces) + print(MediaPlayer2) + print(Player) + print(Playlists) + print(TrackList) + print(types) + print(utils) diff --git a/autoradio/mpris2/interfaces.py b/autoradio/mpris2/interfaces.py index d35487f..006d372 100644 --- a/autoradio/mpris2/interfaces.py +++ b/autoradio/mpris2/interfaces.py @@ -5,6 +5,7 @@ http://www.mpris.org/2.1/spec/index.html """ +from builtins import object class Interfaces(object): """ This class contains the constants defined at index of MPRIS2 definition: diff --git a/autoradio/mpris2/loop_status.py b/autoradio/mpris2/loop_status.py index 6047d00..3cc299b 100644 --- a/autoradio/mpris2/loop_status.py +++ b/autoradio/mpris2/loop_status.py @@ -1,3 +1,4 @@ +from __future__ import print_function NONE = 'None' TRACK = 'Track' PLAYLIST = 'Playlist' @@ -27,7 +28,7 @@ def __int__(self, *args, **kwargs): Loop_Status.PLAYLIST = Loop_Status(PLAYLIST) if __name__ == "__main__": - print Loop_Status.PLAYLIST - print type(Loop_Status.PLAYLIST) - print Loop_Status.PLAYLIST == NONE - print Loop_Status.PLAYLIST == PLAYLIST \ No newline at end of file + print(Loop_Status.PLAYLIST) + print(type(Loop_Status.PLAYLIST)) + print(Loop_Status.PLAYLIST == NONE) + print(Loop_Status.PLAYLIST == PLAYLIST) \ No newline at end of file diff --git a/autoradio/mpris2/mediaplayer2.py b/autoradio/mpris2/mediaplayer2.py index 372d032..95f3645 100644 --- a/autoradio/mpris2/mediaplayer2.py +++ b/autoradio/mpris2/mediaplayer2.py @@ -3,6 +3,8 @@ http://www.mpris.org/2.1/spec/Root_Node.html """ +from __future__ import print_function +from __future__ import absolute_import from autoradio.pydbusdecorator.dbus_attr import DbusAttr @@ -10,7 +12,7 @@ from autoradio.pydbusdecorator.dbus_method import DbusMethod from autoradio.pydbusdecorator.dbus_signal import DbusSignal -from interfaces import Interfaces +from .interfaces import Interfaces class MediaPlayer2(Interfaces): @@ -178,7 +180,7 @@ def PropertiesChanged(self, *args, **kw): from mpris2.utils import SomePlayers uri = Interfaces.MEDIA_PLAYER + '.' + SomePlayers.GMUSICBROWSER mp2 = MediaPlayer2(dbus_interface_info={'dbus_uri': uri}) - print mp2.SupportedUriSchemes + print(mp2.SupportedUriSchemes) # # # from dbus.mainloop.glib import DBusGMainLoop diff --git a/autoradio/mpris2/metada_map.py b/autoradio/mpris2/metada_map.py index efeb699..0ff0c1f 100644 --- a/autoradio/mpris2/metada_map.py +++ b/autoradio/mpris2/metada_map.py @@ -1,3 +1,4 @@ +from __future__ import print_function class Metadata_Map(dict): ''' A mapping from metadata attribute names to values. @@ -48,4 +49,4 @@ def metadata(self): if __name__ == "__main__": mdm = Metadata_Map({Metadata_Map.ALBUM : "Marcelo Nova Ao Vivo"}) - print mdm[Metadata_Map.ALBUM] \ No newline at end of file + print(mdm[Metadata_Map.ALBUM]) \ No newline at end of file diff --git a/autoradio/mpris2/playback_rate.py b/autoradio/mpris2/playback_rate.py index 07d7c79..83bc0a0 100644 --- a/autoradio/mpris2/playback_rate.py +++ b/autoradio/mpris2/playback_rate.py @@ -1,3 +1,4 @@ +from __future__ import print_function class Playback_Rate(float): ''' A playback rate @@ -17,4 +18,4 @@ def rate(self): if __name__ == "__main__": pr = Playback_Rate(12) - print pr == '12' \ No newline at end of file + print(pr == '12') \ No newline at end of file diff --git a/autoradio/mpris2/player.py b/autoradio/mpris2/player.py index 89b0360..9df8a7c 100644 --- a/autoradio/mpris2/player.py +++ b/autoradio/mpris2/player.py @@ -3,14 +3,16 @@ http://www.mpris.org/2.1/spec/Player_Node.html ''' +from __future__ import print_function +from __future__ import absolute_import from autoradio.pydbusdecorator.dbus_attr import DbusAttr from autoradio.pydbusdecorator.dbus_interface import DbusInterface from autoradio.pydbusdecorator.dbus_method import DbusMethod from autoradio.pydbusdecorator.dbus_signal import DbusSignal -from interfaces import Interfaces -from types import Time_In_Us, Loop_Status, Playback_Status, \ +from .interfaces import Interfaces +from .types import Time_In_Us, Loop_Status, Playback_Status, \ Playback_Rate, Metadata_Map, Volume @@ -449,11 +451,11 @@ def CanControl(self): import gobject def my_handler(self, Position): - print 'handled', Position, type(Position) - print 'self handled', self.last_fn_return, type(self.last_fn_return) + print('handled', Position, type(Position)) + print('self handled', self.last_fn_return, type(self.last_fn_return)) def another_handler(self, *args, **kw): - print args, kw + print(args, kw) mloop = gobject.MainLoop() #print mp2.Seeked diff --git a/autoradio/mpris2/playlist.py b/autoradio/mpris2/playlist.py index 4953619..911efa2 100644 --- a/autoradio/mpris2/playlist.py +++ b/autoradio/mpris2/playlist.py @@ -59,7 +59,7 @@ def Valid(self): def Playlist(self): return Playlist(self[1]) - def __nonzero__(self): + def __bool__(self): return bool(self.Valid) def __bool__(self): diff --git a/autoradio/mpris2/playlists.py b/autoradio/mpris2/playlists.py index 0d8eba8..5a7a0b8 100644 --- a/autoradio/mpris2/playlists.py +++ b/autoradio/mpris2/playlists.py @@ -4,12 +4,14 @@ http://www.mpris.org/2.1/spec/Playlists.html ''' +from __future__ import print_function +from __future__ import absolute_import from autoradio.pydbusdecorator.dbus_attr import DbusAttr from autoradio.pydbusdecorator.dbus_interface import DbusInterface from autoradio.pydbusdecorator.dbus_method import DbusMethod from autoradio.pydbusdecorator.dbus_signal import DbusSignal -from interfaces import Interfaces -from types import Playlist, Maybe_Playlist +from .interfaces import Interfaces +from .types import Playlist, Maybe_Playlist from dbus import UInt32 @@ -126,13 +128,13 @@ def ActivePlaylist(self): from mpris2.utils import SomePlayers uri = Interfaces.MEDIA_PLAYER + '.' + SomePlayers.RHYTHMBOX mp2 = Playlists(dbus_interface_info={'dbus_uri': uri}) - print mp2.ActivePlaylist - print 'Active is valid playlist: ', bool(mp2.ActivePlaylist) + print(mp2.ActivePlaylist) + print('Active is valid playlist: ', bool(mp2.ActivePlaylist)) if mp2.ActivePlaylist: - print 'Active playlist name:', mp2.ActivePlaylist.Playlist.Name + print('Active playlist name:', mp2.ActivePlaylist.Playlist.Name) from mpris2.types import Playlist_Ordering - print hasattr('anystring', 'eusequenaotem') - print 'bla', mp2.GetPlaylists(0, 20, Playlist_Ordering.ALPHABETICAL, False) + print(hasattr('anystring', 'eusequenaotem')) + print('bla', mp2.GetPlaylists(0, 20, Playlist_Ordering.ALPHABETICAL, False)) diff --git a/autoradio/mpris2/some_players.py b/autoradio/mpris2/some_players.py index 72fcda9..48ac5e1 100644 --- a/autoradio/mpris2/some_players.py +++ b/autoradio/mpris2/some_players.py @@ -1,3 +1,4 @@ +from builtins import object class Some_Players(object): ''' Not defined in documentation diff --git a/autoradio/mpris2/time_in_us.py b/autoradio/mpris2/time_in_us.py index 5ac664a..c58b4d9 100644 --- a/autoradio/mpris2/time_in_us.py +++ b/autoradio/mpris2/time_in_us.py @@ -3,6 +3,7 @@ @author: hugosenari ''' +from __future__ import print_function class Time_In_Us(int): '''Time in microseconds.''' @@ -17,4 +18,4 @@ def time(self): return self._time if __name__ == "__main__": - print Time_In_Us(10) \ No newline at end of file + print(Time_In_Us(10)) \ No newline at end of file diff --git a/autoradio/mpris2/tracklist.py b/autoradio/mpris2/tracklist.py index fbd0f09..0ba6f94 100644 --- a/autoradio/mpris2/tracklist.py +++ b/autoradio/mpris2/tracklist.py @@ -3,12 +3,14 @@ http://www.mpris.org/2.1/spec/TrackList_Node.html """ +from __future__ import print_function +from __future__ import absolute_import from autoradio.pydbusdecorator.dbus_attr import DbusAttr from autoradio.pydbusdecorator.dbus_interface import DbusInterface from autoradio.pydbusdecorator.dbus_method import DbusMethod from autoradio.pydbusdecorator.dbus_signal import DbusSignal -from interfaces import Interfaces -from types import Metadata_Map +from .interfaces import Interfaces +from .types import Metadata_Map class TrackList(Interfaces): @@ -215,4 +217,4 @@ def CanEditTracks(self): from mpris2.utils import SomePlayers uri = Interfaces.MEDIA_PLAYER + '.' + SomePlayers.GMUSICBROWSER mp2 = TrackList(dbus_interface_info={'dbus_uri': uri}) #some one know any player that support it? - print mp2 + print(mp2) diff --git a/autoradio/mpris2/types.py b/autoradio/mpris2/types.py index e41ae7c..8e6820b 100644 --- a/autoradio/mpris2/types.py +++ b/autoradio/mpris2/types.py @@ -3,28 +3,30 @@ @author: hugosenari ''' +from __future__ import print_function +from __future__ import absolute_import -from loop_status import Loop_Status -from metada_map import Metadata_Map -from playback_rate import Playback_Rate -from playback_status import Playback_Status -from playlist import Playlist -from playlist import Maybe_Playlist -from playlist_id import Playlist_Id -from playlist_ordering import Playlist_Ordering -from time_in_us import Time_In_Us -from uri import Uri -from volume import Volume +from .loop_status import Loop_Status +from .metada_map import Metadata_Map +from .playback_rate import Playback_Rate +from .playback_status import Playback_Status +from .playlist import Playlist +from .playlist import Maybe_Playlist +from .playlist_id import Playlist_Id +from .playlist_ordering import Playlist_Ordering +from .time_in_us import Time_In_Us +from .uri import Uri +from .volume import Volume if __name__ == '__main__': - print Loop_Status - print Metadata_Map - print Playback_Rate - print Playback_Status - print Playlist - print Playlist_Id - print Playlist_Ordering - print Maybe_Playlist - print Time_In_Us - print Uri - print Volume \ No newline at end of file + print(Loop_Status) + print(Metadata_Map) + print(Playback_Rate) + print(Playback_Status) + print(Playlist) + print(Playlist_Id) + print(Playlist_Ordering) + print(Maybe_Playlist) + print(Time_In_Us) + print(Uri) + print(Volume) \ No newline at end of file diff --git a/autoradio/mpris2/uri.py b/autoradio/mpris2/uri.py index 2b3ab7a..07e9e9a 100644 --- a/autoradio/mpris2/uri.py +++ b/autoradio/mpris2/uri.py @@ -1,3 +1,4 @@ +from __future__ import print_function class Uri(str): '''A unique resource identifier.''' def __init__(self, uri, *args, **kw): @@ -9,4 +10,4 @@ def uri(self): return self._uri if __name__ == "__main__": - print Uri('http://www.com.br') \ No newline at end of file + print(Uri('http://www.com.br')) \ No newline at end of file diff --git a/autoradio/mpris2/utils.py b/autoradio/mpris2/utils.py index 68eb73c..9720a22 100644 --- a/autoradio/mpris2/utils.py +++ b/autoradio/mpris2/utils.py @@ -4,10 +4,12 @@ @author: hugosenari ''' +from __future__ import print_function +from __future__ import absolute_import import dbus, re -from some_players import Some_Players as SomePlayers -from interfaces import Interfaces +from .some_players import Some_Players as SomePlayers +from .interfaces import Interfaces def _match_players_uri(name, pattern='.+'): ''' @@ -48,7 +50,7 @@ def get_player_id_from_uri(uri): @param uri: string mpris2 player dbus uri @return: string mrpis2 id """ - print uri + print(uri) mateched = re.match(Interfaces.MEDIA_PLAYER + '\.(.+)', uri or '') return mateched.groups()[0]\ if mateched\ @@ -79,6 +81,6 @@ def unix_path_to_uri(): pass if __name__ == '__main__': - print get_players_uri() - print SomePlayers.get_dict() - print get_player_id_from_uri('org.mpris.MediaPlayer2.banshee') + print(get_players_uri()) + print(SomePlayers.get_dict()) + print(get_player_id_from_uri('org.mpris.MediaPlayer2.banshee')) diff --git a/autoradio/mpris2/volume.py b/autoradio/mpris2/volume.py index ef9985d..12cc15d 100644 --- a/autoradio/mpris2/volume.py +++ b/autoradio/mpris2/volume.py @@ -1,6 +1,10 @@ ''' Audio Volume ''' +from __future__ import division +from __future__ import print_function +from builtins import range +from past.utils import old_div class Volume(float): ''' Audio volume level @@ -13,7 +17,7 @@ class Volume(float): MIN = 0.0 MAX = 1.0 - RANGE = set([n/10.0 for n in range(11)]) + RANGE = set([old_div(n,10.0) for n in range(11)]) def __init__(self, volume=1.0, *args, **kw): super(Volume, self).__init__(volume, *args, **kw) @@ -25,4 +29,4 @@ def volume(self): return self._volume if __name__ == "__main__": - print Volume(1) \ No newline at end of file + print(Volume(1)) \ No newline at end of file diff --git a/autoradio/mprisweb.py b/autoradio/mprisweb.py index 0ace4b2..dfbcd9a 100644 --- a/autoradio/mprisweb.py +++ b/autoradio/mprisweb.py @@ -4,6 +4,8 @@ """ Show mediaplayer playlist on a simple web server. """ +from __future__ import print_function +from __future__ import absolute_import #try: # import sys,glob @@ -12,12 +14,15 @@ # sys.path.insert(0, compatCherryPyPath) #finally: -import autoradio_config +from builtins import str +from builtins import range +from builtins import object +from . import autoradio_config import cherrypy import os import datetime -import autompris -import autompris2 +from . import autompris +from . import autompris2 cpversion3=cherrypy.__version__.startswith("3") maxplele=100 # max number of elements in playlist @@ -54,7 +59,7 @@ ''' -class HomePage: +class HomePage(object): # def Main(self): # # Let's link to another method here. @@ -135,7 +140,7 @@ def index(self): htmlresponse+='
posizioneduratabrano
%i %s // %s %s // %s
' htmlresponse+='' - for pos in xrange(0,min(len,maxplele)): + for pos in range(0,min(len,maxplele)): htmlresponse+='' metadata=mp.get_metadata(pos) @@ -232,8 +237,8 @@ def start_http_server(iht=False,player="AutoPlayer",session=0): start_http_server(iht=True,player=autoradio_config.player,session=0) except: - print "Error" + print("Error") raise finally: - print "Terminated" + print("Terminated") diff --git a/autoradio/player/urls.py b/autoradio/player/urls.py index 3862c94..3b53e50 100644 --- a/autoradio/player/urls.py +++ b/autoradio/player/urls.py @@ -1,9 +1,10 @@ -from django.conf.urls import * -import views - -urlpatterns = [ - # Episode detail of one show - url(r'^nohtml5/(?P(.*))', views.playernohtml5cmd), - url(r'^(?P(.*))', views.playercmd), - -] +from __future__ import absolute_import +from django.conf.urls import * +from . import views + +urlpatterns = [ + # Episode detail of one show + url(r'^nohtml5/(?P(.*))', views.playernohtml5cmd), + url(r'^(?P(.*))', views.playercmd), + +] diff --git a/autoradio/playlists/admin.py b/autoradio/playlists/admin.py index 05ed369..bd8e7d3 100644 --- a/autoradio/playlists/admin.py +++ b/autoradio/playlists/admin.py @@ -1,4 +1,5 @@ -from models import Giorno, Configure, Playlist, Schedule, PeriodicSchedule +from __future__ import absolute_import +from .models import Giorno, Configure, Playlist, Schedule, PeriodicSchedule from django.contrib import admin diff --git a/autoradio/playlists/models.py b/autoradio/playlists/models.py index 5b62d29..1b20162 100644 --- a/autoradio/playlists/models.py +++ b/autoradio/playlists/models.py @@ -1,3 +1,4 @@ +from builtins import str from django.db import models from django.utils.translation import ugettext_lazy import datetime @@ -43,12 +44,12 @@ def delete_file(self, instance, sender, **kwargs): DeletingFileField=models.FileField def giorno_giorno(): - giorni=[] - for giorno in (calendar.day_name): - giorno=giorno.decode('utf-8') - giorni.append(( giorno, giorno)) - return giorni -# yield 'Tutti','Tutti' + giorni=[] + for giorno in (calendar.day_name): + #giorno=giorno.decode('utf-8') + giorni.append(( giorno, giorno)) + return giorni +# yield 'Tutti','Tutti' class Giorno(models.Model): @@ -59,9 +60,9 @@ def __unicode__(self): class Configure(models.Model): sezione = models.CharField(max_length=50,unique=True\ - ,default='playlist',editable=False) + ,default='playlist',editable=False) - active = models.BooleanField(ugettext_lazy("Activate Playlist"),default=True,\ + active = models.BooleanField(ugettext_lazy("Activate Playlist"),default=True,\ help_text=ugettext_lazy("activate/deactivate the intere playlist class")) emission_starttime = models.TimeField(ugettext_lazy('Programmed start time'),null=True,blank=True,\ help_text=ugettext_lazy("The start time from wich the playlist will be active")) @@ -108,7 +109,7 @@ class Schedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) playlist = models.ForeignKey(Playlist, verbose_name=\ - ugettext_lazy('refer to playlist:')) + ugettext_lazy('refer to playlist:')) shuffle = models.BooleanField(ugettext_lazy("Shuffle Playlist on start"),default=True,\ help_text=ugettext_lazy("Every time the playlist will be scheduled it's order will be randomly changed")) @@ -124,10 +125,10 @@ class Schedule(models.Model): # giorni = models.ManyToManyField(Giorno,verbose_name='Giorni programmati',null=True,blank=True) emission_done = models.DateTimeField(ugettext_lazy('Emission done')\ - ,null=True,editable=False ) + ,null=True,editable=False ) # def emitted(self): -# return self.emission_done != None +# return self.emission_done != None # emitted.short_description = 'Trasmesso' def was_scheduled_today(self): @@ -140,7 +141,7 @@ def file(self): file.short_description = ugettext_lazy('Linked Playlist') def __unicode__(self): - return unicode(self.playlist) + return str(self.playlist) class PeriodicSchedule(models.Model): @@ -148,7 +149,7 @@ class PeriodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) playlist = models.ForeignKey(Playlist,verbose_name=\ - ugettext_lazy('refer to playlist:')) + ugettext_lazy('refer to playlist:')) shuffle = models.BooleanField(ugettext_lazy("Shuffle Playlist on start"),default=True,\ help_text=ugettext_lazy("Every time the playlist will be scheduled it's order will be randomly changed")) @@ -163,10 +164,10 @@ class PeriodicSchedule(models.Model): giorni = models.ManyToManyField(Giorno,verbose_name=ugettext_lazy('Programmed days'),blank=True,\ help_text=ugettext_lazy("The playlist will be scheduled those weekdays")) emission_done = models.DateTimeField(ugettext_lazy('Emission done')\ - ,null=True,editable=False ) + ,null=True,editable=False ) # def emitted(self): -# return self.emission_done != None +# return self.emission_done != None # emitted.short_description = 'Trasmesso' def file(self): @@ -174,5 +175,5 @@ def file(self): file.short_description = ugettext_lazy('Linked Playlist') def __unicode__(self): - return unicode(self.playlist) + return str(self.playlist) diff --git a/autoradio/programs/admin.py b/autoradio/programs/admin.py index c724e8d..5e619e3 100644 --- a/autoradio/programs/admin.py +++ b/autoradio/programs/admin.py @@ -1,5 +1,7 @@ +from __future__ import absolute_import +from builtins import object from django.contrib import admin -from models import Giorno, Configure, ProgramType, Show, Schedule, \ +from .models import Giorno, Configure, ProgramType, Show, Schedule, \ PeriodicSchedule,AperiodicSchedule,Episode,Enclosure,ScheduleDone from autoradio.programs.models import ParentCategory, ChildCategory, MediaCategory from django import forms @@ -118,7 +120,7 @@ class MyEnclosureAdminForm(forms.ModelForm): """ Check file if it is a known media file. """ - class Meta: + class Meta(object): model = Enclosure fields = '__all__' diff --git a/autoradio/programs/migrations/0002_fixture.py b/autoradio/programs/migrations/0002_fixture.py index 01df7f7..35c26d1 100644 --- a/autoradio/programs/migrations/0002_fixture.py +++ b/autoradio/programs/migrations/0002_fixture.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals +from __future__ import print_function from django.db import models, migrations from django.core import serializers @@ -25,7 +26,7 @@ def load_fixture(apps, schema_editor): if fixture_filename[-5:] == ".json": fixture_file = os.path.join(fixture_dir, fixture_filename) - print "load fixture from file: ",fixture_file + print("load fixture from file: ",fixture_file) fixture = open(fixture_file, 'rb') objects = serializers.deserialize('json', fixture, ignorenonexistent=True) diff --git a/autoradio/programs/models.py b/autoradio/programs/models.py index b2e5437..5db4194 100644 --- a/autoradio/programs/models.py +++ b/autoradio/programs/models.py @@ -1,4 +1,7 @@ +from builtins import str +from builtins import range +from builtins import object from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy @@ -93,7 +96,7 @@ class MediaCategory(models.Model): name = models.CharField(max_length=50, choices=MEDIA_CATEGORY_CHOICES) slug = models.SlugField(blank=True, unique=False, help_text=ugettext_lazy('A slug is a URL-friendly nickname. For example, a slug for "Games & Hobbies" is "games-hobbies".')) - class Meta: + class Meta(object): ordering = ['slug'] verbose_name = 'category (Media RSS)' verbose_name_plural = 'categories (Media RSS)' @@ -125,7 +128,7 @@ class ParentCategory(models.Model): name = models.CharField(max_length=50, choices=PARENT_CHOICES, help_text=ugettext_lazy('After saving this parent category, please map it to one or more Child Categories below.')) slug = models.SlugField(blank=True, unique=False, help_text=ugettext_lazy('A slug is a URL-friendly nickname. For example, a slug for "Games & Hobbies" is "games-hobbies".')) - class Meta: + class Meta(object): ordering = ['slug'] verbose_name = 'category (iTunes parent)' verbose_name_plural = 'categories (iTunes parent)' @@ -227,7 +230,7 @@ class ChildCategory(models.Model): name = models.CharField(max_length=50, blank=True, choices=CHILD_CHOICES, help_text=ugettext_lazy('Please choose a child category that corresponds to its respective parent category (e.g., "Design" is a child category of "Arts").
If no such child category exists for a parent category (e.g., Comedy, Kids & Family, Music, News & Politics, or TV & Film), simply leave this blank and save.')) slug = models.SlugField(blank=True, unique=False, help_text=ugettext_lazy('A slug is a URL-friendly nickname. For exmaple, a slug for "Fashion & Beauty" is "fashion-beauty".')) - class Meta: + class Meta(object): ordering = ['parent', 'slug'] verbose_name = 'category (iTunes child)' verbose_name_plural = 'categories (iTunes child)' @@ -240,12 +243,12 @@ def __unicode__(self): def giorno_giorno(): - giorni=[] - for giorno in (calendar.day_name): - giorno=giorno.decode('utf-8') - giorni.append(( giorno, giorno)) - return giorni -# yield 'Tutti','Tutti' + giorni=[] + for giorno in (calendar.day_name): + #giorno=giorno.decode('utf-8') + giorni.append(( giorno, giorno)) + return giorni +# yield 'Tutti','Tutti' class Giorno(models.Model): @@ -257,26 +260,26 @@ def __unicode__(self): class Configure(models.Model): - sezione = models.CharField(max_length=50,unique=True\ - ,default='show',editable=False) - active = models.BooleanField(ugettext_lazy("Active show"),default=True,\ + sezione = models.CharField(max_length=50,unique=True\ + ,default='show',editable=False) + active = models.BooleanField(ugettext_lazy("Active show"),default=True,\ help_text=ugettext_lazy("activate/deactivate the intere program class")) - emission_starttime = models.TimeField(ugettext_lazy('Programmed start time'),null=True,blank=True,\ + emission_starttime = models.TimeField(ugettext_lazy('Programmed start time'),null=True,blank=True,\ help_text=ugettext_lazy("The start time from wich the programs will be active")) - emission_endtime = models.TimeField(ugettext_lazy('Programmed end time'),null=True,blank=True,\ + emission_endtime = models.TimeField(ugettext_lazy('Programmed end time'),null=True,blank=True,\ help_text=ugettext_lazy("The end time the programs will be active")) - radiostation = models.CharField(max_length=50,unique=True, default='Radio',editable=True,\ + radiostation = models.CharField(max_length=50,unique=True, default='Radio',editable=True,\ help_text=ugettext_lazy("The station name for the print of programs book")) - channel = models.CharField(max_length=80,unique=True, default='103', editable=True,\ + channel = models.CharField(max_length=80,unique=True, default='103', editable=True,\ help_text=ugettext_lazy("The station channel for the print of programs book")) - mezzo = models.CharField(max_length=50,unique=True, default='analogico terrestre', editable=True,\ + mezzo = models.CharField(max_length=50,unique=True, default='analogico terrestre', editable=True,\ help_text=ugettext_lazy("The station kind of emission for the print of programs book")) - type = models.CharField(max_length=50,unique=True, default='radiofonica', editable=True,\ + type = models.CharField(max_length=50,unique=True, default='radiofonica', editable=True,\ help_text=ugettext_lazy("The station type for the print of programs book")) - def __unicode__(self): + def __unicode__(self): if self.emission_starttime is None: emission_starttime = "-" @@ -289,8 +292,8 @@ def __unicode__(self): emission_endtime = self.emission_endtime.isoformat() return self.sezione+" "+self.active.__str__()+" "\ - +emission_starttime+" "\ - +emission_endtime + +emission_starttime+" "\ + +emission_endtime class ProgramType(models.Model): @@ -304,8 +307,8 @@ def __unicode__(self): return self.type+"/"+self.subtype def Production(): - for production in (ugettext_lazy("autoproduction"),ugettext_lazy("eteroproduction")): - yield production, production + for production in (ugettext_lazy("autoproduction"),ugettext_lazy("eteroproduction")): + yield production, production class Show(models.Model): @@ -315,24 +318,24 @@ class Show(models.Model): active = models.BooleanField(ugettext_lazy("Active"),default=True,help_text=ugettext_lazy("Activate the show for emission")) slug = models.SlugField(unique=True, help_text=ugettext_lazy('Auto-generated from Title.')) length = models.FloatField(ugettext_lazy("Time length (seconds)"),default=None,null=True,blank=True, help_text=ugettext_lazy('Time lenght how you want to see it in the palimpsest')) - type = models.ForeignKey(ProgramType, verbose_name= ugettext_lazy('Program Type'), help_text=ugettext_lazy('The categorization that follow the italian law (you have to use it to produce the programs book')) + type = models.ForeignKey(ProgramType, verbose_name= ugettext_lazy('Program Type'), help_text=ugettext_lazy('The categorization that follow the italian law (you have to use it to produce the programs book')) production = models.CharField(ugettext_lazy("Production"),max_length=30,choices=Production(),default=None,null=True,blank=True, help_text=ugettext_lazy('The type of production')) COPYRIGHT_CHOICES = ( - ('Public domain', 'Public domain'), - ('Creative Commons: Attribution (by)', 'Creative Commons: Attribution (by)'), - ('Creative Commons: Attribution-Share Alike (by-sa)', 'Creative Commons: Attribution-Share Alike (by-sa)'), - ('Creative Commons: Attribution-No Derivatives (by-nd)', 'Creative Commons: Attribution-No Derivatives (by-nd)'), - ('Creative Commons: Attribution-Non-Commercial (by-nc)', 'Creative Commons: Attribution-Non-Commercial (by-nc)'), - ('Creative Commons: Attribution-Non-Commercial-Share Alike (by-nc-sa)', 'Creative Commons: Attribution-Non-Commercial-Share Alike (by-nc-sa)'), - ('Creative Commons: Attribution-Non-Commercial-No Dreivatives (by-nc-nd)', 'Creative Commons: Attribution-Non-Commercial-No Dreivatives (by-nc-nd)'), - ('All rights reserved', 'All rights reserved'), - ) + ('Public domain', 'Public domain'), + ('Creative Commons: Attribution (by)', 'Creative Commons: Attribution (by)'), + ('Creative Commons: Attribution-Share Alike (by-sa)', 'Creative Commons: Attribution-Share Alike (by-sa)'), + ('Creative Commons: Attribution-No Derivatives (by-nd)', 'Creative Commons: Attribution-No Derivatives (by-nd)'), + ('Creative Commons: Attribution-Non-Commercial (by-nc)', 'Creative Commons: Attribution-Non-Commercial (by-nc)'), + ('Creative Commons: Attribution-Non-Commercial-Share Alike (by-nc-sa)', 'Creative Commons: Attribution-Non-Commercial-Share Alike (by-nc-sa)'), + ('Creative Commons: Attribution-Non-Commercial-No Dreivatives (by-nc-nd)', 'Creative Commons: Attribution-Non-Commercial-No Dreivatives (by-nc-nd)'), + ('All rights reserved', 'All rights reserved'), + ) EXPLICIT_CHOICES = ( - ('Yes', 'Yes'), - ('No', 'No'), - ('Clean', 'Clean'), - ) + ('Yes', 'Yes'), + ('No', 'No'), + ('Clean', 'Clean'), + ) # RSS 2.0 organization = models.CharField(max_length=255, help_text=ugettext_lazy('Name of the organization, company or Web site producing the podcast.')) link = models.URLField(help_text=ugettext_lazy('URL of either the main website or the podcast section of the main website.')) @@ -358,7 +361,7 @@ class Show(models.Model): itunes = models.URLField('iTunes Store URL', help_text=ugettext_lazy('Fill this out after saving this show and at least one episode. URL should look like "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=000000000". See documentation for more.'), blank=True) - class Meta: + class Meta(object): ordering = ['organization', 'slug'] def __unicode__(self): @@ -601,7 +604,7 @@ class Episode(models.Model): # Behind the scenes objects = EpisodeManager() - class Meta: + class Meta(object): ordering = ['-date', 'slug'] def __unicode__(self): @@ -704,7 +707,7 @@ class Enclosure(models.Model): height = models.PositiveIntegerField(blank=True, null=True, help_text=ugettext_lazy("Height of the browser window in
which the URL should be opened.
YouTube's default is 344.")) episode = models.ForeignKey(Episode, help_text=ugettext_lazy('Include any number of media files; for example, perhaps include an iPhone-optimized, AppleTV-optimized and Flash Video set of video files. Note that the iTunes feed only accepts the first file. More uploading is available after clicking "Save and continue editing."')) - class Meta: + class Meta(object): ordering = ['mime', 'file'] @@ -727,44 +730,44 @@ class Schedule(models.Model): # program = models.ForeignKey(Program, edit_inline=models.TABULAR,\ # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) - episode = models.ForeignKey(Episode, \ - verbose_name=ugettext_lazy('Linked episode:')) + episode = models.ForeignKey(Episode, \ + verbose_name=ugettext_lazy('Linked episode:')) - emission_date = models.DateTimeField(ugettext_lazy('programmed date'),\ + emission_date = models.DateTimeField(ugettext_lazy('programmed date'),\ help_text=ugettext_lazy("This is the date and time when the program will be on air")) - # def emitted(self): - # return self.emission_done != None - # emitted.short_description = 'Trasmesso' + # def emitted(self): + # return self.emission_done != None + # emitted.short_description = 'Trasmesso' - def was_scheduled_today(self): - return self.emission_date.date() == datetime.date.today() + def was_scheduled_today(self): + return self.emission_date.date() == datetime.date.today() - was_scheduled_today.short_description = ugettext_lazy('Scheduled for today?') + was_scheduled_today.short_description = ugettext_lazy('Scheduled for today?') - def refepisode(self): - return self.episode.title - refepisode.short_description = ugettext_lazy('Linked episode:') + def refepisode(self): + return self.episode.title + refepisode.short_description = ugettext_lazy('Linked episode:') - def __unicode__(self): - return unicode(self.episode.title) + def __unicode__(self): + return str(self.episode.title) class ScheduleDone(models.Model): - schedule = models.ForeignKey(Schedule, \ - verbose_name=ugettext_lazy('Linked schedule:')) + schedule = models.ForeignKey(Schedule, \ + verbose_name=ugettext_lazy('Linked schedule:')) - enclosure = models.ForeignKey(Enclosure, \ - verbose_name=ugettext_lazy('Linked enclosure:')) + enclosure = models.ForeignKey(Enclosure, \ + verbose_name=ugettext_lazy('Linked enclosure:')) - emission_done = models.DateTimeField(ugettext_lazy('emission done')\ - ,null=True,editable=False ) + emission_done = models.DateTimeField(ugettext_lazy('emission done')\ + ,null=True,editable=False ) - def __unicode__(self): - return unicode(self.emission_done) + def __unicode__(self): + return str(self.emission_done) @@ -774,7 +777,7 @@ class PeriodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) show = models.ForeignKey(Show,verbose_name=\ - ugettext_lazy('refer to show:')) + ugettext_lazy('refer to show:')) start_date = models.DateField(ugettext_lazy('Programmed start date'),null=True,blank=True,\ help_text=ugettext_lazy("The program will be in palimpsest starting from this date")) @@ -787,7 +790,7 @@ class PeriodicSchedule(models.Model): def __unicode__(self): - return unicode(self.show) + return str(self.show) class AperiodicSchedule(models.Model): @@ -795,7 +798,7 @@ class AperiodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) show = models.ForeignKey(Show, verbose_name=\ - ugettext_lazy('refer to Show:')) + ugettext_lazy('refer to Show:')) emission_date = models.DateTimeField(ugettext_lazy('Programmed date'),\ help_text=ugettext_lazy("This is the date and time when the program is planned in palimsest")) @@ -806,5 +809,5 @@ def was_scheduled_today(self): was_scheduled_today.short_description = ugettext_lazy('Programmed for today?') def __unicode__(self): - return unicode(self.show) + return str(self.show) diff --git a/autoradio/programs/urls.py b/autoradio/programs/urls.py index f2b929b..392b9ea 100644 --- a/autoradio/programs/urls.py +++ b/autoradio/programs/urls.py @@ -1,8 +1,9 @@ +from __future__ import absolute_import from django.conf.urls import * #from django.contrib import admin #from models import Program, Schedule -import views +from . import views urlpatterns = [ url(r'^$', views.index), diff --git a/autoradio/programs/urls_podcast.py b/autoradio/programs/urls_podcast.py index 4849c7f..32d965a 100644 --- a/autoradio/programs/urls_podcast.py +++ b/autoradio/programs/urls_podcast.py @@ -1,9 +1,10 @@ +from __future__ import absolute_import from django.conf.urls import * #from django.contrib import admin #from models import Program, Schedule -from views import show_list, episode_list, show_list_feed, show_list_atom, show_list_media, episode_sitemap, episode_detail +from .views import show_list, episode_list, show_list_feed, show_list_atom, show_list_media, episode_sitemap, episode_detail urlpatterns = [ diff --git a/autoradio/programs/views.py b/autoradio/programs/views.py index aec82c1..e809b21 100644 --- a/autoradio/programs/views.py +++ b/autoradio/programs/views.py @@ -1,7 +1,12 @@ +from __future__ import absolute_import # Create your views here. +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import range from django.shortcuts import render_to_response -from models import Schedule +from .models import Schedule from django.http import HttpResponse,HttpResponseRedirect from datetime import date,datetime,timedelta,time import autoradio.autoradio_config @@ -11,7 +16,7 @@ import os #from django.forms.extras.widgets import SelectDateWidget -from widgets import MySelectDateWidget +from .widgets import MySelectDateWidget from django.utils.translation import ugettext_lazy #---------------------------------------------------- @@ -35,11 +40,11 @@ def index(request): def stato(request): - import urllib2 + import urllib.request, urllib.error, urllib.parse xmmsweb="" try: - url=urllib2.urlopen("http://"+autoradio.autoradio_config.XMMSHOST+":8888/") + url=urllib.request.urlopen("http://"+autoradio.autoradio_config.XMMSHOST+":8888/") for line in url: xmmsweb=xmmsweb+line except: @@ -78,7 +83,7 @@ def dbusstato(request): htmlresponse+='
positionlenght // remainmedia
' htmlresponse+='' - for pos in xrange(0,min(len,maxplele)): + for pos in range(0,min(len,maxplele)): htmlresponse+='' metadata=mp.get_metadata(pos) @@ -201,10 +206,10 @@ def myPages(canvas, doc): PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() - MezzoTrasmissione=Paragraph("Mezzo di diffusione: "+unicode(mezzo)+ - " // Tipo di trasmissione: "+unicode(trasmissione), styles["Normal"]) - EmittenteCanale=Paragraph("Denominazione dell'emittente: "+unicode(emittente)+ - " // Denominazione del canale: "+unicode(canale), styles["Normal"]) + MezzoTrasmissione=Paragraph("Mezzo di diffusione: "+str(mezzo)+ + " // Tipo di trasmissione: "+str(trasmissione), styles["Normal"]) + EmittenteCanale=Paragraph("Denominazione dell'emittente: "+str(emittente)+ + " // Denominazione del canale: "+str(canale), styles["Normal"]) Space=Spacer(inch, 0.25 * inch) # First the top row, with all the text centered and in Times-Bold, @@ -254,7 +259,7 @@ def myPages(canvas, doc): Elements = [MezzoTrasmissione,EmittenteCanale,Space,Tabella] # Create the PDF object, using the response object as its "file." - p = SimpleDocTemplate(response,title="Libro programmi: "+unicode(emittente),author=author) + p = SimpleDocTemplate(response,title="Libro programmi: "+str(emittente),author=author) p.build(Elements, onFirstPage=myPages, onLaterPages=myPages) diff --git a/autoradio/programs/widgets.py b/autoradio/programs/widgets.py index 6429c50..7eed230 100644 --- a/autoradio/programs/widgets.py +++ b/autoradio/programs/widgets.py @@ -3,6 +3,8 @@ from http://djangosnippets.org/snippets/1834/ """ +from builtins import range +from past.builtins import basestring import datetime import re @@ -34,7 +36,7 @@ def __init__(self, attrs=None, years=None, required=True): self.years = years else: this_year = datetime.date.today().year-9 - self.years = range(this_year, this_year+10) + self.years = list(range(this_year, this_year+10)) def render(self, name, value, attrs=None): @@ -63,7 +65,7 @@ def render(self, name, value, attrs=None): select_html = s.render(self.day_field % name, day_val, local_attrs) output.append(select_html) - month_choices = MONTHS.items() + month_choices = list(MONTHS.items()) if not (self.required and value): month_choices.append(self.none_value) month_choices.sort() diff --git a/autoradio/pydbusdecorator/__init__.py b/autoradio/pydbusdecorator/__init__.py index bb31c86..02dcbec 100644 --- a/autoradio/pydbusdecorator/__init__.py +++ b/autoradio/pydbusdecorator/__init__.py @@ -3,12 +3,13 @@ @author: hugosenari ''' -from dbus_decorator import DbusDecorator -from dbus_interface import DbusInterface -from dbus_attr import DbusAttr -from dbus_method import DbusMethod -from dbus_signal import DbusSignal -from undefined_param import UndefinedParam +from __future__ import absolute_import +from .dbus_decorator import DbusDecorator +from .dbus_interface import DbusInterface +from .dbus_attr import DbusAttr +from .dbus_method import DbusMethod +from .dbus_signal import DbusSignal +from .undefined_param import UndefinedParam if __name__ == '__main__': pass \ No newline at end of file diff --git a/autoradio/pydbusdecorator/dbus_attr.py b/autoradio/pydbusdecorator/dbus_attr.py index f44e7c9..2ad785a 100644 --- a/autoradio/pydbusdecorator/dbus_attr.py +++ b/autoradio/pydbusdecorator/dbus_attr.py @@ -3,9 +3,10 @@ @author: hugosenari ''' -from dbus_decorator import DbusDecorator -from undefined_param import UNDEFINED_PARAM -from dbus_interface import DbusInterface +from __future__ import absolute_import +from .dbus_decorator import DbusDecorator +from .undefined_param import UNDEFINED_PARAM +from .dbus_interface import DbusInterface class DbusAttr(DbusDecorator): @@ -81,7 +82,7 @@ def __set__(self, obj, value): self.attr = value def __delete__(self, obj): - raise AttributeError, "can't delete attribute" + raise AttributeError("can't delete attribute") @property def attr(self): diff --git a/autoradio/pydbusdecorator/dbus_decorator.py b/autoradio/pydbusdecorator/dbus_decorator.py index 1d4f77a..ed5ace3 100644 --- a/autoradio/pydbusdecorator/dbus_decorator.py +++ b/autoradio/pydbusdecorator/dbus_decorator.py @@ -4,6 +4,7 @@ @author: hugosenari ''' +from builtins import object import dbus class DbusDecorator(object): diff --git a/autoradio/pydbusdecorator/dbus_interface.py b/autoradio/pydbusdecorator/dbus_interface.py index de09228..82c0106 100644 --- a/autoradio/pydbusdecorator/dbus_interface.py +++ b/autoradio/pydbusdecorator/dbus_interface.py @@ -3,9 +3,11 @@ @author: hugosenari ''' +from __future__ import absolute_import -from dbus_decorator import DbusDecorator -from undefined_param import UNDEFINED_PARAM +from builtins import object +from .dbus_decorator import DbusDecorator +from .undefined_param import UNDEFINED_PARAM from functools import wraps diff --git a/autoradio/pydbusdecorator/dbus_method.py b/autoradio/pydbusdecorator/dbus_method.py index c5e394d..0ef8315 100644 --- a/autoradio/pydbusdecorator/dbus_method.py +++ b/autoradio/pydbusdecorator/dbus_method.py @@ -3,9 +3,11 @@ @author: hugosenari ''' +from __future__ import absolute_import -from dbus_decorator import DbusDecorator -from dbus_interface import DbusInterface +from builtins import range +from .dbus_decorator import DbusDecorator +from .dbus_interface import DbusInterface from functools import wraps @@ -119,8 +121,8 @@ def convert_kw_to_dbus_kw(self, **kw): return kw_to_dbus(**kw) if hasattr(self.kw_to_dbus, 'keys'): - to_dbus_keys = kw_to_dbus.keys() - for key in kw.keys(): + to_dbus_keys = list(kw_to_dbus.keys()) + for key in list(kw.keys()): if key in to_dbus_keys: kw[key] = kw_to_dbus[key](kw[key]) return kw diff --git a/autoradio/pydbusdecorator/dbus_signal.py b/autoradio/pydbusdecorator/dbus_signal.py index 29a66b8..d2f619d 100644 --- a/autoradio/pydbusdecorator/dbus_signal.py +++ b/autoradio/pydbusdecorator/dbus_signal.py @@ -3,9 +3,10 @@ @author: hugosenari ''' +from __future__ import absolute_import -from dbus_decorator import DbusDecorator -from dbus_interface import DbusInterface +from .dbus_decorator import DbusDecorator +from .dbus_interface import DbusInterface from functools import wraps diff --git a/autoradio/pydbusdecorator/undefined_param.py b/autoradio/pydbusdecorator/undefined_param.py index f024c32..4598b51 100644 --- a/autoradio/pydbusdecorator/undefined_param.py +++ b/autoradio/pydbusdecorator/undefined_param.py @@ -3,8 +3,10 @@ @author: hugosenari ''' +from __future__ import print_function -class Undefined(): +from builtins import object +class Undefined(object): '''Undefined''' def __nonzero__(self=None): return False @@ -22,4 +24,4 @@ def __cmp__(self, other): UNDEFINED_PARAM = UndefinedParam() if __name__ == "__main__": - print "True" if bool(UNDEFINED_PARAM) else "False" \ No newline at end of file + print("True" if bool(UNDEFINED_PARAM) else "False") \ No newline at end of file diff --git a/autoradio/settings.py b/autoradio/settings.py index 5faeb2f..b963459 100644 --- a/autoradio/settings.py +++ b/autoradio/settings.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Django settings for autoradio project. import os @@ -100,7 +101,7 @@ section_string = ', '.join(section_list) if error == False: error = 'Missing value or section.' - print section_string, ' = ', error + print(section_string, ' = ', error) raise error # section django @@ -282,5 +283,5 @@ import django_extensions INSTALLED_APPS += 'django_extensions', except ImportError: - print "django_extensions is not installed; I do not use it" + print("django_extensions is not installed; I do not use it") pass diff --git a/autoradio/spots/admin.py b/autoradio/spots/admin.py index 3ddeb7c..fbc4390 100644 --- a/autoradio/spots/admin.py +++ b/autoradio/spots/admin.py @@ -1,4 +1,6 @@ -from models import Giorno, Configure, Fascia, Spot +from __future__ import absolute_import +from builtins import object +from .models import Giorno, Configure, Fascia, Spot from django.contrib import admin from django import forms from django.utils.translation import ugettext_lazy @@ -13,7 +15,7 @@ class MySpotAdminForm(forms.ModelForm): """ Check file if it is a known media file. """ - class Meta: + class Meta(object): model = Spot fields = '__all__' diff --git a/autoradio/spots/models.py b/autoradio/spots/models.py index 72cce05..eaac75a 100644 --- a/autoradio/spots/models.py +++ b/autoradio/spots/models.py @@ -1,3 +1,4 @@ +from builtins import object from django.db import models from django.utils.translation import ugettext_lazy @@ -43,12 +44,12 @@ def delete_file(self, instance, sender, **kwargs): DeletingFileField=models.FileField def giorno_giorno(): - giorni=[] - for giorno in (calendar.day_name): - giorno=giorno.decode('utf-8') - giorni.append(( giorno, giorno)) - return giorni -# yield 'Tutti','Tutti' + giorni=[] + for giorno in (calendar.day_name): + #giorno=giorno.decode('utf-8') + giorni.append(( giorno, giorno)) + return giorni +# yield 'Tutti','Tutti' class Giorno(models.Model): @@ -58,47 +59,47 @@ class Giorno(models.Model): def __unicode__(self): return self.name - class Admin: - search_fields = ['name'] + class Admin(object): + search_fields = ['name'] ## class Giorno(models.Model): -## #DAY_CHOICES = ( -## # ('1', 'Lunedi'), -## # ('2', 'Martedi'), -## # ('3', 'Mercoledi'), -## # ('4', 'Giovedi'), -## # ('5', 'Venerdi'), -## # ('6', 'Sabato'), -## # ('7', 'Domenica'), -## # ) - - -## DAY_CHOICES = ( -## ( 'Lunedi','Lunedi'), -## ( 'Martedi','Martedi'), -## ( 'Mercoledi','Mercoledi'), -## ( 'Giovedi','Giovedi'), -## ( 'Venerdi','Venerdi'), -## ( 'Sabato','Sabato'), -## ( 'Domenica','Domenica'), -## ) - +## #DAY_CHOICES = ( +## # ('1', 'Lunedi'), +## # ('2', 'Martedi'), +## # ('3', 'Mercoledi'), +## # ('4', 'Giovedi'), +## # ('5', 'Venerdi'), +## # ('6', 'Sabato'), +## # ('7', 'Domenica'), +## # ) + + +## DAY_CHOICES = ( +## ( 'Lunedi','Lunedi'), +## ( 'Martedi','Martedi'), +## ( 'Mercoledi','Mercoledi'), +## ( 'Giovedi','Giovedi'), +## ( 'Venerdi','Venerdi'), +## ( 'Sabato','Sabato'), +## ( 'Domenica','Domenica'), +## ) + ## name = models.CharField(max_length=20,choices=DAY_CHOICES,unique=True) -## #name = models.CharField(max_length=20) - +## #name = models.CharField(max_length=20) + ## def __unicode__(self): ## return self.name ## class Admin: -## search_fields = ['name'] +## search_fields = ['name'] class Configure(models.Model): sezione = models.CharField(max_length=50,unique=True,default='spot',editable=False) - active = models.BooleanField(ugettext_lazy("Activate Spot"),default=True,\ + active = models.BooleanField(ugettext_lazy("Activate Spot"),default=True,\ help_text=ugettext_lazy("activate/deactivate the intere spot class")) emission_starttime = models.TimeField(ugettext_lazy('Programmed start time'),null=True,blank=True,\ help_text=ugettext_lazy("The start time from wich the spot will be active")) @@ -119,99 +120,99 @@ def __unicode__(self): return self.sezione+" "+self.active.__str__()+" "+start+" "+end - class Admin: - list_display = ('sezione','active','emission_starttime','emission_endtime') + class Admin(object): + list_display = ('sezione','active','emission_starttime','emission_endtime') class Fascia(models.Model): - name = models.CharField(max_length=50,unique=True,\ + name = models.CharField(max_length=50,unique=True,\ help_text=ugettext_lazy("The name of commercial break")) - emission_time = models.TimeField(unique=True,\ + emission_time = models.TimeField(unique=True,\ help_text=ugettext_lazy("This is the date and time when the commercial break will be on air")) - active = models.BooleanField(ugettext_lazy("Active"),default=True,\ + active = models.BooleanField(ugettext_lazy("Active"),default=True,\ help_text=ugettext_lazy("Activate the commercial break for emission")) - emission_done = models.DateTimeField(ugettext_lazy('Emission done'),null=True,editable=False ) - - - def spots(self): -# print self.spot_set.filter(prologo__exact=True).order_by('priorita').append(\ -# self.spot_set.exclude(prologo__exact=True).exclude(epilogo__exact=True).order_by('priorita')).append(\ -# self.spot_set.filter(epilogo__exact=True).order_by('priorita')) - - return self.spot_set.all().order_by('prologo').order_by('priorita').order_by('epilogo') - -# filter(prologo__exact=True) -# return di -# di={} -# di["bb"]="ciccia" -# di["cc"]="cacca" -# return di -# sps="" -# for sp in di.iterkeys(): -# sps=sps+di[sp] -# return sps -# .append(\ -# self.spot_set.exclude(prologo__exact=True).exclude(epilogo__exact=True).order_by('priorita')).append(\ -# self.spot_set.filter(epilogo__exact=True).order_by('priorita')) - - def __unicode__(self): + emission_done = models.DateTimeField(ugettext_lazy('Emission done'),null=True,editable=False ) + + + def spots(self): +# print self.spot_set.filter(prologo__exact=True).order_by('priorita').append(\ +# self.spot_set.exclude(prologo__exact=True).exclude(epilogo__exact=True).order_by('priorita')).append(\ +# self.spot_set.filter(epilogo__exact=True).order_by('priorita')) + + return self.spot_set.all().order_by('prologo').order_by('priorita').order_by('epilogo') + + # filter(prologo__exact=True) + # return di + # di={} + # di["bb"]="ciccia" + # di["cc"]="cacca" + # return di + # sps="" + # for sp in di.iterkeys(): + # sps=sps+di[sp] + # return sps + # .append(\ + # self.spot_set.exclude(prologo__exact=True).exclude(epilogo__exact=True).order_by('priorita')).append(\ + # self.spot_set.filter(epilogo__exact=True).order_by('priorita')) + + def __unicode__(self): return self.name+" "+self.emission_time.isoformat() - class Admin: - search_fields = ['name','emission_time','emission_done','active','spots'] - list_display = ('name','emission_time','emission_done','active','spots') + class Admin(object): + search_fields = ['name','emission_time','emission_done','active','spots'] + list_display = ('name','emission_time','emission_done','active','spots') class Spot(models.Model): - - spot = models.CharField(ugettext_lazy("Spot Name"),max_length=80,unique=True,\ + + spot = models.CharField(ugettext_lazy("Spot Name"),max_length=80,unique=True,\ help_text=ugettext_lazy("The name of the spot")) - file = DeletingFileField(ugettext_lazy('File'),upload_to='spots',max_length=255,\ + file = DeletingFileField(ugettext_lazy('File'),upload_to='spots',max_length=255,\ help_text=ugettext_lazy("The spot file to upload")) - rec_date = models.DateTimeField(ugettext_lazy('Record date'),\ + rec_date = models.DateTimeField(ugettext_lazy('Record date'),\ help_text=ugettext_lazy("When the spot was done (for reference only)")) - active = models.BooleanField(ugettext_lazy("Active"),default=True,\ + active = models.BooleanField(ugettext_lazy("Active"),default=True,\ help_text=ugettext_lazy("Activate the spot for emission")) - start_date = models.DateTimeField(ugettext_lazy('Programmed starting date'),null=True,blank=True,\ + start_date = models.DateTimeField(ugettext_lazy('Programmed starting date'),null=True,blank=True,\ help_text=ugettext_lazy("The spot will be scheduled starting from this date")) - end_date = models.DateTimeField(ugettext_lazy('Programmed ending date'),null=True,blank=True,\ + end_date = models.DateTimeField(ugettext_lazy('Programmed ending date'),null=True,blank=True,\ help_text=ugettext_lazy("The spot will be scheduled ending this date")) - # giorni = models.PositiveIntegerField( choices=DAY_CHOICES) -# giorni = models.ForeignKey(Giorno,verbose_name='Giorni programmati',editable=False) - giorni = models.ManyToManyField(Giorno,verbose_name=ugettext_lazy('Programmed days'),blank=True,\ + # giorni = models.PositiveIntegerField( choices=DAY_CHOICES) +# giorni = models.ForeignKey(Giorno,verbose_name='Giorni programmati',editable=False) + giorni = models.ManyToManyField(Giorno,verbose_name=ugettext_lazy('Programmed days'),blank=True,\ help_text=ugettext_lazy("The spot will be scheduled those weekdays")) - fasce = models.ManyToManyField(Fascia,blank=True,\ + fasce = models.ManyToManyField(Fascia,blank=True,\ help_text=ugettext_lazy("The spot will be included in those commercial break")) - priorita = models.IntegerField(ugettext_lazy("Priority"),default=50,\ + priorita = models.IntegerField(ugettext_lazy("Priority"),default=50,\ help_text=ugettext_lazy("The order of the spots in commercial breaks will be ordered by this numer")) - prologo = models.BooleanField(ugettext_lazy("Prologue"),default=False,\ + prologo = models.BooleanField(ugettext_lazy("Prologue"),default=False,\ help_text=ugettext_lazy("This spot will be the firt in commercial breaks to introduce the others")) - epilogo = models.BooleanField(ugettext_lazy("Epilogue"),default=False,\ + epilogo = models.BooleanField(ugettext_lazy("Epilogue"),default=False,\ help_text=ugettext_lazy("This spot will be the last in commercial breaks to leave-taking")) - - def was_recorded_today(self): - return self.rec_date.date() == datetime.date.today() + + def was_recorded_today(self): + return self.rec_date.date() == datetime.date.today() - was_recorded_today.short_description = ugettext_lazy('Recorded today?') - - def __unicode__(self): - return self.spot - - class Admin: - fields = ( - (None, {'fields': ('spot','file','rec_date')}), - ('Emission information', {'fields': \ - ('start_date','end_date','giorni','fasce','priorita','prologo','epilogo')}), - ) - # list_display = ('spot', 'rec_date', 'was_recorded_today','giorni','fasce','priorita') - list_filter = ['start_date','end_date','fasce','giorni',"prologo","epilogo"] - date_hierarchy = 'rec_date' - search_fields = ['spot','giorni','fascie'] - list_display = ('spot','file','rec_date','priorita') - - - #class Meta: - # unique_together = ("prologo", "epilogo","fasce") - + was_recorded_today.short_description = ugettext_lazy('Recorded today?') + + def __unicode__(self): + return self.spot + + class Admin(object): + fields = ( + (None, {'fields': ('spot','file','rec_date')}), + ('Emission information', {'fields': \ + ('start_date','end_date','giorni','fasce','priorita','prologo','epilogo')}), + ) + # list_display = ('spot', 'rec_date', 'was_recorded_today','giorni','fasce','priorita') + list_filter = ['start_date','end_date','fasce','giorni',"prologo","epilogo"] + date_hierarchy = 'rec_date' + search_fields = ['spot','giorni','fascie'] + list_display = ('spot','file','rec_date','priorita') + + + #class Meta: + # unique_together = ("prologo", "epilogo","fasce") + diff --git a/autoradio/urls.py b/autoradio/urls.py index 15a0be6..2d4b60d 100644 --- a/autoradio/urls.py +++ b/autoradio/urls.py @@ -1,5 +1,6 @@ +from __future__ import absolute_import from django.conf.urls import * -import settings +from . import settings from django.conf.urls.static import static diff --git a/autoradio/xmmsweb.py b/autoradio/xmmsweb.py index 3ef2372..d715823 100755 --- a/autoradio/xmmsweb.py +++ b/autoradio/xmmsweb.py @@ -5,6 +5,9 @@ Show xmms playlist on a simple web server. """ +from builtins import str +from builtins import range +from builtins import object session=0 # sessione di xmms maxplele=100 # massimo numero di elementi della playlist iht=False # emetti header e tail @@ -54,7 +57,7 @@ ''' -class HomePage: +class HomePage(object): # def Main(self): # # Let's link to another method here. @@ -106,7 +109,7 @@ def index(self): htmlresponse+='
positionlenght // remainmedia
' htmlresponse+='' - for pos in xrange(0,min(len,maxplele)): + for pos in range(0,min(len,maxplele)): htmlresponse+='' file=xmms.control.get_playlist_file(pos, session) title=xmms.control.get_playlist_title(pos, session) diff --git a/setup.py b/setup.py index 9be2a46..4219750 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,4 @@ +from __future__ import print_function from distutils.core import setup import os @@ -47,42 +48,42 @@ def run(self): for root, dirs, files in os.walk(os.getcwd(), topdown=False): for name in files: if name.endswith('.pyc') and os.path.isfile(os.path.join(root, name)): - print 'removing: %s' % os.path.join(root, name) + print('removing: %s' % os.path.join(root, name)) if not(self.dry_run): os.remove(os.path.join(root, name)) try: os.remove("autoradio/programs/static/programs/playogg/js/jquery-1.12.4.min.js") except: - print "autoradio/programs/static/programs/playogg/js/jquery-1.12.4.min.js not removed" + print("autoradio/programs/static/programs/playogg/js/jquery-1.12.4.min.js not removed") try: os.remove("autoradio/programs/static/programs/playogg/js/jquery.min.js") except: - print "autoradio/programs/static/programs/playogg/js/jquery.min.js not removed" + print("autoradio/programs/static/programs/playogg/js/jquery.min.js not removed") try: os.remove("autoradio/programs/static/programs/playogg/flash/AnOgg.swf") except: - print "autoradio/programs/static/programs/playogg/flash/AnOgg.swf not removed" + print("autoradio/programs/static/programs/playogg/flash/AnOgg.swf not removed") try: os.remove("anoggplayer/anoggplayer/AnOgg.swf") except: - print "anoggplayer/anoggplayer/AnOgg.swf not removed" + print("anoggplayer/anoggplayer/AnOgg.swf not removed") try: os.remove("autoradio/programs/static/programs/playogg/java/cortado.jar") except: - print "autoradio/programs/static/programs/playogg/java/cortado.jar not removed" + print("autoradio/programs/static/programs/playogg/java/cortado.jar not removed") try: os.remove("autoradio/programs/static/programs/playogg/java/cortado-ovt-stripped-0.6.0.jar") except: - print "autoradio/programs/static/programs/playogg/java/cortado-ovt-stripped-0.6.0.jar not removed" + print("autoradio/programs/static/programs/playogg/java/cortado-ovt-stripped-0.6.0.jar not removed") try: os.remove("autoradio/programs/static/programs/playogg/swfobject/expressInstall.swf") except: - print "autoradio/programs/static/programs/playogg/swfobject/expressInstall.swf not removed" + print("autoradio/programs/static/programs/playogg/swfobject/expressInstall.swf not removed") try: os.remove("autoradio/programs/static/programs/playogg/swfobject/swfobject.js") except: - print "autoradio/programs/static/programs/playogg/swfobject/swfobject.js not removed" + print("autoradio/programs/static/programs/playogg/swfobject/swfobject.js not removed") class build(build_): @@ -169,7 +170,7 @@ def run(self): subprocess.check_call(["make"]) os.chdir("../..") except: - print "WARNING !!!!! anoggplayer not created" + print("WARNING !!!!! anoggplayer not created") class djangocollectstatic(Command): description = "collect static files for web server to serve it" From 78ed500e025dc55e876f3d21ed9b36155f790c77 Mon Sep 17 00:00:00 2001 From: pat1 Date: Sat, 21 Jul 2018 11:11:28 +0200 Subject: [PATCH 3/8] new migration for python3 --- .../migrations/0002_auto_20180721_1059.py | 20 +++++++++++++++++++ .../migrations/0002_auto_20180721_1059.py | 20 +++++++++++++++++++ .../migrations/0002_auto_20180721_1059.py | 20 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 autoradio/jingles/migrations/0002_auto_20180721_1059.py create mode 100644 autoradio/playlists/migrations/0002_auto_20180721_1059.py create mode 100644 autoradio/spots/migrations/0002_auto_20180721_1059.py diff --git a/autoradio/jingles/migrations/0002_auto_20180721_1059.py b/autoradio/jingles/migrations/0002_auto_20180721_1059.py new file mode 100644 index 0000000..ec8da78 --- /dev/null +++ b/autoradio/jingles/migrations/0002_auto_20180721_1059.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2018-07-21 10:59 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('jingles', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='giorno', + name='name', + field=models.CharField(choices=[(b'luned\xc3\xac', b'luned\xc3\xac'), (b'marted\xc3\xac', b'marted\xc3\xac'), (b'mercoled\xc3\xac', b'mercoled\xc3\xac'), (b'gioved\xc3\xac', b'gioved\xc3\xac'), (b'venerd\xc3\xac', b'venerd\xc3\xac'), (b'sabato', b'sabato'), (b'domenica', b'domenica')], help_text='weekday name', max_length=20, unique=True), + ), + ] diff --git a/autoradio/playlists/migrations/0002_auto_20180721_1059.py b/autoradio/playlists/migrations/0002_auto_20180721_1059.py new file mode 100644 index 0000000..9050dc3 --- /dev/null +++ b/autoradio/playlists/migrations/0002_auto_20180721_1059.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2018-07-21 10:59 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('playlists', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='giorno', + name='name', + field=models.CharField(choices=[(b'luned\xc3\xac', b'luned\xc3\xac'), (b'marted\xc3\xac', b'marted\xc3\xac'), (b'mercoled\xc3\xac', b'mercoled\xc3\xac'), (b'gioved\xc3\xac', b'gioved\xc3\xac'), (b'venerd\xc3\xac', b'venerd\xc3\xac'), (b'sabato', b'sabato'), (b'domenica', b'domenica')], help_text='weekday name', max_length=20, unique=True), + ), + ] diff --git a/autoradio/spots/migrations/0002_auto_20180721_1059.py b/autoradio/spots/migrations/0002_auto_20180721_1059.py new file mode 100644 index 0000000..ac367d2 --- /dev/null +++ b/autoradio/spots/migrations/0002_auto_20180721_1059.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2018-07-21 10:59 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('spots', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='giorno', + name='name', + field=models.CharField(choices=[(b'luned\xc3\xac', b'luned\xc3\xac'), (b'marted\xc3\xac', b'marted\xc3\xac'), (b'mercoled\xc3\xac', b'mercoled\xc3\xac'), (b'gioved\xc3\xac', b'gioved\xc3\xac'), (b'venerd\xc3\xac', b'venerd\xc3\xac'), (b'sabato', b'sabato'), (b'domenica', b'domenica')], help_text='weekday name', max_length=20, unique=True), + ), + ] From e807e0931f9d6e412175c76c80ffc1837cbbc80b Mon Sep 17 00:00:00 2001 From: pat1 Date: Mon, 23 Jul 2018 16:11:19 +0200 Subject: [PATCH 4/8] ported player to python 3 --- autoplayergui | 66 ++-- autoradio/autompris2.py | 19 +- autoradio/autoplayer/player_gstreamer0.py | 5 +- autoradio/autoplayer/playlist.py | 45 ++- autoradio/dbusdecorator/__init__.py | 13 + autoradio/dbusdecorator/__main__.py | 10 + autoradio/dbusdecorator/attribute.py | 65 ++++ autoradio/dbusdecorator/base.py | 19 + autoradio/dbusdecorator/interface.py | 125 +++++++ autoradio/dbusdecorator/method.py | 121 +++++++ autoradio/dbusdecorator/signal.py | 69 ++++ autoradio/dbusdecorator/utils.py | 162 +++++++++ autoradio/mpris2/loop_status.py | 4 +- autoradio/mpris2/mediaplayer2.py | 8 +- autoradio/mpris2/playback_status.py | 6 +- autoradio/mpris2/player.py | 30 +- autoradio/mpris2/playlists.py | 8 +- autoradio/mpris2/tracklist.py | 8 +- autoradio/mpris2/types.py | 2 +- autoradio/mprisweb.py | 30 +- autoradio/pydbusdecorator/__init__.py | 15 - autoradio/pydbusdecorator/dbus_attr.py | 96 ----- autoradio/pydbusdecorator/dbus_data.py | 27 -- autoradio/pydbusdecorator/dbus_decorator.py | 20 -- autoradio/pydbusdecorator/dbus_interface.py | 347 ------------------- autoradio/pydbusdecorator/dbus_method.py | 141 -------- autoradio/pydbusdecorator/dbus_signal.py | 87 ----- autoradio/pydbusdecorator/undefined_param.py | 27 -- 28 files changed, 732 insertions(+), 843 deletions(-) create mode 100644 autoradio/dbusdecorator/__init__.py create mode 100644 autoradio/dbusdecorator/__main__.py create mode 100644 autoradio/dbusdecorator/attribute.py create mode 100644 autoradio/dbusdecorator/base.py create mode 100644 autoradio/dbusdecorator/interface.py create mode 100644 autoradio/dbusdecorator/method.py create mode 100644 autoradio/dbusdecorator/signal.py create mode 100644 autoradio/dbusdecorator/utils.py delete mode 100644 autoradio/pydbusdecorator/__init__.py delete mode 100644 autoradio/pydbusdecorator/dbus_attr.py delete mode 100644 autoradio/pydbusdecorator/dbus_data.py delete mode 100644 autoradio/pydbusdecorator/dbus_decorator.py delete mode 100644 autoradio/pydbusdecorator/dbus_interface.py delete mode 100644 autoradio/pydbusdecorator/dbus_method.py delete mode 100644 autoradio/pydbusdecorator/dbus_signal.py delete mode 100644 autoradio/pydbusdecorator/undefined_param.py diff --git a/autoplayergui b/autoplayergui index 005deb4..db6b285 100755 --- a/autoplayergui +++ b/autoplayergui @@ -2,6 +2,13 @@ # -*- coding: utf-8 -*- # GPL. (C) 2013 Paolo Patruno. +from __future__ import division +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import range +from builtins import object +from past.utils import old_div from autoradio.mpris2.mediaplayer2 import MediaPlayer2 from autoradio.mpris2.player import Player from autoradio.mpris2.tracklist import TrackList @@ -10,12 +17,23 @@ from autoradio.mpris2.some_players import Some_Players from autoradio.mpris2.utils import get_players_uri from autoradio.mpris2.utils import get_session from dbus.mainloop.glib import DBusGMainLoop -import pygtk, gtk -import os,stat,time,urlparse,urllib,optparse,sys +#import pygtk +try: + from gi import pygtkcompat +except ImportError: + pygtkcompat = None + +if pygtkcompat is not None: + pygtkcompat.enable() + pygtkcompat.enable_gtk(version='3.0') + +import gtk + +import os,stat,time,urllib.parse,urllib.request,urllib.parse,urllib.error,optparse,sys import gobject import dbus import autoradio.settings -import urlparse +import urllib.parse import traceback busaddress=autoradio.settings.busaddressplayer @@ -38,11 +56,11 @@ class Main(object): return False def playhandler(self, *args, **kw): - #print args, kw - playbackstatus = args[2].get("PlaybackStatus",None) - position = args[2].get("Position",None) + playbackstatus = args[1].get("PlaybackStatus",None) + position = args[1].get("Position",None) + if playbackstatus is not None: - print "PlaybackStatus",playbackstatus + print("PlaybackStatus",playbackstatus) if playbackstatus == "Stopped": self.play_button.set_sensitive(True) @@ -63,7 +81,7 @@ class Main(object): if id is not None: length=self.tl.GetTracksMetadata((id,))[0].get(u'mpris:length',None) if position <= length and length != 0: - frac = float(position)/float(length) + frac = old_div(float(position),float(length)) else: frac = 0 else: @@ -92,7 +110,7 @@ class Main(object): self.mp2 = MediaPlayer2(dbus_interface_info={'dbus_uri': uri,'dbus_session':bus}) self.play = Player(dbus_interface_info={'dbus_uri': uri,'dbus_session':bus}) else: - print "No players availables" + print("No players availables") return if hasattr (self.mp2, 'HasTrackList'): @@ -144,7 +162,7 @@ class Main(object): # Create the ProgressBar self.pbar = gtk.ProgressBar() - self.pbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT) + self.pbar.set_inverted(False) self.pbar.set_fraction(.5) hbox.pack_start(self.pbar) self.pbar.show() @@ -188,7 +206,7 @@ class Main(object): #gobject.timeout_add(6000,self.update) def update(self, *args, **kw): - print "update gtktree" + print("update gtktree") try: new_model = self.make_list() self.treeview.set_model(new_model) @@ -215,15 +233,15 @@ class Main(object): for path in paths: iter = model.get_iter(path) # Remove the ListStore row referenced by iter - print "remove: ",model.get_value(iter, 0) + print("remove: ",model.get_value(iter, 0)) self.tl.RemoveTrack(model.get_value(iter, 0)) #model.remove(iter) def on_file_selected(self, widget): multimedia_file = self.load_file.get_filename() - url=urlparse.urlsplit(multimedia_file) - uri=urlparse.urljoin("file://",urllib.unquote(url.path)) + url=urllib.parse.urlsplit(multimedia_file) + uri=urllib.parse.urljoin("file://",urllib.parse.unquote(url.path)) new_model = self.make_list() self.treeview.set_model(new_model) self.tl.AddTrack(uri, self.play.Metadata.get(u'mpris:trackid',""), False) @@ -238,7 +256,7 @@ class Main(object): def open_file(self, treeview, path, column): model = treeview.get_model() iter = model.get_iter(path) - print "goto: ",model.get_value(iter, 0) + print("goto: ",model.get_value(iter, 0)) self.tl.GoTo(model.get_value(iter, 0)) new_model = self.make_list() self.treeview.set_model(new_model) @@ -253,13 +271,13 @@ class Main(object): for track in self.tl.GetTracksMetadata( self.tl.Tracks): listmodel.append([track.get(u'mpris:trackid',"")]) except: - print traceback.format_exc() - print "Error getting player playlist" + print(traceback.format_exc()) + print("Error getting player playlist") gtk.main_quit() return listmodel - def id(self, column, cell, model, iter): + def id(self, column, cell, model, iter, data=None): cell.set_property('text', model.get_value(iter, 0)) if model.get_value(iter, 0) == self.play.Metadata.get(u'mpris:trackid',None): cell.set_property('cell-background',"red") @@ -267,20 +285,20 @@ class Main(object): cell.set_property('cell-background',"green") return - def Len(self, column, cell, model, iter): + def Len(self, column, cell, model, iter, data=None): track=self.tl.GetTracksMetadata((model.get_value(iter, 0),)) cell.set_property('text', convert_ns(track[0].get(u'mpris:length',""))) return - def Artist(self, column, cell, model, iter): + def Artist(self, column, cell, model, iter, data=None): track=self.tl.GetTracksMetadata((model.get_value(iter, 0),)) - dir=os.path.dirname(urlparse.urlparse(track[0].get(u'xesam:url',"")).path).split('/')[-1] + dir=os.path.dirname(urllib.parse.urlparse(track[0].get(u'xesam:url',"")).path).split('/')[-1] cell.set_property('text', track[0].get(u'xesam:artist', dir)) return - def Title(self, column, cell, model, iter): + def Title(self, column, cell, model, iter, data=None): track=self.tl.GetTracksMetadata((model.get_value(iter, 0),)) - file=os.path.basename(urlparse.urlparse(track[0].get(u'xesam:url',"")).path) + file=os.path.basename(urllib.parse.urlparse(track[0].get(u'xesam:url',"")).path) cell.set_property('text', track[0].get(u'xesam:title',file)) return @@ -302,5 +320,5 @@ if __name__ == "__main__": gtk.main() except KeyboardInterrupt : # Clean up - print 'Keyboard Exiting' + print('Keyboard Exiting') gtk.main_quit() diff --git a/autoradio/autompris2.py b/autoradio/autompris2.py index 0f95619..3e98d70 100644 --- a/autoradio/autompris2.py +++ b/autoradio/autompris2.py @@ -15,15 +15,16 @@ from gi.repository import GObject as gobject else: import gobject -import autoradio.settings + +from . import settings from dbus.mainloop.glib import DBusGMainLoop -from autoradio.mpris2.mediaplayer2 import MediaPlayer2 -from autoradio.mpris2.player import Player -from autoradio.mpris2.tracklist import TrackList -from autoradio.mpris2.interfaces import Interfaces -from autoradio.mpris2.some_players import Some_Players -from autoradio.mpris2.utils import get_players_uri -from autoradio.mpris2.utils import get_session +from .mpris2.mediaplayer2 import MediaPlayer2 +from .mpris2.player import Player +from .mpris2.tracklist import TrackList +from .mpris2.interfaces import Interfaces +from .mpris2.some_players import Some_Players +from .mpris2.utils import get_players_uri +from .mpris2.utils import get_session # ------- dbus mpris2 interface --------- # http://specifications.freedesktop.org/mpris-spec/latest/index.html @@ -71,7 +72,7 @@ class mediaplayer(object): - def __init__(self,player="AutoPlayer",session=0, busaddress=autoradio.settings.busaddressplayer): + def __init__(self,player="AutoPlayer",session=0, busaddress=settings.busaddressplayer): #qdbus --literal org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get org.mpris.MediaPlayer2.TrackList Tracks # import gobject diff --git a/autoradio/autoplayer/player_gstreamer0.py b/autoradio/autoplayer/player_gstreamer0.py index 74aca7a..a3459bb 100644 --- a/autoradio/autoplayer/player_gstreamer0.py +++ b/autoradio/autoplayer/player_gstreamer0.py @@ -31,7 +31,10 @@ from builtins import object from past.utils import old_div import sys, time, _thread -import gobject +if sys.version_info[0] == 3: + from gi.repository import GObject as gobject +else: + import gobject import pygst pygst.require("0.10") import gst diff --git a/autoradio/autoplayer/playlist.py b/autoradio/autoplayer/playlist.py index 3f602b5..7a17696 100644 --- a/autoradio/autoplayer/playlist.py +++ b/autoradio/autoplayer/playlist.py @@ -147,7 +147,10 @@ def endElement(s, name): if (url.scheme == "http"): s.track['location']=url.geturl() else: - s.track['location']=urllib.parse.urljoin("file://",urllib.parse.unquote(url.path.encode("UTF-8"))) + if sys.version_info[0] == 3: + s.track['location']=urllib.parse.urljoin(u"file://",urllib.parse.unquote(url.path)) + else: + s.track['location']=urllib.parse.urljoin(u"file://",urllib.parse.unquote(url.path.encode("UTF-8"))) elif s.path == "/playlist/trackList/track/title": s.track['title'] = s.content @@ -210,8 +213,9 @@ def read(s, path): except: lines = data.split('\n') - lines = [line.strip().rstrip() for line in lines] - lines = [line for line in lines if line if line != "" and line[0] != '#' else None] + lines = map(lambda line: line.strip().rstrip(), lines) + lines = filter(lambda line: line if line != "" and line[0] != '#' else None, lines) + if lines == []: return @@ -229,7 +233,7 @@ def read(s, path): if (url.scheme == "http"): location=url.geturl() else: - location=urllib.parse.urljoin("file://",urllib.parse.unquote(url.path)) + location=urllib.parse.urljoin(u"file://",urllib.parse.unquote(url.path)) track=Track._make(list(Track(location,None,None,None,None,None).get_metadata().values())) s.append(track) @@ -299,13 +303,26 @@ def write(s,path): track=track._asdict() f.write('\t\n') if track.get('title') not in ['', None]: - f.write( '\t\t%s\n' \ + if sys.version_info[0] == 3: + f.write( '\t\t%s\n' \ + % doc.createTextNode(track['title']).toxml() ) + else: + f.write( '\t\t%s\n' \ % doc.createTextNode(track['title'].encode("utf-8")).toxml() ) if track.get('artist') not in ['', None]: - f.write('\t\t%s\n' \ + + if sys.version_info[0] == 3: + f.write('\t\t%s\n' \ + % doc.createTextNode(track['artist']).toxml() ) + else: + f.write('\t\t%s\n' \ % doc.createTextNode(track['artist'].encode("utf-8")).toxml() ) if track.get('album') not in ['', None]: - f.write( '\t\t%s\n' \ + if sys.version_info[0] == 3: + f.write( '\t\t%s\n' \ + % doc.createTextNode(track['album']).toxml() ) + else: + f.write( '\t\t%s\n' \ % doc.createTextNode(track['album'].encode("utf-8")).toxml() ) if track.get('tracknum') not in ['', None]: if type(track['tracknum']) == int: @@ -343,11 +360,14 @@ def write(s,path): if (url.scheme == "http"): location=url.geturl() else: - #here problem when file name come fron gtk or command line + #here problem when file name come from gtk or command line try: - location=urllib.parse.urljoin("file://",urllib.parse.quote(url.path)) + location=urllib.parse.urljoin(u"file://",urllib.parse.quote(url.path)) except: - location=urllib.parse.urljoin("file://",urllib.parse.quote(url.path.encode("UTF-8"))) + if sys.version_info[0] == 3: + raise + else: + location=urllib.parse.urljoin("file://",urllib.parse.quote(url.path.encode("UTF-8"))) ##location = location.encode("utf-8") #if not 'http://' in location.lower() and \ @@ -381,7 +401,10 @@ def write(s,path): v = '1' if v else '0' elif t in [int, int]: t = "int" - v = str(v).encode("utf-8") + if sys.version_info[0] == 3: + v = str(v) + else: + v = str(v).encode("utf-8") elif t == float: t = "float" v = repr(v) diff --git a/autoradio/dbusdecorator/__init__.py b/autoradio/dbusdecorator/__init__.py new file mode 100644 index 0000000..ea7a66d --- /dev/null +++ b/autoradio/dbusdecorator/__init__.py @@ -0,0 +1,13 @@ +''' +This is not part of specification + +Helper class to make it work as python lib +''' + + +from .attribute import DbusAttr +from .interface import DbusInterface +from .method import DbusMethod +from .signal import DbusSignal +from .utils import get_mainloop, get_uri, implements, \ +list_all_interface, list_interfaces, list_paths diff --git a/autoradio/dbusdecorator/__main__.py b/autoradio/dbusdecorator/__main__.py new file mode 100644 index 0000000..fbbf74f --- /dev/null +++ b/autoradio/dbusdecorator/__main__.py @@ -0,0 +1,10 @@ +from . import DbusAttr +from . import DbusInterface +from . import DbusMethod +from . import DbusSignal + +if __name__ == '__main__': + print(DbusAttr()) + print(DbusInterface()) + print(DbusMethod()) + print(DbusSignal()) diff --git a/autoradio/dbusdecorator/attribute.py b/autoradio/dbusdecorator/attribute.py new file mode 100644 index 0000000..f189d57 --- /dev/null +++ b/autoradio/dbusdecorator/attribute.py @@ -0,0 +1,65 @@ +''' +This is not part of specification + +Helper class to make it work as python lib +''' + +from .base import Decorator, ATTR_KEY + + +class DbusAttr(Decorator): + ''' + https://docs.python.org/2/howto/descriptor.html#properties + ''' + + def __init__(self, meth=None, produces=lambda resp: resp): + self.attr = meth + self.produces = produces + self._update_me(meth) + + def __call__(self, meth): + self.attr = meth + self._update_me(meth) + return self + + def __get__(self, obj, objtype=None): + #static call + if not obj: + return self + + _dbus = getattr(obj, ATTR_KEY) + props = _dbus.properties + iface = _dbus.iface + result = props.Get(iface, self.attr.__name__) + produces = self.produces + return produces(result) + + def __set__(self, obj, value): + if obj: + _dbus = getattr(obj, ATTR_KEY) + props = _dbus.properties + iface = _dbus.iface + props.Set(iface, self.attr.__name__, value) + else: #static call + self.attr = value + + def __delete__(self, obj): + raise AttributeError('can not delete attribute') + + +if __name__ == '__main__': + # examples + from .interface import DbusInterface + + @DbusInterface('org.mpris.MediaPlayer2', + '/org/mpris/MediaPlayer2') + class Example(object): + @DbusAttr + def Identity(self): + pass + + d = Example( + dbus_interface_info={ + 'dbus_uri': 'org.mpris.MediaPlayer2.vlc'}) + + assert d.Identity == 'VLC media player' diff --git a/autoradio/dbusdecorator/base.py b/autoradio/dbusdecorator/base.py new file mode 100644 index 0000000..00b2a17 --- /dev/null +++ b/autoradio/dbusdecorator/base.py @@ -0,0 +1,19 @@ +''' +This is not part of specification + +Helper class to make it work as python lib +''' + +I_PROP = 'org.freedesktop.DBus.Properties' +ARG_KEY = 'dbus_interface_info' +ATTR_KEY = '_dbus_interface_info' + + +class Decorator(object): + def _update_me(self, target=None): + if hasattr(target, "__doc__"): + self.__doc__ = target.__doc__ + if hasattr(target, "__name__"): + self.__name__ = target.__name__ + if hasattr(target, "__bases__"): + self.__bases__ = target.__bases__ diff --git a/autoradio/dbusdecorator/interface.py b/autoradio/dbusdecorator/interface.py new file mode 100644 index 0000000..882a894 --- /dev/null +++ b/autoradio/dbusdecorator/interface.py @@ -0,0 +1,125 @@ +''' +This is not part of specification + +Helper class to make it work as python lib +''' + +import dbus +from functools import wraps +from .base import Decorator, ARG_KEY, I_PROP, ATTR_KEY + + +class _DbusInfoProperty(object): + def __init__(self, iface=None, path=None, + uri=None, dbus_object=None, session=None, wrapped=None): + self.iface = iface + self.path = path + self.uri = uri + self.object = dbus_object + self.session = session + self.wrapped = wrapped + self.interface = None + self.properties = None + + if not self.object: + bus = self.session = self.session or dbus.SessionBus() + self.object = bus.get_object(self.uri, self.path) + if not self.interface: + self.interface = dbus.Interface(self.object, + dbus_interface=self.iface) + if not self.properties: + self.properties = dbus.Interface(self.object, I_PROP) + + def reconnect(self, session=None): + ''' + Required if you need update session/proxy object/interfaces + ''' + + session = session or self.session + if session == self.session: + self.session.close() + session = self.session = dbus.SessionBus() + self.object = session.get_object(self.uri, self.path) + self.interface = dbus.Interface(self.object, dbus_interface=self.iface) + self.properties = dbus.Interface(self.object, I_PROP) + + +class DbusInterface(Decorator): + + def __init__(self, iface=None, path=None, + uri=None, dbus_object=None, session=None): + self.iface = iface + self.path = path + self.uri = uri + self.object = dbus_object + self.session = session + self.wrapped = None + + def __call__(self, meth): + ''' Called when any decorated class is loaded''' + self.wrapped = meth + self._update_me(meth) + + @wraps(meth) + def dbusWrapedInterface(*args, **kw): + _args = kw.get(ARG_KEY, {}) + info_property = _DbusInfoProperty( + iface=_args.get('dbus_iface', self.iface), + path=_args.get('dbus_path', self.path), + uri=_args.get('dbus_uri', self.uri), + dbus_object =_args.get('dbus_object', self.object), + session =_args.get('dbus_session', self.session), + wrapped=self.wrapped + ) + if ARG_KEY in kw: + del kw[ARG_KEY] + + return self.dbusWrapedInterface(info_property, *args, **kw) + + return dbusWrapedInterface + + def dbusWrapedInterface(self, info_property, *args, **kw): + ''' Called when some decoreted class was called + Inject attrs from decorator at new object then return object + + @param *args: list of args to call constructor + @param **kw: dict of keywords, can redefine class default parameters + @return: instance of decoreted class, with new attributes + @see: mpris2.mediaplayer2 to see some examples + ''' + #call decorated class constructor + new_obj = self.wrapped(*args, **kw) + if new_obj: + setattr(new_obj, ATTR_KEY, info_property) + elif len(args) > 0: + setattr(args[0], ATTR_KEY, info_property) + + return new_obj + + +if __name__ == '__main__': + # examples + @DbusInterface('org.freedesktop.DBus', '/') + class Example(object): + pass + + + d = Example( + dbus_interface_info={ + 'dbus_uri': 'org.freedesktop.DBus'}) + assert d._dbus_interface_info.iface == 'org.freedesktop.DBus' + assert d._dbus_interface_info.path == '/' + assert d._dbus_interface_info.uri == 'org.freedesktop.DBus' + + class ExempleToo(object): + @DbusInterface('org.freedesktop.DBus', '/') + def __init__(self): + pass + + dd = ExempleToo( + dbus_interface_info={ + 'dbus_uri': 'org.freedesktop.DBus'}) + + assert dd._dbus_interface_info.iface == 'org.freedesktop.DBus' + assert dd._dbus_interface_info.path == '/' + assert dd._dbus_interface_info.uri == 'org.freedesktop.DBus' diff --git a/autoradio/dbusdecorator/method.py b/autoradio/dbusdecorator/method.py new file mode 100644 index 0000000..eb7bc07 --- /dev/null +++ b/autoradio/dbusdecorator/method.py @@ -0,0 +1,121 @@ +''' +This is not part of specification + +Helper class to make it work as python lib +''' + +from .base import Decorator, ATTR_KEY + + +def kw_to_dbus(**kw): + return kw + +def args_to_dbus(*args): + return args + + +class DbusMethod(Decorator): + + def __init__(self, meth=None, + iface=None, + produces=lambda resp: resp, + args_to_dbus=args_to_dbus, + kw_to_dbus=kw_to_dbus, + std_args=(), + std_kwds={}): + self.meth = meth + self.handler = None + self.produces = produces + self.iface = iface + self.args_to_dbus = args_to_dbus + self.kw_to_dbus = kw_to_dbus + self.std_args = std_args + self.std_kwds = std_kwds + self.obj = None + self._update_me(meth) + + def __call__(self, meth=None): + self.meth = meth + self._update_me(meth) + return self + + def __get__(self, obj=None, cls=None): + if obj is None: + return self + self.obj = obj + return self._call_dbus + + def _call_dbus(self, *args, **kwds): + _dbus = getattr(self.obj, ATTR_KEY) + if self.iface: + iface = self.iface + else: + iface = _dbus.iface + bus_obj = _dbus.object + bus_meth = bus_obj.get_dbus_method(self.meth.__name__, iface) + _args = self.merge_args(args, self.std_args) + args = self.convert_args_to_dbus_args(*_args) + _kwds = self.std_kwds.copy() + _kwds.update(kwds) + kwds = self.convert_kw_to_dbus_kw(**_kwds) + result = bus_meth(*args, **kwds) + return self.produces(result) + + @classmethod + def merge_args(cls, args, std_args): + _len = len(std_args) - len(args) + return args + std_args[-_len:] if _len > 0 else args + + @classmethod + def merge_kwds(cls, kwds, std_kwds): + _kwds = std_kwds.copy() + _kwds.update(kwds) + return _kwds + + def convert_args_to_dbus_args(self, *args): + args_to_dbus = self.args_to_dbus + if callable(args_to_dbus): + return args_to_dbus(*args) + + #iterate over args + result = [] + for arg in args: + i = args.index(arg) + if i < len(args_to_dbus): + make = args_to_dbus[i] + if callable(make): + arg = make(arg) + result.append(arg) + return tuple(result) + + def convert_kw_to_dbus_kw(self, **kw): + kw_to_dbus = self.kw_to_dbus + if callable(kw_to_dbus): + return kw_to_dbus(**kw) + + if hasattr(self.kw_to_dbus, 'keys'): + for key, val in kw.items(): + make = kw_to_dbus.get(key, lambda v: v) + kw[key] = make(val) + return kw + + +if __name__ == '__main__': + # examples + from .interface import DbusInterface + @DbusInterface('org.freedesktop.DBus', '/') + class Example(object): + + @DbusMethod + def GetId(self): + pass + + @DbusMethod + def GetNameOwner(self, name): + pass + + d = Example( + dbus_interface_info={ + 'dbus_uri': 'org.freedesktop.DBus'}) + assert d.GetId() + assert d.GetNameOwner('org.freedesktop.DBus') == 'org.freedesktop.DBus' diff --git a/autoradio/dbusdecorator/signal.py b/autoradio/dbusdecorator/signal.py new file mode 100644 index 0000000..0239a2e --- /dev/null +++ b/autoradio/dbusdecorator/signal.py @@ -0,0 +1,69 @@ +from .base import Decorator, ATTR_KEY + + +class DbusSignal(Decorator): + ''' + https://docs.python.org/2/howto/descriptor.html#properties + ''' + + def __init__(self, meth=None, iface=None): + self.attr = meth + self.handler = None + self.iface = iface + self._update_me(meth) + + def __call__(self, meth): + self.attr = meth + self._update_me(meth) + return self + + def __get__(self, obj, objtype=None): + if obj: + return self.handler + + #static call + return self + + def __set__(self, obj, value): + if obj: + _dbus = getattr(obj, ATTR_KEY) + interface = _dbus.interface + def handle(*args, **kwds): + h = self.handler + h and h(*args, **kwds) + + if not self.handler: + interface.connect_to_signal(self.attr.__name__, handle, + dbus_interface=self.iface) + self.handler = value + else: #static call + self.attr = value + + def __delete__(self, obj): + self.handler = None + + +if __name__ == '__main__': + from .interface import DbusInterface + from .utils import get_mainloop + mainloop = get_mainloop() + print('mainloop', mainloop) + + @DbusInterface('org.mpris.MediaPlayer2.player', + '/org/mpris/MediaPlayer2') + class Example(object): + + @DbusSignal + def Seeked(self): + pass + + + d = Example( + dbus_interface_info={ + 'dbus_uri': 'org.mpris.MediaPlayer2.gmusicbrowser'}) + + def handler(self, *args): + print(args) + + d.Seeked = handler + mainloop and mainloop.run() diff --git a/autoradio/dbusdecorator/utils.py b/autoradio/dbusdecorator/utils.py new file mode 100644 index 0000000..70aafa9 --- /dev/null +++ b/autoradio/dbusdecorator/utils.py @@ -0,0 +1,162 @@ +''' +utils functions +''' + +import dbus, re +import xml.etree.ElementTree as ET + + +I_INSPECT = 'org.freedesktop.DBus.Introspectable' + +def _match_uri(name, pattern='.+'): + ''' + Filter logic for get_players and get_player_uri + @param name: string name to test + @param pattern=None: string RegEx to test + @return: boolean + ''' + return re.match(pattern, name) + +def get_session(): + ''' + @return: dbus.SessionBus.get_session() + ''' + return dbus.SessionBus.get_session() + +def get_uri(pattern='.'): + ''' + Return string of player bus name + @param pattern=None: string RegEx that filter response + @return: array string of players bus name + ''' + for item in get_session().list_names(): + if _match_uri(item, pattern): + yield item + + +def get_mainloop(): + ''' + @return: mainloop (with 'run' method) + ''' + try: + from dbus.mainloop.glib import DBusGMainLoop + DBusGMainLoop(set_as_default=True) + try: + import gobject + return gobject.MainLoop() + except: + pass + + try: + import gi.repository.GLib + return gi.repository.GLib.MainLoop() + except: + pass + except: + pass + + class PyQtMainLoop(): + def __init__(self, app): + self.app = app + + def run(self): + if hasattr(self.app, 'exec_'): + self.app.exec_() + if hasattr(self.app, 'exec'): + method = getattr(self.app, 'exec') + method(self.app) + + + try: + from dbus.mainloop.qt import DBusQtMainLoop + DBusQtMainLoop(set_as_default=True) + try: + from PySide.QtGui import QApplication + return PyQtMainLoop(QApplication([])) + except: + pass + + try: + from PyQt5.QtWidgets import QApplication + return PyQtMainLoop(QApplication([])) + except: + pass + + try: + from PyQt4 import Qt + return PyQtMainLoop(Qt.QApplication([])) + except: + pass + except: + pass + + return None + +def _introspect_uri(bus_name, path, bus): + bus = bus or dbus.SessionBus.get_session() + path = path.replace('//', '/') or '/' + obj = bus.get_object(bus_name, path) + xml = obj.Introspect(dbus_interface=I_INSPECT) + return ET.fromstring(xml) + +def list_paths(bus_name, path='/', bus=None): + ''' + Return generator with all subpaths of uri + @param bus_name: string dbus object name + @param path='/': string dbus object path + @param bus=None: Conn dbus.Conn (commonly SessionBus or SystemBus) + @return: generator with all paths that has interfaces + ''' + nodes = _introspect_uri(bus_name, path, bus) + if [iface for iface in nodes.findall('interface')]: + yield path.replace('//', '/') + + for node in nodes.findall('node'): + sub_path = path + '/'+ node.attrib['name'] + for path_name in list_paths(bus_name, sub_path, bus): + yield path_name + +def list_interfaces(bus_name, path, bus=None): + ''' + Return generator with all interfaces of path + @param bus_name: string dbus object name + @param path: string dbus object path + @param bus=None: Conn dbus.Conn (commonly SessionBus or SystemBus) + @return: generator with all interfaces of path + ''' + nodes = _introspect_uri(bus_name, path, bus) + for interface in nodes.findall('interface'): + yield interface.attrib['name'] + +def list_all_interface(bus_name, path='/', bus=None): + ''' + Return generator with all interfaces of path and subpaths + @param bus_name: string dbus object name + @param path: string dbus object path + @param bus=None: Conn dbus.Conn (commonly SessionBus or SystemBus) + @return: generator with all interfaces of path and subpaths + ''' + paths = list_paths(bus_name, path, bus) + for sub_path in paths: + for interface in list_interfaces(bus_name, sub_path, bus): + yield sub_path, interface + +def implements(uri, interface, path, bus=None): + ''' + ''' + for iface in list_interfaces(uri, path, bus): + if iface == interface: + return True + + +if __name__ == '__main__': + uri = None + for uri in get_uri(): + if uri.count(':') == 0: + print(uri) + + if uri: + for interface in list_all_interface(uri, '/'): + print('\t', interface) + else: + print('Nothing running') diff --git a/autoradio/mpris2/loop_status.py b/autoradio/mpris2/loop_status.py index 3cc299b..ec3e7a0 100644 --- a/autoradio/mpris2/loop_status.py +++ b/autoradio/mpris2/loop_status.py @@ -17,7 +17,7 @@ class Loop_Status(str): ''' VALUES = (NONE, TRACK, PLAYLIST) def __init__(self, status, *args, **kw): - super(Loop_Status, self).__init__(status, *args, **kw) + super(Loop_Status, self).__init__() self._status = status def __int__(self, *args, **kwargs): @@ -31,4 +31,4 @@ def __int__(self, *args, **kwargs): print(Loop_Status.PLAYLIST) print(type(Loop_Status.PLAYLIST)) print(Loop_Status.PLAYLIST == NONE) - print(Loop_Status.PLAYLIST == PLAYLIST) \ No newline at end of file + print(Loop_Status.PLAYLIST == PLAYLIST) diff --git a/autoradio/mpris2/mediaplayer2.py b/autoradio/mpris2/mediaplayer2.py index 95f3645..e8cca9d 100644 --- a/autoradio/mpris2/mediaplayer2.py +++ b/autoradio/mpris2/mediaplayer2.py @@ -7,10 +7,10 @@ from __future__ import absolute_import -from autoradio.pydbusdecorator.dbus_attr import DbusAttr -from autoradio.pydbusdecorator.dbus_interface import DbusInterface -from autoradio.pydbusdecorator.dbus_method import DbusMethod -from autoradio.pydbusdecorator.dbus_signal import DbusSignal +from autoradio.dbusdecorator import DbusAttr +from autoradio.dbusdecorator import DbusInterface +from autoradio.dbusdecorator import DbusMethod +from autoradio.dbusdecorator import DbusSignal from .interfaces import Interfaces diff --git a/autoradio/mpris2/playback_status.py b/autoradio/mpris2/playback_status.py index d330ac4..5dde455 100644 --- a/autoradio/mpris2/playback_status.py +++ b/autoradio/mpris2/playback_status.py @@ -16,8 +16,8 @@ class Playback_Status(str): ''' VALUES = (PLAYING, PAUSED, STOPPED) - def __init__(self, status, *args, **kw): - super(Playback_Status, self).__init__(status, *args, **kw) + def __init__(self, status): + super(Playback_Status, self).__init__() self._status = status @property @@ -26,4 +26,4 @@ def status(self): Playback_Status.PLAYING = PLAYING Playback_Status.PAUSED = PAUSED -Playback_Status.STOPPED = STOPPED \ No newline at end of file +Playback_Status.STOPPED = STOPPED diff --git a/autoradio/mpris2/player.py b/autoradio/mpris2/player.py index 9df8a7c..c95f786 100644 --- a/autoradio/mpris2/player.py +++ b/autoradio/mpris2/player.py @@ -6,15 +6,29 @@ from __future__ import print_function from __future__ import absolute_import -from autoradio.pydbusdecorator.dbus_attr import DbusAttr -from autoradio.pydbusdecorator.dbus_interface import DbusInterface -from autoradio.pydbusdecorator.dbus_method import DbusMethod -from autoradio.pydbusdecorator.dbus_signal import DbusSignal + +#insert projet at path +# not required if installed +#import sys +#sys.path = ["/home/pat1/git/autoradio"] + sys.path + + +from autoradio.dbusdecorator import DbusAttr +from autoradio.dbusdecorator import DbusInterface +from autoradio.dbusdecorator import DbusMethod +from autoradio.dbusdecorator import DbusSignal from .interfaces import Interfaces -from .types import Time_In_Us, Loop_Status, Playback_Status, \ -Playback_Rate, Metadata_Map, Volume +#from types import Time_In_Us, Loop_Status, Playback_Status, \ +# Playback_Rate, Metadata_Map, Volume + +from .time_in_us import Time_In_Us +from .loop_status import Loop_Status +from .playback_status import Playback_Status +from .playback_rate import Playback_Rate +from .metada_map import Metadata_Map +from .volume import Volume class Player(Interfaces): ''' @@ -439,7 +453,7 @@ def CanControl(self): pass if __name__ == '__main__': - from mpris2.utils import SomePlayers + from utils import SomePlayers #uri = Interfaces.MEDIA_PLAYER + '.' + SomePlayers.GMUSICBROWSER #mp2 = Player(dbus_interface_info={'dbus_uri': uri}) #print mp2.LoopStatus @@ -461,7 +475,7 @@ def another_handler(self, *args, **kw): #print mp2.Seeked #mp2.Seeked = my_handler #mp2.PropertiesChanged = another_handler - from mpris2.utils import get_session + from utils import get_session s = get_session() s.add_signal_receiver(another_handler, "PropertiesChanged", "org.freedesktop.DBus.Properties", path="/org/mpris/MediaPlayer2") mloop.run() diff --git a/autoradio/mpris2/playlists.py b/autoradio/mpris2/playlists.py index 5a7a0b8..cac416a 100644 --- a/autoradio/mpris2/playlists.py +++ b/autoradio/mpris2/playlists.py @@ -6,10 +6,10 @@ ''' from __future__ import print_function from __future__ import absolute_import -from autoradio.pydbusdecorator.dbus_attr import DbusAttr -from autoradio.pydbusdecorator.dbus_interface import DbusInterface -from autoradio.pydbusdecorator.dbus_method import DbusMethod -from autoradio.pydbusdecorator.dbus_signal import DbusSignal +from autoradio.dbusdecorator import DbusAttr +from autoradio.dbusdecorator import DbusInterface +from autoradio.dbusdecorator import DbusMethod +from autoradio.dbusdecorator import DbusSignal from .interfaces import Interfaces from .types import Playlist, Maybe_Playlist from dbus import UInt32 diff --git a/autoradio/mpris2/tracklist.py b/autoradio/mpris2/tracklist.py index 0ba6f94..e769dba 100644 --- a/autoradio/mpris2/tracklist.py +++ b/autoradio/mpris2/tracklist.py @@ -5,10 +5,10 @@ """ from __future__ import print_function from __future__ import absolute_import -from autoradio.pydbusdecorator.dbus_attr import DbusAttr -from autoradio.pydbusdecorator.dbus_interface import DbusInterface -from autoradio.pydbusdecorator.dbus_method import DbusMethod -from autoradio.pydbusdecorator.dbus_signal import DbusSignal +from autoradio.dbusdecorator import DbusAttr +from autoradio.dbusdecorator import DbusInterface +from autoradio.dbusdecorator import DbusMethod +from autoradio.dbusdecorator import DbusSignal from .interfaces import Interfaces from .types import Metadata_Map diff --git a/autoradio/mpris2/types.py b/autoradio/mpris2/types.py index 8e6820b..ac19524 100644 --- a/autoradio/mpris2/types.py +++ b/autoradio/mpris2/types.py @@ -29,4 +29,4 @@ print(Maybe_Playlist) print(Time_In_Us) print(Uri) - print(Volume) \ No newline at end of file + print(Volume) diff --git a/autoradio/mprisweb.py b/autoradio/mprisweb.py index dfbcd9a..5116734 100644 --- a/autoradio/mprisweb.py +++ b/autoradio/mprisweb.py @@ -25,6 +25,7 @@ from . import autompris2 cpversion3=cherrypy.__version__.startswith("3") +cpversion5=cherrypy.__version__.startswith("5") maxplele=100 # max number of elements in playlist port=8888 # server port @@ -122,8 +123,8 @@ def index(self): try: cpos=mp.get_playlist_pos() - if cpos is None: cpos=0 - cpos=int(cpos) + if cpos is None: cpos=0 + cpos=int(cpos) except: return "error get_playlist_pos()" @@ -169,15 +170,15 @@ def index(self): htmlresponse+='' except: - htmlresponse+='error getting player information' + htmlresponse+='error getting player information' htmlresponse+='
posizioneduratabrano
' - try: - if len > maxplele : - htmlresponse+="

ATTENTION: there are more file than you can see here.

" - except: - pass + try: + if len > maxplele : + htmlresponse+="

ATTENTION: there are more file than you can see here.

" + except: + pass if (self.iht) : htmlresponse+=tail @@ -217,7 +218,7 @@ def start_http_server(iht=False,player="AutoPlayer",session=0): # to objects, so we need to mount a request handler object here. A request # to '/' will be mapped to cherrypy.root.index(). - if (cpversion3): + if (cpversion3 or cpversion5): cherrypy.quickstart(HomePage(iht,player,session),config=settings) else: @@ -226,12 +227,11 @@ def start_http_server(iht=False,player="AutoPlayer",session=0): cherrypy.server.start() -if __name__ == '__main__': - +def main(): # Set the signal handler #import signal #signal.signal(signal.SIGINT, signal.SIG_IGN) - + # Start the CherryPy server. try: start_http_server(iht=True,player=autoradio_config.player,session=0) @@ -242,3 +242,9 @@ def start_http_server(iht=False,player="AutoPlayer",session=0): finally: print("Terminated") + + +if __name__ == '__main__': + + main() + diff --git a/autoradio/pydbusdecorator/__init__.py b/autoradio/pydbusdecorator/__init__.py deleted file mode 100644 index 02dcbec..0000000 --- a/autoradio/pydbusdecorator/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import absolute_import -from .dbus_decorator import DbusDecorator -from .dbus_interface import DbusInterface -from .dbus_attr import DbusAttr -from .dbus_method import DbusMethod -from .dbus_signal import DbusSignal -from .undefined_param import UndefinedParam - -if __name__ == '__main__': - pass \ No newline at end of file diff --git a/autoradio/pydbusdecorator/dbus_attr.py b/autoradio/pydbusdecorator/dbus_attr.py deleted file mode 100644 index 2ad785a..0000000 --- a/autoradio/pydbusdecorator/dbus_attr.py +++ /dev/null @@ -1,96 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import absolute_import -from .dbus_decorator import DbusDecorator -from .undefined_param import UNDEFINED_PARAM -from .dbus_interface import DbusInterface - - -class DbusAttr(DbusDecorator): - ''' - Wrap some method as attribute - - Works like @property, but for dbus - ''' - - def __init__(self, meth=None, iface=None, - produces=lambda resp: resp, - to_primitive=lambda resp: resp, - override_none_val=UNDEFINED_PARAM, - override_none_return=True, *args, **kw): - ''' - Instantiate one new DbusAttr decoreator - By default pass received val to method - @param meth: - function overrided - @param iface: - str dbus intercafe string with this property - @param produces: - callable, function or class with one param, that converts received data - @param to_primitive: - callable, function or class with one param, that converts data to send - @param override_none_val: - Set if override val to call decorated attr (method) with value of dbus attr response - Any value of val different than UNDEFINED_PARAM is not 'None' - @param override_none_return: - Set if override response of call decorated attr (method) with value of dbus attr response - ''' - super(DbusAttr, self).__init__(*args, **kw) - self.attr = meth - self.iface = iface - self.produces = produces - self.to_primitive = to_primitive - self.override_val = override_none_val - self.override_return = override_none_return - - def __call__(self, meth, *args, **kw): - self.attr = meth - return self - - def _get_set_dbus(self, obj, val=UNDEFINED_PARAM, *args, **kw): - properties = DbusInterface.get_bus_properties(obj) - iface = self.iface or DbusInterface.get_bus_iface(obj) - #vals is UndefinedParam, try to get val from object - if val is UNDEFINED_PARAM: - mval = properties.Get(iface, self.attr.__name__) - DbusInterface.store_result(obj, mval) - if self.override_val: - val = mval - #else set val in property (meth.__name__) - else: - to_primitve = self.to_primitive - properties.Set(iface, self.attr.__name__, val) - DbusInterface.store_result(obj, to_primitve(val)) - result = self.attr(val, *args, **kw) - if result is None and self.override_return: - result = properties.Get(iface, self.attr.__name__) - produces = self.produces - return produces(result) - - def __get__(self, obj, objtype=None): - if obj is None: - return self - return self._get_set_dbus(obj) - - def __set__(self, obj, value): - if obj: - self._get_set_dbus(obj, value) - else: - self.attr = value - - def __delete__(self, obj): - raise AttributeError("can't delete attribute") - - @property - def attr(self): - return self._attr - - @attr.setter - def attr(self, value): - self._attr = value - if hasattr(value, "__doc__"): - self.__doc__ = value.__doc__ - diff --git a/autoradio/pydbusdecorator/dbus_data.py b/autoradio/pydbusdecorator/dbus_data.py deleted file mode 100644 index 1ebfe75..0000000 --- a/autoradio/pydbusdecorator/dbus_data.py +++ /dev/null @@ -1,27 +0,0 @@ -#''' -#Created on Nov 5, 2011 -# -#@author: hugosenari -#''' -#from functools import wraps -#class DbusData(object): -# ''' -# Wrapps class as data -# ''' -# -# def __init__(self, *args, **kw): -# ''' -# Constructor -# ''' -# -# def __call__(self, meth, *args, **kw): -# ''' -# wrap function -# ''' -# @wraps(meth) -# def dbusWrapedData(*args, **kw): -# return meth(*args, **kw) -# return dbusWrapedData -# -# def __get__(self, obj, objtype=None): -# return obj if obj else self \ No newline at end of file diff --git a/autoradio/pydbusdecorator/dbus_decorator.py b/autoradio/pydbusdecorator/dbus_decorator.py deleted file mode 100644 index ed5ace3..0000000 --- a/autoradio/pydbusdecorator/dbus_decorator.py +++ /dev/null @@ -1,20 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' - -from builtins import object -import dbus - -class DbusDecorator(object): - ''' - Decorator root class - ''' - dbus_lib = dbus - - def __init__(self, *args, **kw): - ''' - Constructor - ''' - pass \ No newline at end of file diff --git a/autoradio/pydbusdecorator/dbus_interface.py b/autoradio/pydbusdecorator/dbus_interface.py deleted file mode 100644 index 82c0106..0000000 --- a/autoradio/pydbusdecorator/dbus_interface.py +++ /dev/null @@ -1,347 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import absolute_import - -from builtins import object -from .dbus_decorator import DbusDecorator -from .undefined_param import UNDEFINED_PARAM -from functools import wraps - - -class DBUS_INJECTED_ATTRS(object): - #defalt var names in object - dbus_interface_info_at = 'dbus_interface_info' - #default keywords params for decorated class constructor - iface_at = 'dbus_iface' - path_at = 'dbus_path' - uri_at = 'dbus_uri' - obj_at = 'dbus_object' - session_at = 'dbus_session' - last_fn_return_at = 'last_fn_return' - on_change_at = 'on_change' - prop_iface_at ='dbus_prop_iface' - - -class DBUS_DEFAULT_ATTRS(object): - #default values - iface = None - path = None - uri = None - obj = None - session = None - retur = None - on_change = None - prop_iface = "org.freedesktop.DBus.Properties" - dbus_interface_info = None - - -class DbusInterfaceInfo(DbusDecorator): - ''' Object with this lib vars ''' - - def __init__(self, - #default values - dbus_iface=DBUS_DEFAULT_ATTRS.iface, - dbus_path=DBUS_DEFAULT_ATTRS.path, - dbus_uri=DBUS_DEFAULT_ATTRS.uri, - dbus_object=DBUS_DEFAULT_ATTRS.obj, - dbus_session=DBUS_DEFAULT_ATTRS.session, - last_fn_return=DBUS_DEFAULT_ATTRS.retur, - on_change=DBUS_DEFAULT_ATTRS.on_change, - dbus_prop_iface=DBUS_DEFAULT_ATTRS.iface, - *args, **kw): - ''' Constructor ''' - - self.dbus_interfaces = {} - self.dbus_obj = dbus_object - self.dbus_obj_uri = dbus_uri - self.dbus_path = dbus_path - self.dbus_session = dbus_session - self.dbus_iface = dbus_iface - self.dbus_prop_iface = dbus_prop_iface - self.last_return = last_fn_return - self.on_change = on_change - - -class DbusInterface(DbusDecorator): - ''' Wraps some class that define dbus interface ''' - - #constructor of decorator - def __init__(self, - #default values - iface=DBUS_DEFAULT_ATTRS.iface, - path=DBUS_DEFAULT_ATTRS.path, - uri=DBUS_DEFAULT_ATTRS.uri, - obj=DBUS_DEFAULT_ATTRS.obj, - session=DBUS_DEFAULT_ATTRS.session, - retur=DBUS_DEFAULT_ATTRS.retur, - on_change=DBUS_DEFAULT_ATTRS.on_change, - prop_iface=DBUS_DEFAULT_ATTRS.prop_iface, - dbus_interface_info=DBUS_DEFAULT_ATTRS.dbus_interface_info, - #defalt attr name in object - dbus_interface_info_at=DBUS_INJECTED_ATTRS.dbus_interface_info_at, - *args, **kw): - ''' Init this decorator - @param iface: str dbus object interface - @param path: str dbus object path - @param uri: str dbus object uri (org.mpris.MediaPlayer2.banshee) - @param obj: dbus.proxies.ProxyObject - @param session: dbus dbus.SessionBus.get_session() - @param retur: object, last function return - @param on_change: callable, reserved key but not in use - @param prop_iface: str dbus object default interface for properties - @param dbus_interface_info: DbusInterfaceInfo, object with DbusInterface infos - @param dbus_interface_info_at: str where store DbusInterface properties in this obj - - @see: mpris2.mediaplayer2 to see some examples - ''' - super(DbusInterface, self).__init__(*args, **kw) - - self._dbus_default_attrs = { - 'dbus_iface' : iface, - 'dbus_path' : path, - 'dbus_uri' : uri, - 'dbus_object' : obj, - 'dbus_session' : session, - 'last_fn_return' : retur, - 'on_change' : on_change, - 'dbus_prop_iface' : prop_iface, - 'dbus_interface_info' : dbus_interface_info - } - self._dbus_default_keys = {} - - self._dbus_interface_info_at = dbus_interface_info_at - self._dbus_interface_info = dbus_interface_info - self._meth = None - - #constructor of decorated class - def __call__(self, meth, *args, **kw): - ''' Called when any decorated class is loaded''' - self._meth = meth - - @wraps(meth) - def dbusWrapedInterface(*args, **kw): - return self.dbusWrapedInterface(*args, **kw) - - return dbusWrapedInterface - - def dbusWrapedInterface(self, *args, **kw): - ''' Called when some decoreted class was called - Inject attrs from decorator at new object then return object - - @param *args: list of args to call constructor - @param **kw: dict of keywords, can redefine class default parameters - @return: instance of decoreted class, with new attributes - @see: mpris2.mediaplayer2 to see some examples - ''' - #shift dbus interface info from keywords - kw = self.remove_interface_info_from_kw(**kw) - #call decorated class constructor - new_obj = self._meth(*args, **kw) - if new_obj: - self.inject_interface_info(new_obj) - elif len(args) > 0: - self.inject_interface_info(args[0]) - #inject dbus interface info - - return new_obj - - def remove_interface_info_from_kw(self, **kw): - ''' Remove dbus interface info from keyords and set it in _dbus_interface_info ''' - constructor_keys = {} #dict to create new DbusInterfaceInfo - dbus_info_at = DBUS_INJECTED_ATTRS.dbus_interface_info_at - attr_keys = (DBUS_INJECTED_ATTRS.dbus_interface_info_at, - DBUS_INJECTED_ATTRS.iface_at, - DBUS_INJECTED_ATTRS.path_at, - DBUS_INJECTED_ATTRS.uri_at, - DBUS_INJECTED_ATTRS.obj_at, - DBUS_INJECTED_ATTRS.session_at, - DBUS_INJECTED_ATTRS.last_fn_return_at, - DBUS_INJECTED_ATTRS.on_change_at, - DBUS_INJECTED_ATTRS.prop_iface_at) - keys_for_keys = {DBUS_INJECTED_ATTRS.dbus_interface_info_at : 'dbus_interface_info', - DBUS_INJECTED_ATTRS.iface_at : 'dbus_iface', - DBUS_INJECTED_ATTRS.path_at : 'dbus_path', - DBUS_INJECTED_ATTRS.uri_at : 'dbus_uri', - DBUS_INJECTED_ATTRS.obj_at : 'dbus_object', - DBUS_INJECTED_ATTRS.session_at : 'dbus_session', - DBUS_INJECTED_ATTRS.last_fn_return_at : 'last_fn_return', - DBUS_INJECTED_ATTRS.on_change_at : 'on_change', - DBUS_INJECTED_ATTRS.prop_iface_at : 'dbus_prop_iface' - } - self._dbus_default_keys = keys_for_keys # 'from to' for kw and constructor_keys - has_same_key_in_kw = False # infor if this constructor changes dbus_interface_info - not_user_interface_info = True # inform if this constructor NOT pass dbus_interface_info param - #remove dbus interface info keyword from kw for constructor - dbus_interface_info = kw.get(dbus_info_at) - if dbus_interface_info: - del kw[dbus_info_at] - for key in attr_keys: - default_val = self._dbus_default_attrs.get(key) - if dbus_interface_info and key in dbus_interface_info and dbus_interface_info[key] is not default_val: - has_same_key_in_kw = True - constructor_keys[keys_for_keys[key]] = dbus_interface_info[key] - else: - constructor_keys[keys_for_keys[key]] = self._dbus_default_attrs.get(key) - - #kw has dbus_interface_info param? - if not_user_interface_info: - #kw has info that diff from class definition? - #or we not had dbus_interface_info? - if has_same_key_in_kw \ - or not self._dbus_interface_info: - self._dbus_interface_info = DbusInterfaceInfo(**constructor_keys) - - return kw - - def inject_interface_info(self, new_obj): - #set dbus_interface_info as attr in new_obj - setattr(new_obj, - DBUS_INJECTED_ATTRS.dbus_interface_info_at, - self._dbus_interface_info) - - #core info getter - @staticmethod - def attr_name_at(at, attr_id=DBUS_INJECTED_ATTRS.dbus_interface_info_at, - val=UNDEFINED_PARAM): - ''' gets/sets objs attributes - @param at: object where get/set - @param attr_id: str internal name of attribute - @param val: object, new value - @return: attribute value or val - ''' - #return None if at, attr_id - if not (at and - attr_id and - #And if at has attr attr_id - hasattr(at, attr_id)): - return None - if UNDEFINED_PARAM == val: - setattr(at, attr_id, val) - return getattr(at, attr_id) - - @staticmethod - def get_dbus_interface_info(at): - ''' Use to get dbus_interface_info in object - @param at: object where get dbus_interface_info - @return session object - ''' - return DbusInterface.attr_name_at(at, DBUS_INJECTED_ATTRS.dbus_interface_info_at) - - #simple info getters - @staticmethod - def get_path(at): - ''' return dbus object path attribute - @param at: object where get this path - @return: str object dbus path - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - return dbus_interface_info.dbus_path - - @staticmethod - def get_uri(at): - ''' return dbus object uri attribute - @param at: object where get this uri - @return: str object dbus uri - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - return dbus_interface_info.dbus_obj_uri - - @staticmethod - def get_bus_iface(at): - ''' return dbus_iface str of 'at' - @param at: object where get this dbus object - @return: str of dbus interface - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - return dbus_interface_info.dbus_iface - - @staticmethod - def get_bus_prop_iface(at): - ''' return bus_prop_iface str of 'at' - @param at: object where get this dbus object - @return: str of dbus interface for properties - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - return dbus_interface_info.dbus_prop_iface \ - or DbusInterface.get_bus_iface(at) - - #complex info getter - @staticmethod - def get_session(at): - ''' Use to get dbus_session in object - @param at: object where get session previously criated - @return session object - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - dbus_session = dbus_interface_info.dbus_session - if not dbus_session: - dbus_session = DbusInterface.dbus_lib.SessionBus.get_session() - dbus_interface_info.dbus_session = dbus_session - return dbus_session - - @staticmethod - def get_bus_obj(at): - ''' return dbus object - @param at: object where get this dbus object - @return: dbus proxy object - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - obj = dbus_interface_info.dbus_obj - if not obj: - uri = DbusInterface.get_uri(at) - if uri: - path = DbusInterface.get_path(at) - if path: - session = DbusInterface.get_session(at) - obj = session.get_object(uri, path) - dbus_interface_info.dbus_obj = obj - return obj - - @staticmethod - def get_bus_properties(at, iface=None): - ''' return bus propeterty proxy for 'at' - @param at: object where get this dbus object - @param iface: str for property dbus interfacece (dbus properties by default) - @return: dbus proxy object of iface - ''' - return DbusInterface.iface(at, iface) - - #utilities - @staticmethod - def iface(at, dbus_str_iface=None, dbus_obj=None): - ''' Get iface from dict or create one and append it''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - dbus_str_iface = dbus_str_iface \ - or dbus_interface_info.dbus_prop_iface - result = dbus_interface_info.dbus_interfaces.get(dbus_str_iface) - if not result: - result = DbusInterface.dbus_lib.Interface( - dbus_obj or DbusInterface.get_bus_obj(at), - dbus_str_iface) - dbus_interface_info.dbus_interfaces[dbus_str_iface] = result - return result - - @staticmethod - def store_result(at, val=UNDEFINED_PARAM): - ''' use to set last call result - @param at: object where set - @param val: object to set - @return: val - ''' - dbus_interface_info = DbusInterface.get_dbus_interface_info(at) - if dbus_interface_info: - if val is UNDEFINED_PARAM: - dbus_interface_info.last_return = val - else: - val = dbus_interface_info.last_return - return val diff --git a/autoradio/pydbusdecorator/dbus_method.py b/autoradio/pydbusdecorator/dbus_method.py deleted file mode 100644 index 0ef8315..0000000 --- a/autoradio/pydbusdecorator/dbus_method.py +++ /dev/null @@ -1,141 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import absolute_import - -from builtins import range -from .dbus_decorator import DbusDecorator -from .dbus_interface import DbusInterface - -from functools import wraps - - -def kw_to_dbus(**kw): - return kw - -def args_to_dbus(*args): - return args - -class DbusMethod(DbusDecorator): - ''' - Wrapps some method calling dbus method - ''' - DbusMethodId = 0 - - def __init__(self, meth=None, - iface=None, - produces=None, - args_to_dbus=args_to_dbus, - kw_to_dbus=kw_to_dbus, - override_none_return = True, - *args, **kw): - ''' - Wrapps some method calling dbus method - @param meth: - method to be wrapped - @param produces: - callable to convert dbus response into other type: produces(dbus_returned) - if is not callable but iterable try convert params calling list item in same order - @param args_to_dbus: - callable to convert function params into dbus typee: args_to_dbus([array of args]) - if is not callable but dict try convert params calling dicts item whith the same keyword - @param kw_to_dbus: - callable to convert function params (received as keywords dict) into dbus types: kw_to_dbus({dict of keywords}) - @param override_none_return: - Set if override response of call decorated attr (method) with value of dbus attr response - ''' - self.uniq = DbusMethod.DbusMethodId - DbusMethod.DbusMethodId = self.uniq + 1 - super(DbusMethod, self).__init__(*args, **kw) - self.meth = meth - self.iface = iface - self.obj = None - self.produces = produces - self.args_to_dbus = args_to_dbus - self.kw_to_dbus = kw_to_dbus - self.override_return = True - - def _call_dbus(self, obj, *args, **kw): -# print self.meth.__name__, args, kw - bus_obj = DbusInterface.get_bus_obj(obj) - bus_interface = self.iface if self.iface else\ - DbusInterface.get_bus_iface(obj) - bus_meth = bus_obj.get_dbus_method(self.meth.__name__, bus_interface) - args = self.convert_args_to_dbus_args(*args) - kw = self.convert_kw_to_dbus_kw(**kw) - dbus_result = bus_meth(*args, **kw) - DbusInterface.store_result(obj, dbus_result) - produces = self.produces - if produces: - return produces(dbus_result) - meth = self.meth - result = None - if meth: - result = meth(obj, *args, **kw) - if result is None and self.override_return: - result = dbus_result - return result - - def __call__(self, _meth=None, *args, **kw): - meth = _meth or self.meth - if self.meth and self.obj: - if _meth: - largs = list(args) - largs.insert(0, meth) - args = tuple(largs) - return self._call_dbus(self.obj, *args, **kw) - else: - self.meth = meth - @wraps(self.meth) - def dbusWrapedMethod(obj, *args, **kw): - return self._call_dbus(obj, *args, **kw) - return dbusWrapedMethod - - def __get__(self, obj=None, *args, **kw): - if obj is None: - return self - self.obj = obj - return self.__call__ - - def convert_args_to_dbus_args(self, *args): - args_to_dbus = self.args_to_dbus - if callable(args_to_dbus): - return args_to_dbus(*args) - - result = [] - #iterate over args - for i in range(len(args)): - arg = args[i] - if i < len(args_to_dbus): - make = args_to_dbus[i] - if callable(make): - arg = make(arg) - result.append(arg) - return tuple(result) - - def convert_kw_to_dbus_kw(self, **kw): - kw_to_dbus = self.kw_to_dbus - if callable(kw_to_dbus): - return kw_to_dbus(**kw) - - if hasattr(self.kw_to_dbus, 'keys'): - to_dbus_keys = list(kw_to_dbus.keys()) - for key in list(kw.keys()): - if key in to_dbus_keys: - kw[key] = kw_to_dbus[key](kw[key]) - return kw - - @property - def meth(self): - return self._meth - - @meth.setter - def meth(self, value): - self._meth = value - if hasattr(value, "__doc__"): - self.__doc__ = value.__doc__ - - - diff --git a/autoradio/pydbusdecorator/dbus_signal.py b/autoradio/pydbusdecorator/dbus_signal.py deleted file mode 100644 index d2f619d..0000000 --- a/autoradio/pydbusdecorator/dbus_signal.py +++ /dev/null @@ -1,87 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import absolute_import - -from .dbus_decorator import DbusDecorator -from .dbus_interface import DbusInterface - -from functools import wraps - -class DbusSignal(DbusDecorator): - ''' - Wrapps some method as attribute - ''' - - - def __init__(self, meth=None, iface=None, *args, **kw): - ''' - @param meth: function, wrapped - ''' - super(DbusSignal, self).__init__(*args, **kw) - self.meth = meth - self.iface = iface - self._obj = None - self._handler = meth - - def _watch_dbus(self, obj, *args, **kw): - ''' - set self._handler to be called when obj fire signal wrapped - ''' - def handler(*args, **kw): - if self.meth is not self._handler: - DbusInterface.store_result(obj, self.meth(obj, *args, **kw)) - return self._handler(self._obj, *args, **kw) - if self.iface: - bus_iface = DbusInterface.iface(obj, self.iface) - bus_iface.connect_to_signal(self.meth.__name__, - handler, - dbus_interface=self.iface, - *args, **kw) - else: - bus_obj = DbusInterface.get_bus_obj(obj) - bus_obj.connect_to_signal(self.meth.__name__, - handler, - dbus_interface=DbusInterface.get_bus_iface(obj), - *args, **kw) - - def _remove_watch_dbus(self, obj): - pass - - def __call__(self, __call__meth=None, *args, **kw): - if self.meth and self._obj: - if __call__meth: - largs = list(args) - largs.insert(0, __call__meth) - args = tuple(largs) - return self._watch_dbus(self._obj, *args, **kw) - else: - self.meth = __call__meth - self._handler = __call__meth - @wraps(self.meth) - def dbusWrapedMethod(obj, *args, **kw): - return self._watch_dbus(obj, *args, **kw) - return self - - def __get__(self, obj, objtype=None): - if obj is None: - return self - self._obj = obj - return self._handler - - def __set__(self, obj, handler, *args, **kw): - self._obj = obj - self._handler = handler - self._watch_dbus(obj, *args, **kw) - - @property - def meth(self): - return self._meth - - @meth.setter - def meth(self, value): - self._meth = value - if hasattr(value, "__doc__"): - self.__doc__ = value.__doc__ diff --git a/autoradio/pydbusdecorator/undefined_param.py b/autoradio/pydbusdecorator/undefined_param.py deleted file mode 100644 index 4598b51..0000000 --- a/autoradio/pydbusdecorator/undefined_param.py +++ /dev/null @@ -1,27 +0,0 @@ -''' -Created on Nov 5, 2011 - -@author: hugosenari -''' -from __future__ import print_function - -from builtins import object -class Undefined(object): - '''Undefined''' - def __nonzero__(self=None): - return False - - def __repr__(self=None): - return "Undefined" - -class UndefinedParam(Undefined): - ''' UndefinedParam ''' - - def __cmp__(self, other): - return isinstance(other, Undefined) - -UNDEFINED = Undefined() -UNDEFINED_PARAM = UndefinedParam() - -if __name__ == "__main__": - print("True" if bool(UNDEFINED_PARAM) else "False") \ No newline at end of file From ae14a09fdd2f07e3a2383a75667dcb8b9db91fb0 Mon Sep 17 00:00:00 2001 From: pat1 Date: Mon, 23 Jul 2018 16:17:38 +0200 Subject: [PATCH 5/8] ready for release 3.0 --- autoradio/__init__.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/autoradio/__init__.py b/autoradio/__init__.py index 0805516..61b166e 100644 --- a/autoradio/__init__.py +++ b/autoradio/__init__.py @@ -1 +1 @@ -_version_="2.8.10" +_version_="3.0" diff --git a/setup.py b/setup.py index 4219750..a298440 100644 --- a/setup.py +++ b/setup.py @@ -314,7 +314,7 @@ def run(self): 'autoradio.jingles.migrations', 'autoradio.programs.migrations', 'autoradio.player', 'autoradio.doc', 'autoradio.autoplayer', 'autoradio.mpris2', - 'autoradio.pydbusdecorator'], + 'autoradio.dbusdecorator'], package_data={ 'autoradio.doc': ['templates/doc/*'], 'autoradio.programs': ['fixtures/*.json', From f94ff18db5e997f02578a11b7e12a558434a7a30 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 30 Aug 2018 15:33:51 +0200 Subject: [PATCH 6/8] bug on debian install (default locale) and python3 refinements --- autoradio-site.cfg | 2 +- autoradio.cfg | 2 +- autoradio/__init__.py | 2 +- autoradio/daemon.py | 8 ++++---- autoradiod | 7 +++++-- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/autoradio-site.cfg b/autoradio-site.cfg index f405fde..7385d1f 100644 --- a/autoradio-site.cfg +++ b/autoradio-site.cfg @@ -22,7 +22,7 @@ minelab=180 # to adjust the programming you have to make changes minsched minutes before minsched=5 -locale="it_IT.UTF-8" +locale="C.UTF-8" user = autoradio group = autoradio diff --git a/autoradio.cfg b/autoradio.cfg index 05b0d36..70a1693 100644 --- a/autoradio.cfg +++ b/autoradio.cfg @@ -22,7 +22,7 @@ minelab=180 # to adjust the programming you have to make changes minsched minutes before minsched=5 -locale="it_IT.UTF-8" +locale="C.UTF-8" #user = pat1 #group = pat1 diff --git a/autoradio/__init__.py b/autoradio/__init__.py index 61b166e..3935908 100644 --- a/autoradio/__init__.py +++ b/autoradio/__init__.py @@ -1 +1 @@ -_version_="3.0" +_version_="3.1" diff --git a/autoradio/daemon.py b/autoradio/daemon.py index 07b0a1e..612d567 100644 --- a/autoradio/daemon.py +++ b/autoradio/daemon.py @@ -135,8 +135,8 @@ def openstreams(self): in the constructor. """ si = open(self.options.stdin, "r") - so = open(self.options.stdout, "a+") - se = open(self.options.stderr, "a+", 0) + so = open(self.options.stdout, "ab+") + se = open(self.options.stderr, "ab+", 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) @@ -267,7 +267,7 @@ def start(self): # Write pid file (will belong to the new user) if self.options.pidfile is not None: - open(self.options.pidfile, "wb").write(str(os.getpid())) + open(self.options.pidfile, "w").write(str(os.getpid())) # Reopen file descriptors on SIGHUP signal.signal(signal.SIGHUP, self.handlesighup) @@ -283,7 +283,7 @@ def stop(self): if self.options.pidfile is None: sys.exit("no pidfile specified") try: - pidfile = open(self.options.pidfile, "rb") + pidfile = open(self.options.pidfile, "r") except IOError as exc: sys.exit("can't open pidfile %s: %s" % (self.options.pidfile, str(exc))) data = pidfile.read() diff --git a/autoradiod b/autoradiod index e399b65..7119da7 100755 --- a/autoradiod +++ b/autoradiod @@ -45,7 +45,10 @@ def main(): import logging,os,sys,errno,signal,logging.handlers import subprocess - import thread + try: + import thread + except: + import _thread as thread import datetime import time as timesleep #from threading import * @@ -150,7 +153,7 @@ def main(): type=schedule.type emission_done=schedule.emission_done - if ( emission_done <> None ): + if ( emission_done != None ): if ( type == "program" ): #la trasmissione ha una schedula con un'unica emissione prevista logging.debug( " %s %s %s schedula already done; ignore it !",type,scheduledatetime,emission_done) From 805525311090ee425d18974a67e9c6ed1d082b62 Mon Sep 17 00:00:00 2001 From: Paolo Patruno Date: Mon, 21 Oct 2019 23:50:34 +0200 Subject: [PATCH 7/8] migrate to django 2.2 and python3 bugs --- autoradio/autoradio_core.py | 169 +++++++++++------- autoradio/gest_jingle.py | 5 +- autoradio/gest_playlist.py | 4 +- autoradio/jingles/models.py | 6 +- autoradio/managempris.py | 6 +- autoradio/playlists/models.py | 14 +- autoradio/programs/models.py | 55 +++--- .../programs/templates/schedule/index.html | 37 ++-- autoradio/programs/views.py | 15 +- autoradio/programs/widgets.py | 4 +- autoradio/settings.py | 3 +- autoradio/spots/models.py | 10 +- autoradio/urls.py | 2 +- autoradioctrl | 3 +- autoradiod | 3 +- autoradiodbusd | 2 +- 16 files changed, 197 insertions(+), 141 deletions(-) diff --git a/autoradio/autoradio_core.py b/autoradio/autoradio_core.py index 8e578f4..9573881 100644 --- a/autoradio/autoradio_core.py +++ b/autoradio/autoradio_core.py @@ -38,9 +38,9 @@ def __init__ (self,djobj,scheduledatetime,media,filename,length=None,type=None,e """ init of schedule object: """ - self.djobj=djobj + self.mydjobj=djobj self.scheduledatetime=scheduledatetime - self.media=media + self.mymedia=media self.filename=filename #self.mediaweb = self.media[len(settings.MEDIA_URL)+1:] self.length=length @@ -48,30 +48,32 @@ def __init__ (self,djobj,scheduledatetime,media,filename,length=None,type=None,e self.emission_done=emission_done self.shuffle=shuffle self.maxlength=maxlength - self.title=title + self.mytitle=title - def __cmp__ (self, b): - if self.scheduledatetime is None and b.scheduledatetime is None : - return 0 - - if self.scheduledatetime is None : - return -1 - - if b.scheduledatetime is None : - return 1 - + def __eq__(self, other): + if (self.scheduledatetime is None and other.scheduledatetime is None + or self.scheduledatetime == other.scheduledatetime) : + return True - if self.scheduledatetime == b.scheduledatetime : - return 0 - elif self.scheduledatetime < b.scheduledatetime : - return -1 - elif self.scheduledatetime > b.scheduledatetime : - return 1 + def __ne__(self, other): + return not self.__eq__(self, other) + + def __lt__(self, other): + return self.scheduledatetime < other.scheduledatetime + + def __le__(self, other): + return self.scheduledatetime <= other.scheduledatetime + + def __gt__(self, other): + return self.scheduledatetime > other.scheduledatetime + + def __ge__(self, other): + return self.scheduledatetime >= other.scheduledatetime + def future (self,now=None): - self.future=self.scheduledatetime > now - return self.future + return self.scheduledatetime > now def filter (self): @@ -80,31 +82,64 @@ def filter (self): return True - def __str__ (self): - - return self.type+" "+self.media - - - def __iter__(self,now=None): - ''' - return a list nome,datet,media,len,tipo,datetdone,future - ''' - - if now is None : now=datetime.now() - - #return iter((self.djobj,self.scheduledatetime,self.media,self.length,self.type,\ - # self.emission_done,self.shuffle,self.future(now))) - - yield self.djobj - yield self.title - yield self.scheduledatetime - yield self.media - yield str((datetime(2000,1,1)+timedelta(seconds=int(self.length))).time()) - yield self.type - yield self.emission_done - yield self.future(now) - + def __repr__ (self): + + return self.type+" "+self.mymedia + + +# def __iter__(self,now=None): +# self.index=0 +# self.now=now +# if self.now is None : self.now=datetime.now() +# return self +# +# def __next__(self): +# self.index+=1 +# if (self.index==1): +# return self.mydjobj +# if (self.index==2): +# return self.mytitle +# if (self.index==3): +# return self.scheduledatetime +# if (self.index==4): +# return self.mymedia +# if (self.index==5): +# return str((datetime(2000,1,1)+timedelta(seconds=int(self.length))).time()) +# if (self.index==6): +# return self.type +# if (self.index==7): +# return self.emission_done +# if (self.index==8): +# return self.future(self.now) +# raise StopIteration + + def get_djobj(self): + return self.mydjobj + def get_title(self): + return self.mytitle + def get_datet(self): + return self.scheduledatetime + def get_media(self): + return self.mymedia + def get_length_s(self): + return str((datetime(2000,1,1)+timedelta(seconds=int(self.length))).time()) + def get_tipo(self): + return self.type + def get_datetdone(self): + return self.emission_done + def get_isfuture(self): + return self.future(datetime.now()) + + djobj=property(get_djobj) + title=property(get_title) + datet=property(get_datet) + media=property(get_media) + length_s=property(get_length_s) + tipo=property(get_tipo) + datetdone=property(get_datetdone) + isfuture=property(get_isfuture) + class schedules(list): """ multiple schedule object @@ -393,7 +428,7 @@ def get_all(self,now=None,genfile=True): emission_done,title=str(jingle))) - return self + #return self def get_all_refine(self,now=None,genfile=True): @@ -404,8 +439,8 @@ def get_all_refine(self,now=None,genfile=True): pass self.purge() self.sort() - - return self + + #return self @@ -475,22 +510,33 @@ def __str__ (self): str(self.datetime_end)+" "+str(self.type)+" "+\ str(self.subtype)+" "+str(self.production)+" "+str(self.note) - + def __iter__(self): ''' return a list ''' + self.index=0 + return self - yield self.title - yield self.datetime_start - yield self.datetime_end - yield self.code - yield self.type - yield self.subtype - yield self.production - yield self.note - - + def __next__(self): + self.index+=1 + if (self.index==1): + return self.title + if (self.index==2): + return self.datetime_start + if (self.index==3): + return self.datetime_end + if (self.index==4): + return self.code + if (self.index==5): + return self.type + if (self.index==6): + return self.subtype + if (self.index==7): + return self.production + if (self.index==8): + return self.note + raise StopIteration class dates(object): @@ -513,6 +559,7 @@ def __next__(self): return self.datetime_start else: raise StopIteration + #return class palimpsests(list): @@ -550,9 +597,9 @@ def get_palimpsest(self,datetime_start,datetime_end): self.sort() - #print "prima:" + #print ("prima:") #for program in self: - # print program + # print (program) # timing adjust: # 1) overlay diff --git a/autoradio/gest_jingle.py b/autoradio/gest_jingle.py index 445b762..a228c1a 100644 --- a/autoradio/gest_jingle.py +++ b/autoradio/gest_jingle.py @@ -127,7 +127,10 @@ def get_jingle(self): # for datac in time_iterator(self.datesched_min,self.datesched_max,self.emission_freq): for datac in time_iterator(self.now,self.datesched_max,self.emission_freq): - jingle=next(many_jingles) + try: + jingle=next(many_jingles) + except StopIteration: + return jingle.ar_filename=jingle.file.path.encode("utf8") jingle.ar_url=jingle.file.url # jingle.ar_filename=jingle.get_file_filename() diff --git a/autoradio/gest_playlist.py b/autoradio/gest_playlist.py index 85d4e47..6a6ae21 100644 --- a/autoradio/gest_playlist.py +++ b/autoradio/gest_playlist.py @@ -84,8 +84,8 @@ def __init__ (self,now,minelab): # warning here we are around midnight logging.debug("PLAYLIST: around midnight") - ieri=str(calendar.day_name[self.datesched_min.weekday()], 'utf-8') - domani=str(calendar.day_name[self.datesched_max.weekday()], 'utf-8') + ieri=str(calendar.day_name[self.datesched_min.weekday()]) + domani=str(calendar.day_name[self.datesched_max.weekday()]) self.periodicschedule=PeriodicSchedule.objects.filter \ (Q(start_date__lte=self.oggi) | Q(start_date__isnull=True),\ diff --git a/autoradio/jingles/models.py b/autoradio/jingles/models.py index 3624e42..69acf61 100644 --- a/autoradio/jingles/models.py +++ b/autoradio/jingles/models.py @@ -55,7 +55,7 @@ class Giorno(models.Model): name = models.CharField(max_length=20,choices=giorno_giorno(),unique=True,\ help_text=ugettext_lazy("weekday name")) - def __unicode__(self): + def __str__(self): return self.name class Admin(object): @@ -69,7 +69,7 @@ class Configure(models.Model): emission_freq = models.TimeField(ugettext_lazy('Frequency')) - def __unicode__(self): + def __str__(self): return self.sezione+" "+self.active.__str__()+" "+self.emission_freq.isoformat() class Admin(object): @@ -105,7 +105,7 @@ def was_recorded_today(self): was_recorded_today.short_description = ugettext_lazy('Recorded today?') - def __unicode__(self): + def __str__(self): return self.jingle class Admin(object): diff --git a/autoradio/managempris.py b/autoradio/managempris.py index ae699d2..33225cb 100644 --- a/autoradio/managempris.py +++ b/autoradio/managempris.py @@ -14,7 +14,7 @@ from threading import * import os from . import autoradio_config - +import traceback os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.conf import settings @@ -140,7 +140,7 @@ def ManagePlayer (player,session,schedule): raise PlayerError("Managempris: ERROR in xmms.control.get_playlist_posauto") logging.info( "ManageXmms: insert media: %s at position %d",media,pos) - aud.playlist_add_atpos("file://"+media,pos) + aud.playlist_add_atpos("file://"+media.decode("utf-8"),pos) # recheck for consistency newpos=aud.get_playlist_pos() @@ -173,7 +173,7 @@ def ManagePlayer (player,session,schedule): except: logging.error("generic error in ManagePlayer") - + traceback.print_exc() return diff --git a/autoradio/playlists/models.py b/autoradio/playlists/models.py index 1b20162..b9f00b6 100644 --- a/autoradio/playlists/models.py +++ b/autoradio/playlists/models.py @@ -55,7 +55,7 @@ class Giorno(models.Model): name = models.CharField(max_length=20,choices=giorno_giorno(),unique=True,\ help_text=ugettext_lazy("weekday name")) - def __unicode__(self): + def __str__(self): return self.name class Configure(models.Model): @@ -70,7 +70,7 @@ class Configure(models.Model): help_text=ugettext_lazy("The end time the playlist will be active")) - def __unicode__(self): + def __str__(self): if self.emission_starttime is None: start="-" else: @@ -99,7 +99,7 @@ def was_recorded_today(self): was_recorded_today.short_description = ugettext_lazy('Generated today?') - def __unicode__(self): + def __str__(self): #return self.playlist+" "+self.rec_date.isoformat()+" "+self.active.__str__() return self.playlist @@ -109,7 +109,7 @@ class Schedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) playlist = models.ForeignKey(Playlist, verbose_name=\ - ugettext_lazy('refer to playlist:')) + ugettext_lazy('refer to playlist:'), on_delete=models.CASCADE) shuffle = models.BooleanField(ugettext_lazy("Shuffle Playlist on start"),default=True,\ help_text=ugettext_lazy("Every time the playlist will be scheduled it's order will be randomly changed")) @@ -140,7 +140,7 @@ def file(self): return self.playlist.playlist file.short_description = ugettext_lazy('Linked Playlist') - def __unicode__(self): + def __str__(self): return str(self.playlist) class PeriodicSchedule(models.Model): @@ -149,7 +149,7 @@ class PeriodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) playlist = models.ForeignKey(Playlist,verbose_name=\ - ugettext_lazy('refer to playlist:')) + ugettext_lazy('refer to playlist:'), on_delete=models.CASCADE) shuffle = models.BooleanField(ugettext_lazy("Shuffle Playlist on start"),default=True,\ help_text=ugettext_lazy("Every time the playlist will be scheduled it's order will be randomly changed")) @@ -174,6 +174,6 @@ def file(self): return self.playlist.playlist file.short_description = ugettext_lazy('Linked Playlist') - def __unicode__(self): + def __str__(self): return str(self.playlist) diff --git a/autoradio/programs/models.py b/autoradio/programs/models.py index 5db4194..708fe9f 100644 --- a/autoradio/programs/models.py +++ b/autoradio/programs/models.py @@ -5,10 +5,7 @@ from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy - -from django.db.models import permalink from autoradio.programs.managers import EpisodeManager - import datetime import calendar from django.db.models import Q @@ -101,7 +98,7 @@ class Meta(object): verbose_name = 'category (Media RSS)' verbose_name_plural = 'categories (Media RSS)' - def __unicode__(self): + def __str__(self): return u'%s' % (self.name) @@ -133,7 +130,7 @@ class Meta(object): verbose_name = 'category (iTunes parent)' verbose_name_plural = 'categories (iTunes parent)' - def __unicode__(self): + def __str__(self): return u'%s' % (self.name) @@ -226,7 +223,7 @@ class ChildCategory(models.Model): ) ), ) - parent = models.ForeignKey(ParentCategory, related_name='child_category_parents') + parent = models.ForeignKey(ParentCategory, related_name='child_category_parents', on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, choices=CHILD_CHOICES, help_text=ugettext_lazy('Please choose a child category that corresponds to its respective parent category (e.g., "Design" is a child category of "Arts").
If no such child category exists for a parent category (e.g., Comedy, Kids & Family, Music, News & Politics, or TV & Film), simply leave this blank and save.')) slug = models.SlugField(blank=True, unique=False, help_text=ugettext_lazy('A slug is a URL-friendly nickname. For exmaple, a slug for "Fashion & Beauty" is "fashion-beauty".')) @@ -235,7 +232,7 @@ class Meta(object): verbose_name = 'category (iTunes child)' verbose_name_plural = 'categories (iTunes child)' - def __unicode__(self): + def __str__(self): if self.name!='': return u'%s > %s' % (self.parent, self.name) else: @@ -254,7 +251,7 @@ class Giorno(models.Model): name = models.CharField(max_length=20,choices=giorno_giorno(),unique=True,\ help_text=ugettext_lazy("weekday name")) - def __unicode__(self): + def __str__(self): return self.name class Configure(models.Model): @@ -279,7 +276,7 @@ class Configure(models.Model): type = models.CharField(max_length=50,unique=True, default='radiofonica', editable=True,\ help_text=ugettext_lazy("The station type for the print of programs book")) - def __unicode__(self): + def __str__(self): if self.emission_starttime is None: emission_starttime = "-" @@ -303,7 +300,7 @@ class ProgramType(models.Model): subtype = models.CharField(ugettext_lazy("SubType"),max_length=254,default=None,null=False,blank=False) description = models.TextField(ugettext_lazy("Description"),default=None,null=True,blank=True) - def __unicode__(self): + def __str__(self): return self.type+"/"+self.subtype def Production(): @@ -318,7 +315,7 @@ class Show(models.Model): active = models.BooleanField(ugettext_lazy("Active"),default=True,help_text=ugettext_lazy("Activate the show for emission")) slug = models.SlugField(unique=True, help_text=ugettext_lazy('Auto-generated from Title.')) length = models.FloatField(ugettext_lazy("Time length (seconds)"),default=None,null=True,blank=True, help_text=ugettext_lazy('Time lenght how you want to see it in the palimpsest')) - type = models.ForeignKey(ProgramType, verbose_name= ugettext_lazy('Program Type'), help_text=ugettext_lazy('The categorization that follow the italian law (you have to use it to produce the programs book')) + type = models.ForeignKey(ProgramType, verbose_name= ugettext_lazy('Program Type'), help_text=ugettext_lazy('The categorization that follow the italian law (you have to use it to produce the programs book') , on_delete=models.CASCADE) production = models.CharField(ugettext_lazy("Production"),max_length=30,choices=Production(),default=None,null=True,blank=True, help_text=ugettext_lazy('The type of production')) COPYRIGHT_CHOICES = ( @@ -344,7 +341,7 @@ class Show(models.Model): copyright = models.CharField(max_length=255, default='All rights reserved', choices=COPYRIGHT_CHOICES, help_text=ugettext_lazy('See Creative Commons licenses for more information.')) copyright_url = models.URLField('Copyright URL', blank=True, help_text=ugettext_lazy('A URL pointing to additional copyright information. Consider a Creative Commons license URL.')) author = models.ManyToManyField(User, related_name='display_authors', help_text=ugettext_lazy('Remember to save the user\'s name and e-mail address in the User application.
')) - webmaster = models.ForeignKey(User, related_name='display_webmaster', blank=True, null=True, help_text=ugettext_lazy('Remember to save the user\'s name and e-mail address in the User application.')) + webmaster = models.ForeignKey(User, related_name='display_webmaster', blank=True, null=True, help_text=ugettext_lazy('Remember to save the user\'s name and e-mail address in the User application.') , on_delete=models.CASCADE) category_show = models.CharField('Category', max_length=255, blank=True, help_text=ugettext_lazy('Limited to one user-specified category for the sake of sanity.')) domain = models.URLField(blank=True, help_text=ugettext_lazy('A URL that identifies a categorization taxonomy.')) ttl = models.PositiveIntegerField('TTL', help_text=ugettext_lazy('"Time to Live," the number of minutes a channel can be cached before refreshing.'), blank=True, null=True) @@ -364,7 +361,7 @@ class Show(models.Model): class Meta(object): ordering = ['organization', 'slug'] - def __unicode__(self): + def __str__(self): return u'%s' % (self.title) #@models.permalink @@ -372,7 +369,7 @@ def __unicode__(self): # return ('podcast_episodes', (), { 'slug': self.slug }) def get_absolute_url(self): - from django.core.urlresolvers import reverse + from django.urls import reverse return reverse('podcast_episodes', args=[str(self.slug)]) @@ -555,7 +552,7 @@ class Episode(models.Model): ('never', 'Never'), ) # RSS 2.0 - show = models.ForeignKey(Show) + show = models.ForeignKey(Show , on_delete=models.CASCADE) title = models.CharField(max_length=255, help_text=ugettext_lazy('Make it specific but avoid explicit language. Limit to 100 characters for a Google video sitemap.')) active = models.BooleanField(ugettext_lazy("Active"),default=True) date = models.DateTimeField(ugettext_lazy('Recording date'),auto_now_add=True) @@ -607,7 +604,7 @@ class Episode(models.Model): class Meta(object): ordering = ['-date', 'slug'] - def __unicode__(self): + def __str__(self): return u'%s' % (self.title) #@models.permalink @@ -615,7 +612,7 @@ def __unicode__(self): # return ('podcast_episode', (), { 'show_slug': self.show.slug, 'episode_slug': self.slug }) def get_absolute_url(self): - from django.core.urlresolvers import reverse + from django.urls import reverse return reverse('podcast_episode', args=[str(self.show.slug),str(self.slug)]) def seconds_total(self): @@ -631,7 +628,7 @@ def was_recorded_today(self): return self.rec_date.date() == datetime.date.today() was_recorded_today.short_description = ugettext_lazy('Recorded today?') - def __unicode__(self): + def __str__(self): return self.title @@ -705,7 +702,7 @@ class Enclosure(models.Model): embed = models.BooleanField(help_text=ugettext_lazy('Check to allow Google to embed your external player in search results on Google Video.'), blank=True) width = models.PositiveIntegerField(blank=True, null=True, help_text=ugettext_lazy("Width of the browser window in
which the URL should be opened.
YouTube's default is 425.")) height = models.PositiveIntegerField(blank=True, null=True, help_text=ugettext_lazy("Height of the browser window in
which the URL should be opened.
YouTube's default is 344.")) - episode = models.ForeignKey(Episode, help_text=ugettext_lazy('Include any number of media files; for example, perhaps include an iPhone-optimized, AppleTV-optimized and Flash Video set of video files. Note that the iTunes feed only accepts the first file. More uploading is available after clicking "Save and continue editing."')) + episode = models.ForeignKey(Episode, help_text=ugettext_lazy('Include any number of media files; for example, perhaps include an iPhone-optimized, AppleTV-optimized and Flash Video set of video files. Note that the iTunes feed only accepts the first file. More uploading is available after clicking "Save and continue editing."'), on_delete=models.CASCADE) class Meta(object): ordering = ['mime', 'file'] @@ -721,7 +718,7 @@ def save(self, *args, **kwargs): super(Enclosure, self).save(*args, **kwargs) - def __unicode__(self): + def __str__(self): return u'%s' % (self.file) @@ -731,7 +728,7 @@ class Schedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) episode = models.ForeignKey(Episode, \ - verbose_name=ugettext_lazy('Linked episode:')) + verbose_name=ugettext_lazy('Linked episode:'), on_delete=models.CASCADE) emission_date = models.DateTimeField(ugettext_lazy('programmed date'),\ help_text=ugettext_lazy("This is the date and time when the program will be on air")) @@ -750,7 +747,7 @@ def refepisode(self): return self.episode.title refepisode.short_description = ugettext_lazy('Linked episode:') - def __unicode__(self): + def __str__(self): return str(self.episode.title) @@ -758,15 +755,15 @@ def __unicode__(self): class ScheduleDone(models.Model): schedule = models.ForeignKey(Schedule, \ - verbose_name=ugettext_lazy('Linked schedule:')) + verbose_name=ugettext_lazy('Linked schedule:'), on_delete=models.CASCADE) enclosure = models.ForeignKey(Enclosure, \ - verbose_name=ugettext_lazy('Linked enclosure:')) + verbose_name=ugettext_lazy('Linked enclosure:'), on_delete=models.CASCADE) emission_done = models.DateTimeField(ugettext_lazy('emission done')\ ,null=True,editable=False ) - def __unicode__(self): + def __str__(self): return str(self.emission_done) @@ -777,7 +774,7 @@ class PeriodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) show = models.ForeignKey(Show,verbose_name=\ - ugettext_lazy('refer to show:')) + ugettext_lazy('refer to show:'), on_delete=models.CASCADE) start_date = models.DateField(ugettext_lazy('Programmed start date'),null=True,blank=True,\ help_text=ugettext_lazy("The program will be in palimpsest starting from this date")) @@ -789,7 +786,7 @@ class PeriodicSchedule(models.Model): help_text=ugettext_lazy("The program will be in palimpsest those weekdays")) - def __unicode__(self): + def __str__(self): return str(self.show) class AperiodicSchedule(models.Model): @@ -798,7 +795,7 @@ class AperiodicSchedule(models.Model): # num_in_admin=2,verbose_name='si riferisce al programma:',editable=False) show = models.ForeignKey(Show, verbose_name=\ - ugettext_lazy('refer to Show:')) + ugettext_lazy('refer to Show:'), on_delete=models.CASCADE) emission_date = models.DateTimeField(ugettext_lazy('Programmed date'),\ help_text=ugettext_lazy("This is the date and time when the program is planned in palimsest")) @@ -808,6 +805,6 @@ def was_scheduled_today(self): was_scheduled_today.short_description = ugettext_lazy('Programmed for today?') - def __unicode__(self): + def __str__(self): return str(self.show) diff --git a/autoradio/programs/templates/schedule/index.html b/autoradio/programs/templates/schedule/index.html index 0494408..0db26b6 100644 --- a/autoradio/programs/templates/schedule/index.html +++ b/autoradio/programs/templates/schedule/index.html @@ -9,30 +9,31 @@

{% trans "Automatic update every" %} 5 {% trans "minuts" %}. {% trans "Last update" %}: {% now "Y-m-d H:i:s" %}

{% trans "This is on air status" %}:

-{% if schedule %} - +{% if schedules %} +
- {% for djobj,title,datet,media,length,tipo,datetdone,future in schedule %} + {% for schedule in schedules %} + {%ifequal schedule.tipo "spot" %} bgcolor="#FFA500" {% endifequal %} + {%ifequal schedule.tipo "playlist" %} bgcolor="#FFFF00" {% endifequal %} + {%ifequal schedule.tipo "program" %} bgcolor="#1E90FF" {% endifequal %} + {%ifequal schedule.tipo "jingle" %} bgcolor="#448888" {% endifequal %} + > {{ schedule.tipo }} - - - - - + {%ifequal schedule.tipo "spot" %} bgcolor="#FFA500" {% endifequal %} + {%ifequal schedule.tipo "playlist" %} bgcolor="#FFFF00" {% endifequal %} + {%ifequal schedule.tipo "program" %} bgcolor="#1E90FF" {% endifequal %} + {%ifequal schedule.tipo "jingle" %} bgcolor="#448888" {% endifequal %} + > {{ schedule.title }} + + + + + {% endfor %}
{% trans "Type" %} {% trans "Title" %} {% trans "Programmed for" %} {% trans "That is" %} {% trans "Last emission done" %} {% trans "Length" %} {% trans "File" %}
{{ tipo }} {{ title }} {{ datet|date:"Y-m-d H:i:s" }} {%if datet %} {% if future %} {% trans "in" %} {{ datet|timeuntil }} {% else %} {{ datet|timesince }} {% trans "ago" %} {% endif %}{% endif %} {{ datetdone|timesince }} {%if datetdone %} {% trans "ago" %} {% endif %} {{ length }} {% trans "Download" %} {{ schedule.datet|date:"Y-m-d H:i:s" }} {%if schedule.datet %} {% if schedule.isfuture %} {% trans "in" %} {{ schedule.datet|timeuntil }} {% else %} {{ schedule.datet|timesince }} {% trans "ago" %} {% endif %}{% endif %} {{ schedule.datetdone|timesince }} {%if schedule.datetdone %} {% trans "ago" %} {% endif %} {{ schedule.length_s }} {% trans "Download" %}
diff --git a/autoradio/programs/views.py b/autoradio/programs/views.py index e809b21..b7d35a8 100644 --- a/autoradio/programs/views.py +++ b/autoradio/programs/views.py @@ -33,10 +33,16 @@ def index(request): - scheds=autoradio.autoradio_core.schedules([]) - return render_to_response('schedule/index.html', {'schedule': scheds.get_all_refine(genfile=False)}) + scheds.get_all_refine(genfile=False) + #print ("s=",scheds) + #for ss in scheds: + # ss + # print ("ss=",ss) + # for sss in ss: + # print ("sss=",sss) + return render_to_response('schedule/index.html', {'schedules': scheds}) def stato(request): @@ -270,7 +276,7 @@ def myPages(canvas, doc): form = ExtremeForm() # An unbound form return render_to_response('palimpsest/extreme.html', { - 'form': form,}) + 'form': form}) #---------------------------------------------------- @@ -279,8 +285,7 @@ def myPages(canvas, doc): from django.views.generic.detail import DetailView #from django.views.generic.list_detail import object_list from autoradio.programs.models import Episode, Show, Enclosure -from django.core.urlresolvers import reverse - +from django.urls import reverse class episode_detail(DetailView): #class episode_detail(ListView): diff --git a/autoradio/programs/widgets.py b/autoradio/programs/widgets.py index 7eed230..6e50ab4 100644 --- a/autoradio/programs/widgets.py +++ b/autoradio/programs/widgets.py @@ -38,7 +38,7 @@ def __init__(self, attrs=None, years=None, required=True): this_year = datetime.date.today().year-9 self.years = list(range(this_year, this_year+10)) - def render(self, name, value, attrs=None): + def render(self, name, value, attrs=None, renderer=None): try: year_val, month_val, day_val = value.year, value.month, value.day @@ -59,7 +59,7 @@ def render(self, name, value, attrs=None): day_choices = [(i, i) for i in range(1, 32)] if not (self.required and value): day_choices.insert(0, self.none_value) - local_attrs = self.build_attrs(id=self.day_field % id_) + local_attrs = self.build_attrs(base_attrs={'id':self.day_field % id_}) s = Select(choices=day_choices) select_html = s.render(self.day_field % name, day_val, local_attrs) diff --git a/autoradio/settings.py b/autoradio/settings.py index b963459..511f6c5 100644 --- a/autoradio/settings.py +++ b/autoradio/settings.py @@ -239,7 +239,7 @@ -MIDDLEWARE_CLASSES = [ +MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', @@ -250,6 +250,7 @@ ROOT_URLCONF = 'autoradio.urls' INSTALLED_APPS = [ + 'django.contrib.messages', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', diff --git a/autoradio/spots/models.py b/autoradio/spots/models.py index eaac75a..dbea633 100644 --- a/autoradio/spots/models.py +++ b/autoradio/spots/models.py @@ -56,7 +56,7 @@ class Giorno(models.Model): name = models.CharField(max_length=20,choices=giorno_giorno(),unique=True, help_text=ugettext_lazy("weekday name")) - def __unicode__(self): + def __str__(self): return self.name class Admin(object): @@ -90,7 +90,7 @@ class Admin(object): ## #name = models.CharField(max_length=20) -## def __unicode__(self): +## def __str__(self): ## return self.name ## class Admin: @@ -107,7 +107,7 @@ class Configure(models.Model): help_text=ugettext_lazy("The end time the spot will be active")) - def __unicode__(self): + def __str__(self): if self.emission_starttime is None: start="-" else: @@ -155,7 +155,7 @@ def spots(self): # self.spot_set.exclude(prologo__exact=True).exclude(epilogo__exact=True).order_by('priorita')).append(\ # self.spot_set.filter(epilogo__exact=True).order_by('priorita')) - def __unicode__(self): + def __str__(self): return self.name+" "+self.emission_time.isoformat() class Admin(object): @@ -197,7 +197,7 @@ def was_recorded_today(self): was_recorded_today.short_description = ugettext_lazy('Recorded today?') - def __unicode__(self): + def __str__(self): return self.spot class Admin(object): diff --git a/autoradio/urls.py b/autoradio/urls.py index 2d4b60d..2c939c6 100644 --- a/autoradio/urls.py +++ b/autoradio/urls.py @@ -22,7 +22,7 @@ url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: - url(r'^admin/', include(admin.site.urls)), + url(r'^admin/', admin.site.urls), url(r'^', include('autoradio.programs.urls')), # url(r'^', include('autoradio.palimpsest.urls')), diff --git a/autoradioctrl b/autoradioctrl index 3962b50..1175fdf 100755 --- a/autoradioctrl +++ b/autoradioctrl @@ -47,7 +47,8 @@ def initdb(cwd): #os.chdir(cwd) if (options.syncdb): - management.call_command("migrate",no_initial_data=True ) + #management.call_command("migrate",no_initial_data=True ) + management.call_command("migrate" ) if __name__ == '__main__': diff --git a/autoradiod b/autoradiod index 7119da7..66597fe 100755 --- a/autoradiod +++ b/autoradiod @@ -146,7 +146,8 @@ def main(): while ( True): scheds=autoradio.autoradio_core.schedules([]) - for schedule in scheds.get_all_refine(now): + scheds.get_all_refine(now) + for schedule in scheds: scheduledatetime=schedule.scheduledatetime filename=schedule.filename diff --git a/autoradiodbusd b/autoradiodbusd index c82ebc2..7cd1785 100755 --- a/autoradiodbusd +++ b/autoradiodbusd @@ -40,7 +40,7 @@ def main(self): self.procs=[subprocess.Popen(["dbus-daemon", "--config-file="+autoradio.settings.conffiledbus, '--address='+busaddress, "--nofork"],cwd=self.cwd)] else: - print "busaddress is not defined in config file: dbus-daemon not started" + print ("busaddress is not defined in config file: dbus-daemon not started") if __name__ == '__main__': From a1ef269235c8cf9c2e0e8108c35194bd2d1ff697 Mon Sep 17 00:00:00 2001 From: Paolo Patruno Date: Tue, 14 Jan 2020 18:42:02 +0100 Subject: [PATCH 8/8] release 3.2 for Debian --- autoradio/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autoradio/__init__.py b/autoradio/__init__.py index 3935908..5024d89 100644 --- a/autoradio/__init__.py +++ b/autoradio/__init__.py @@ -1 +1 @@ -_version_="3.1" +_version_="3.2"