Drop python2 support.

Update for PyTQt.

Signed-off-by: Slávek Banko <slavek.banko@axis.cz>
pull/35/head
Slávek Banko 1 year ago
parent 5f01cbb7f8
commit 9be5499101
No known key found for this signature in database
GPG Key ID: 608F5293A04BE668

@ -4,7 +4,7 @@
# Config dialog for alarm script
# (c) 2005 Mark Kretschmann <markey@web.de>
#
# Depends on: Python 2.2, PyQt
# Depends on: Python 3, PyTQt
############################################################################
#
# This program is free software; you can redistribute it and/or modify
@ -14,42 +14,42 @@
#
############################################################################
from ConfigParser import *
import Queue
from configparser import *
import queue
import os.path
import sys
import threading
from os import *
try:
from qt import *
from PyTQt.qt import *
except:
popen( "kdialog --sorry 'PyQt (Qt bindings for Python) is required for this script.'" )
popen( "kdialog --sorry 'PyTQt (TQt bindings for Python) is required for this script.'" )
raise
class ConfigDialog( QDialog ):
class ConfigDialog( TQDialog ):
def __init__( self ):
QDialog.__init__( self )
self.setWFlags( Qt.WDestructiveClose )
TQDialog.__init__( self )
self.setWFlags( TQt.WDestructiveClose )
self.setCaption( "Alarm Script - Amarok" )
self.lay = QHBoxLayout( self )
self.lay = TQHBoxLayout( self )
self.vbox = QVBox( self )
self.vbox = TQVBox( self )
self.lay.addWidget( self.vbox )
self.htopbox = QHBox( self.vbox )
QLabel( "Alarm time: ", self.htopbox )
self.timeEdit = QTimeEdit( self.htopbox )
self.htopbox = TQHBox( self.vbox )
TQLabel( "Alarm time: ", self.htopbox )
self.timeEdit = TQTimeEdit( self.htopbox )
self.hbox = QHBox( self.vbox )
self.hbox = TQHBox( self.vbox )
self.ok = QPushButton( self.hbox )
self.ok = TQPushButton( self.hbox )
self.ok.setText( "Ok" )
self.cancel = QPushButton( self.hbox )
self.cancel = TQPushButton( self.hbox )
self.cancel.setText( "Cancel" )
self.cancel.setDefault( True )
@ -59,11 +59,11 @@ class ConfigDialog( QDialog ):
self.adjustSize()
def __del__( self ):
print "ConfigDialog dtor"
print("ConfigDialog dtor")
def save( self ):
wakeTime = str( self.timeEdit.time().toString() )
print wakeTime
print(wakeTime)
self.file = file( "alarmrc", 'w' )
@ -76,24 +76,24 @@ class ConfigDialog( QDialog ):
self.accept()
class Alarm( QApplication ):
class Alarm( TQApplication ):
def __init__( self, args ):
QApplication.__init__( self, args )
TQApplication.__init__( self, args )
self.queue = Queue.Queue()
self.queue = queue.Queue()
self.startTimer( 100 )
self.t = threading.Thread( target = self.readStdin )
self.t.start()
self.alarmTimer = QTimer()
self.alarmTimer = TQTimer()
self.connect( self.alarmTimer, SIGNAL( "timeout()" ), self.wakeup )
self.readSettings()
def __del__( self ):
print "Alarm dtor"
print("Alarm dtor")
def wakeup( self ):
popen( "dcop amarok player play" )
@ -106,10 +106,10 @@ class Alarm( QApplication ):
try:
timestr = config.get( "General", "alarmtime" )
print "Alarm Time: " + timestr
print("Alarm Time: " + timestr)
time = QTime.fromString( timestr )
secondsleft = QTime.currentTime().secsTo( time )
time = TQTime.fromString( timestr )
secondsleft = TQTime.currentTime().secsTo( time )
if secondsleft > 0:
self.alarmTimer.start( secondsleft * 1000, True )
@ -137,14 +137,14 @@ class Alarm( QApplication ):
def timerEvent( self, event ):
if not self.queue.empty():
string = QString( self.queue.get_nowait() )
print "[Alarm Script] Received notification: " + str( string )
eventStr = TQString( self.queue.get_nowait() )
print("[Alarm Script] Received notification: " + str( eventStr ))
if string.contains( "configure" ):
if eventStr.contains( "configure" ):
self.configure()
def configure( self ):
print "Alarm Script: configuration"
print("Alarm Script: configuration")
self.dia = ConfigDialog()
self.dia.show()

@ -7,7 +7,7 @@
#
# (c) 2005 Leo Franchi <lfranchi@gmail.com>
#
# Depends on: Python 2.2, PyQt
# Depends on: Python 3, PyTQt
############################################################################
#
# This program is free software; you can redistribute it and/or modify
@ -17,7 +17,7 @@
#
############################################################################
import ConfigParser
import configparser
import os
import sys
import threading
@ -25,9 +25,9 @@ import signal
from time import sleep
try:
from qt import *
from TQt.qt import *
except:
os.popen( "kdialog --sorry 'PyQt (Qt bindings for Python) is required for this script.'" )
os.popen( "kdialog --sorry 'PyTQt (TQt bindings for Python) is required for this script.'" )
raise
@ -35,34 +35,34 @@ except:
debug_prefix = "LiveCD Remastering"
class ConfigDialog ( QDialog ):
class ConfigDialog ( TQDialog ):
""" Configuration widget """
def __init__( self ):
QDialog.__init__( self )
self.setWFlags( Qt.WDestructiveClose )
TQDialog.__init__( self )
self.setWFlags( TQt.WDestructiveClose )
self.setCaption("Amarok Live! Configuration")
self.lay = QGridLayout( self, 3, 2)
self.lay = TQGridLayout( self, 3, 2)
self.lay.addColSpacing( 0, 300 )
self.isopath = QLineEdit( self )
self.isopath = TQLineEdit( self )
self.isopath.setText( "Path to Amarok Live! iso" )
self.tmppath = QLineEdit( self )
self.tmppath = TQLineEdit( self )
self.tmppath.setText( "Temporary directory used, 2.5gb free needed" )
self.lay.addWidget( self.isopath, 0, 0 )
self.lay.addWidget( self.tmppath, 1, 0 )
self.isobutton = QPushButton( self )
self.isobutton = TQPushButton( self )
self.isobutton.setText("Browse..." )
self.tmpbutton = QPushButton( self )
self.tmpbutton = TQPushButton( self )
self.tmpbutton.setText("Browse..." )
self.cancel = QPushButton( self )
self.cancel = TQPushButton( self )
self.cancel.setText( "Cancel" )
self.ok = QPushButton( self )
self.ok = TQPushButton( self )
self.ok.setText( "Ok" )
self.lay.addWidget( self.isobutton, 0, 1 )
@ -82,7 +82,7 @@ class ConfigDialog ( QDialog ):
path = None
try:
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
config.read( "remasterrc" )
path = config.get( "General", "path" )
iso = config.get( "General", "iso")
@ -97,7 +97,7 @@ class ConfigDialog ( QDialog ):
def save( self ):
""" Saves configuration to file """
self.file = file( "remasterrc", 'w' )
self.config = ConfigParser.ConfigParser()
self.config = configparser.ConfigParser()
self.config.add_section( "General" )
self.config.set( "General", "path", self.tmppath.text() )
self.config.set( "General", "iso", self.isopath.text() )
@ -109,7 +109,7 @@ class ConfigDialog ( QDialog ):
def clear():
self.file = file( "remasterrc", 'w' )
self.config = ConfigParser.ConfigParser()
self.config = configparser.ConfigParser()
self.config.add_section( "General" )
self.config.set( "General", "path", "" )
self.config.set( "General", "iso", "" )
@ -118,7 +118,7 @@ class ConfigDialog ( QDialog ):
def browseISO( self ):
path = QFileDialog.getOpenFileName( "/home",
path = TQFileDialog.getOpenFileName( "/home",
"CD Images (*.iso)",
self,
"iso choose dialogr",
@ -127,7 +127,7 @@ class ConfigDialog ( QDialog ):
def browsePath( self ):
tmp = QFileDialog.getExistingDirectory( "/home",
tmp = TQFileDialog.getExistingDirectory( "/home",
self,
"get tmp dir",
"Choose working directory",
@ -147,7 +147,7 @@ class ConfigDialog ( QDialog ):
path, iso = self.readConfig()
os.system("tdesu -t sh %s/amarok.live.remaster.part1.sh %s %s" % (scriptdir, path, iso))
#os.wait()
print "got path: %s" % path
print("got path: %s" % path)
@ -156,7 +156,7 @@ class ConfigDialog ( QDialog ):
path = ""
iso = ""
try:
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
config.read("remasterrc")
path = config.get("General", "path")
iso = config.get("General", "iso")
@ -166,19 +166,18 @@ class ConfigDialog ( QDialog ):
class Notification( QCustomEvent ):
__super_init = QCustomEvent.__init__
class Notification( TQCustomEvent ):
__super_init = TQCustomEvent.__init__
def __init__( self, str ):
self.__super_init(TQCustomEvent.User + 1)
self.eventStr = str
self.__super_init(QCustomEvent.User + 1)
self.string = str
class Remasterer( QApplication ):
""" The main application, also sets up the Qt event loop """
class Remasterer( TQApplication ):
""" The main application, also sets up the TQt event loop """
def __init__( self, args ):
QApplication.__init__( self, args )
TQApplication.__init__( self, args )
debug( "Started." )
# Start separate thread for reading data from stdin
@ -187,7 +186,6 @@ class Remasterer( QApplication ):
self.readSettings()
# ugly hack, thanks mp8 anyway
os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
@ -234,22 +232,22 @@ class Remasterer( QApplication ):
def customEvent( self, notification ):
""" Handles notifications """
string = QString(notification.string)
debug( "Received notification: " + str( string ) )
eventStr = TQString(notification.eventStr)
debug( "Received notification: " + str( eventStr ) )
if string.contains( "configure" ):
if eventStr.contains( "configure" ):
self.configure()
if string.contains( "stop"):
if eventStr.contains( "stop" ):
self.stop()
elif string.contains( "customMenuClicked" ):
if "selected" in string:
self.copyTrack( string )
elif "playlist" in string:
elif eventStr.contains( "customMenuClicked" ):
if eventStr.contains( "selected" ):
self.copyTrack( eventStr )
elif eventStr.contains( "playlist" ):
self.copyPlaylist()
elif "Create" in string:
elif eventStr.contains( "Create" ):
self.createCD()
elif "Clear" in string:
elif eventStr.contains( "Clear" ):
self.clearCD()
@ -297,7 +295,7 @@ class Remasterer( QApplication ):
os.system("dcop amarok playlist saveM3u '%s' false" % tmpfileloc)
tmpfile = open(tmpfileloc)
import urllib
import urllib.request, urllib.parse, urllib.error
files = ""
m3u = ""
@ -310,7 +308,7 @@ class Remasterer( QApplication ):
name = line.split("/")[-1]
#make url
url = "file://" + urllib.quote(line)
url = "file://" + urllib.parse.quote(line)
#make path on livecd
livecdpath = "/music/" + name
@ -394,7 +392,7 @@ def onSignal( signum, stackframe ):
fd.write( "stopping")
fd.close()
print 'STOPPING'
print('STOPPING')
os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add playlist to livecd\"")
os.system("dcop amarok script removeCustomMenuItem \"Amarok live\" \"Add selected to livecd\"")
@ -405,7 +403,7 @@ def onSignal( signum, stackframe ):
def debug( message ):
""" Prints debug message to stdout """
print debug_prefix + " " + message
print(debug_prefix + " " + message)
def main():
app = Remasterer( sys.argv )
@ -420,7 +418,7 @@ if __name__ == "__main__":
mainapp = threading.Thread(target=main)
mainapp.start()
signal.signal(15, onSignal)
print signal.getsignal(15)
print(signal.getsignal(15))
while 1: sleep(120)
#main( sys.argv )

@ -87,6 +87,7 @@ import socket
import threading
import select
import traceback
from functools import reduce
__all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
@ -212,7 +213,7 @@ class DNSEntry(object):
"""A DNS entry"""
def __init__(self, name, type, clazz):
self.key = string.lower(name)
self.key = name.lower()
self.name = name
self.type = type
self.clazz = clazz & _CLASS_MASK
@ -821,7 +822,7 @@ class DNSCache(object):
"""Returns a list of all entries"""
def add(x, y): return x+y
try:
return reduce(add, self.cache.values())
return reduce(add, list(self.cache.values()))
except:
return []
@ -870,7 +871,7 @@ class Engine(threading.Thread):
def getReaders(self):
result = []
self.condition.acquire()
result = self.readers.keys()
result = list(self.readers.keys())
self.condition.release()
return result
@ -1008,7 +1009,7 @@ class ServiceBrowser(threading.Thread):
if self.nextTime <= now:
out = DNSOutgoing(_FLAGS_QR_QUERY)
out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
for record in self.services.values():
for record in list(self.services.values()):
if not record.isExpired(now):
out.addAnswerAtTime(record, now)
self.zeroconf.send(out)
@ -1335,7 +1336,7 @@ class Zeroconf(object):
changed if needed to make it unique on the network."""
self.checkService(info)
self.services[info.name.lower()] = info
if self.servicetypes.has_key(info.type):
if info.type in self.servicetypes:
self.servicetypes[info.type]+=1
else:
self.servicetypes[info.type]=1
@ -1387,7 +1388,7 @@ class Zeroconf(object):
def unregisterAllServices(self):
"""Unregister all registered services."""
print 'Unregistering ',len(self.services),' services'
print('Unregistering ',len(self.services),' services')
if len(self.services) > 0:
now = currentTimeMillis()
nextTime = now
@ -1398,7 +1399,7 @@ class Zeroconf(object):
now = currentTimeMillis()
continue
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
for info in self.services.values():
for info in list(self.services.values()):
out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.server), 0)
out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
@ -1495,11 +1496,11 @@ class Zeroconf(object):
for question in msg.questions:
if question.type == _TYPE_PTR:
if question.name == "_services._dns-sd._udp.local.":
for stype in self.servicetypes.keys():
for stype in list(self.servicetypes.keys()):
if out is None:
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
out.addAnswer(msg, DNSPointer("_services._dns-sd._udp.local.", _TYPE_PTR, _CLASS_IN, _DNS_TTL, stype))
for service in self.services.values():
for service in list(self.services.values()):
if question.name == service.type:
if out is None:
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
@ -1511,7 +1512,7 @@ class Zeroconf(object):
# Answer A record queries for any service addresses we know
if question.type == _TYPE_A or question.type == _TYPE_ANY:
for service in self.services.values():
for service in list(self.services.values()):
if service.server == question.name.lower():
out.addAnswer(msg, DNSAddress(question.name, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address))
@ -1544,10 +1545,10 @@ class Zeroconf(object):
def close(self):
"""Ends the background threads, and prevent this instance from
servicing further queries."""
print 'in close'
print('in close')
if globals()['_GLOBAL_DONE'] == 0:
globals()['_GLOBAL_DONE'] = 1
print 'closing globals'
print('closing globals')
self.notifyAll()
self.engine.notify()
self.unregisterAllServices()
@ -1558,21 +1559,21 @@ class Zeroconf(object):
# query (for Zoe), and service unregistration.
if __name__ == '__main__':
print "Multicast DNS Service Discovery for Python, version", __version__
print("Multicast DNS Service Discovery for Python, version", __version__)
r = Zeroconf()
print "1. Testing registration of a service..."
print("1. Testing registration of a service...")
desc = {'version':'0.10','a':'test value', 'b':'another value'}
info = ServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.", socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
print " Registering service..."
print(" Registering service...")
r.registerService(info)
print " Registration done."
print "2. Testing query of service information..."
print " Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))
print " Query done."
print "3. Testing query of own service..."
print " Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local."))
print " Query done."
print "4. Testing unregister of service information..."
print(" Registration done.")
print("2. Testing query of service information...")
print(" Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local.")))
print(" Query done.")
print("3. Testing query of own service...")
print(" Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.")))
print(" Query done.")
print("4. Testing unregister of service information...")
r.unregisterService(info)
print " Unregister done."
print(" Unregister done.")
r.close()

@ -16,7 +16,7 @@ class Track(object):
__Q_SLOTS__ = FIELDS
def __init__(self, **kwargs):
for key,value in kwargs.iteritems():
for key,value in kwargs.items():
setattr(self, key, value)

@ -9,8 +9,8 @@
License: GPL
"""
import SimpleHTTPServer
import BaseHTTPServer
import http.server
import http.server
from Playlist import Playlist
# the port number to listen to
@ -19,7 +19,7 @@ PORT = 4773
PLIST = None
class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
class RequestHandler(http.server.SimpleHTTPRequestHandler):
"""We need our own 'RequestHandler, to handle the requests, that arrive at
our server."""
@ -35,7 +35,7 @@ def main():
"""main is the starting-point for our script."""
global PLIST
PLIST = Playlist()
srv = BaseHTTPServer.HTTPServer(('',PORT),RequestHandler)
srv = http.server.HTTPServer(('',PORT),RequestHandler)
srv.serve_forever()

@ -10,7 +10,7 @@ def main():
stdin = os.popen("kdialog --getsaveurl %s"%(user.home))
dest = stdin.readline().strip()[5:]
plist = Playlist()
print dest
print(dest)
try:
f = open(dest, "w")
f.write(plist.toHtml())

@ -4,7 +4,7 @@
# Python-Qt template script for Amarok
# (c) 2005 Mark Kretschmann <markey@web.de>
#
# Depends on: Python 2.2, PyQt
# Depends on: Python 3, PyTQt
############################################################################
#
# This program is free software; you can redistribute it and/or modify
@ -14,7 +14,7 @@
#
############################################################################
import ConfigParser
import configparser
import os
import sys
import threading
@ -22,9 +22,9 @@ import signal
from time import sleep
try:
from qt import *
from PyTQt.qt import *
except:
os.popen( "kdialog --sorry 'PyQt (Qt bindings for Python) is required for this script.'" )
os.popen( "kdialog --sorry 'PyTQt (TQt bindings for Python) is required for this script.'" )
raise
@ -36,13 +36,13 @@ class ConfigDialog( QDialog ):
""" Configuration widget """
def __init__( self ):
QDialog.__init__( self )
self.setWFlags( Qt.WDestructiveClose )
TQDialog.__init__( self )
self.setWFlags( TQt.WDestructiveClose )
self.setCaption( "Test Script - Amarok" )
foo = None
try:
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
config.read( "testrc" )
foo = config.get( "General", "foo" )
except:
@ -55,7 +55,7 @@ class ConfigDialog( QDialog ):
self.file = file( "testrc", 'w' )
self.config = ConfigParser.ConfigParser()
self.config = configparser.ConfigParser()
self.config.add_section( "General" )
self.config.set( "General", "foo", foovar )
self.config.write( self.file )
@ -64,17 +64,17 @@ class ConfigDialog( QDialog ):
self.accept()
class Notification( QCustomEvent ):
__super_init = QCustomEvent.__init__
class Notification( TQCustomEvent ):
__super_init = TQCustomEvent.__init__
def __init__( self, str ):
self.__super_init(QCustomEvent.User + 1)
self.string = str
self.__super_init(TQCustomEvent.User + 1)
self.eventStr = str
class Test( QApplication ):
""" The main application, also sets up the Qt event loop """
class Test( TQApplication ):
""" The main application, also sets up the TQt event loop """
def __init__( self, args ):
QApplication.__init__( self, args )
TQApplication.__init__( self, args )
debug( "Started." )
# Start separate thread for reading data from stdin
@ -117,25 +117,25 @@ class Test( QApplication ):
def customEvent( self, notification ):
""" Handles notifications """
string = QString(notification.string)
debug( "Received notification: " + str( string ) )
eventStr = TQString(notification.eventStr)
debug( "Received notification: " + str( eventStr ) )
if string.contains( "configure" ):
if eventStr.contains( "configure" ):
self.configure()
if string.contains( "engineStateChange: play" ):
if eventStr.contains( "engineStateChange: play" ):
self.engineStatePlay()
if string.contains( "engineStateChange: idle" ):
if eventStr.contains( "engineStateChange: idle" ):
self.engineStateIdle()
if string.contains( "engineStateChange: pause" ):
if eventStr.contains( "engineStateChange: pause" ):
self.engineStatePause()
if string.contains( "engineStateChange: empty" ):
if eventStr.contains( "engineStateChange: empty" ):
self.engineStatePause()
if string.contains( "trackChange" ):
if eventStr.contains( "trackChange" ):
self.trackChange()
# Notification callbacks. Implement these functions to react to specific notification
@ -174,7 +174,7 @@ class Test( QApplication ):
def debug( message ):
""" Prints debug message to stdout """
print debug_prefix + " " + message
print(debug_prefix + " " + message)
def main( ):
app = Test( sys.argv )

@ -30,7 +30,7 @@ class Track(object):
max_field_value_lengths = [(0,"")] * len(FIELDS)
def __init__(self, **kwargs):
for key,value in kwargs.iteritems():
for key,value in kwargs.items():
setattr(self, key, value)
@ -53,11 +53,11 @@ class Track(object):
index = 0
# for f in self.__Q_SLOTS__ :
# print string.strip(f)
# print f.strip()
for i in [getattr(self,f) for f in self.__Q_SLOTS__ ]:
if len(string.strip(i)) > Track.max_field_value_lengths[index][0]:
Track.max_field_value_lengths[index] = (len(string.strip(i)),i)
if len(i.strip()) > Track.max_field_value_lengths[index][0]:
Track.max_field_value_lengths[index] = (len(i.strip()),i)
index += 1
tr_style = ''

@ -11,8 +11,8 @@
License: GPL
"""
import SimpleHTTPServer
import BaseHTTPServer
import http.server
import http.server
from Playlist import Playlist
import Globals
@ -63,8 +63,7 @@ class AmarokStatus:
if self.playState != -1:
res = self.playState == self.EnginePlay
else:
res = string.find(self.dcop_isplaying.result(), "true") >= 0
if res:
if "true" in self.dcop_isplaying.result():
self.playState = self.EnginePlay
else:
self.playState = self.EnginePause
@ -85,7 +84,7 @@ class AmarokStatus:
def controlsEnabled(self):
return self.allowControl
class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
class RequestHandler(http.server.SimpleHTTPRequestHandler):
"""We need our own 'RequestHandler, to handle the requests, that arrive at
our server."""
@ -144,10 +143,10 @@ class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# abort a request that has already been completed
# probably a refresh from the users browser
if qmap.has_key("reqid") and req_id == int(qmap["reqid"]):
if "reqid" in qmap and req_id == int(qmap["reqid"]):
return 0
if qmap.has_key("action"):
if "action" in qmap:
a = qmap["action"]
if a == "stop":
self._amarokStop()
@ -193,9 +192,9 @@ class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# get the sessions last reqid
last_req_id = 0
session_id = None
if qmap.has_key("sesid"):
if "sesid" in qmap:
session_id = qmap["sesid"]
if REQ_IDS.has_key(session_id):
if session_id in REQ_IDS:
last_req_id = REQ_IDS[session_id]
else:
REQ_IDS[session_id] = last_req_id
@ -229,15 +228,15 @@ class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# Surely there must be a better way that this:)
#
self.send_response(200)
if string.find(self.path, ".png") >= 0:
if ".png" in self.path:
self.send_header("content-type","image/png")
self.end_headers()
self._sendFile(self.path)
elif string.find(self.path, ".js") >= 0:
elif ".js" in self.path:
self.send_header("content-type","text/plain")
self.end_headers()
self._sendFile(self.path)
elif string.find(self.path, ".css") >= 0:
elif ".css" in self.path:
self.send_header("content-type","text/css")
self.end_headers()
self._sendFile(self.path)
@ -257,7 +256,7 @@ def main():
"""main is the starting-point for our script."""
global PLIST
PLIST = Playlist()
srv = BaseHTTPServer.HTTPServer(('',Globals.PORT),RequestHandler)
srv = http.server.HTTPServer(('',Globals.PORT),RequestHandler)
srv.serve_forever()

@ -4,11 +4,11 @@
# (c) 2005 Jonas Drewsen <kde@xspect.dk>
# (c) 2006 Peter C. Ndikuwera <pndiku@gmail.com>
#
# Depends on: Python 2.2, PyQt
# Depends on: Python 3, PyTQt
#
############################################################################
# Based on
# Python-Qt template script for Amarok
# PyTQt template script for Amarok
# (c) 2005 Mark Kretschmann <markey@web.de>
#
############################################################################
@ -20,7 +20,7 @@
#
############################################################################
import ConfigParser
import configparser
import os
import sys
import socket
@ -31,7 +31,7 @@ from time import sleep
import Globals
from Playlist import Playlist
import RequestHandler
import BaseHTTPServer
import http.server
from WebPublisher import *
import time
@ -40,9 +40,9 @@ import time
import string
try:
from qt import *
from PyTQt.qt import *
except:
os.popen( "kdialog --sorry 'PyQt (Qt bindings for Python) is required for this script.'" )
os.popen( "kdialog --sorry 'PyTQt (TQt bindings for Python) is required for this script.'" )
raise
@ -50,47 +50,47 @@ except:
debug_prefix = "[WebControl Script]"
class ConfigDialog( QDialog ):
class ConfigDialog( TQDialog ):
""" Configuration widget """
def __init__( self ):
QDialog.__init__( self )
self.setWFlags( Qt.WDestructiveClose )
TQDialog.__init__( self )
self.setWFlags( TQt.WDestructiveClose )
self.setCaption( "WebControl - Amarok" )
self.config = ConfigParser.ConfigParser()
self.config = configparser.ConfigParser()
allowControl = RequestHandler.AmarokStatus.allowControl
publish = RequestHandler.AmarokStatus.publish
try:
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
config.read( "webcontrolrc" )
allowControl = string.find(config.get( "General", "allowcontrol" ), "True") >= 0
publish = string.find(config.get( "General", "publish" ), "True") >= 0
allowControl = "True" in config.get( "General", "allowcontrol" )
publish = "True" in config.get( "General", "publish" )
except:
pass
self.lay = QHBoxLayout( self )
self.lay = TQHBoxLayout( self )
self.vbox = QVBox( self )
self.vbox = TQVBox( self )
self.lay.addWidget( self.vbox )
self.hbox1 = QHBox( self.vbox )
self.hbox1 = TQHBox( self.vbox )
self.allowControl = QCheckBox( QString("Allow control"), self.hbox1 )
self.allowControl = TQCheckBox( TQString("Allow control"), self.hbox1 )
self.allowControl.setChecked(allowControl)
self.hbox1 = QHBox( self.vbox )
self.hbox1 = TQHBox( self.vbox )
self.publish = QCheckBox( QString("Publish"), self.hbox1 )
self.publish = TQCheckBox( TQString("Publish"), self.hbox1 )
self.publish.setChecked(publish)
self.hbox = QHBox( self.vbox )
self.hbox = TQHBox( self.vbox )
self.ok = QPushButton( self.hbox )
self.ok = TQPushButton( self.hbox )
self.ok.setText( "Ok" )
self.cancel = QPushButton( self.hbox )
self.cancel = TQPushButton( self.hbox )
self.cancel.setText( "Cancel" )
self.cancel.setDefault( True )
@ -104,7 +104,7 @@ class ConfigDialog( QDialog ):
self.file = file( "webcontrolrc", 'w' )
self.config = ConfigParser.ConfigParser()
self.config = configparser.ConfigParser()
self.config.add_section( "General" )
self.config.set( "General", "allowcontrol", self.allowControl.isChecked() )
self.config.set( "General", "publish", self.publish.isChecked() )
@ -114,17 +114,17 @@ class ConfigDialog( QDialog ):
self.accept()
class Notification( QCustomEvent ):
__super_init = QCustomEvent.__init__
class Notification( TQCustomEvent ):
__super_init = TQCustomEvent.__init__
def __init__( self, str ):
self.__super_init(QCustomEvent.User + 1)
self.string = str
self.__super_init(TQCustomEvent.User + 1)
self.eventStr = str
class WebControl( QApplication ):
""" The main application, also sets up the Qt event loop """
class WebControl( TQApplication ):
""" The main application, also sets up the TQt event loop """
def __init__( self, args ):
QApplication.__init__( self, args )
TQApplication.__init__( self, args )
debug( "Started." )
self.readSettings()
@ -139,14 +139,14 @@ class WebControl( QApplication ):
while p_incr < 10:
try:
p_i=p_incr+Globals.PORT
self.srv = BaseHTTPServer.HTTPServer(('',p_i),RequestHandler.RequestHandler)
self.srv = http.server.HTTPServer(('',p_i),RequestHandler.RequestHandler)
publisher.port = p_i
break
except socket.error:
p_incr+=1
self.zeroconfPublishing()
self.snsrv = QSocketNotifier(self.srv.fileno(), QSocketNotifier.Read)
self.snsrv = TQSocketNotifier(self.srv.fileno(), TQSocketNotifier.Read)
self.snsrv.connect( self.snsrv, SIGNAL('activated(int)'), self.readSocket )
def readSocket( self ):
@ -155,12 +155,12 @@ class WebControl( QApplication ):
def readSettings( self ):
""" Reads settings from configuration file """
config = ConfigParser.ConfigParser()
config = configparser.ConfigParser()
config.read( "webcontrolrc" )
try:
RequestHandler.AmarokStatus.allowControl = string.find(config.get( "General", "allowcontrol" ), "True") >= 0
RequestHandler.AmarokStatus.publish = string.find(config.get( "General", "publish" ), "True") >= 0
RequestHandler.AmarokStatus.allowControl = "True" in config.get( "General", "allowcontrol" )
RequestHandler.AmarokStatus.publish = "True" in config.get( "General", "publish" )
except:
debug( "No config file found, using defaults." )
@ -195,32 +195,32 @@ class WebControl( QApplication ):
def customEvent( self, notification ):
""" Handles the notifications """
string = QString(notification.string)
debug( "Received notification: " + str( string ) )
eventStr = TQString(notification.eventStr)
debug( "Received notification: " + str( eventStr ) )
if string.contains( "configure" ):
if eventStr.contains( "configure" ):
self.configure()
elif string.contains( "exit" ):
elif eventStr.contains( "exit" ):
cleanup(None,None)
elif string.contains( "engineStateChange: play" ):
elif eventStr.contains( "engineStateChange: play" ):
self.engineStatePlay()
elif string.contains( "engineStateChange: idle" ):
elif eventStr.contains( "engineStateChange: idle" ):
self.engineStateIdle()
elif string.contains( "engineStateChange: pause" ):
elif eventStr.contains( "engineStateChange: pause" ):
self.engineStatePause()
elif string.contains( "engineStateChange: empty" ):
elif eventStr.contains( "engineStateChange: empty" ):
self.engineStatePause()
elif string.contains( "trackChange" ):
elif eventStr.contains( "trackChange" ):
self.trackChange()
else:
debug( "Unknown notification: " + str(string) + " -> ignoring")
debug( "Unknown notification: " + str(eventStr) + " -> ignoring")
# Notification callbacks. Implement these functions to react to specific notification
# events from Amarok:
@ -263,13 +263,12 @@ class WebControl( QApplication ):
############################################################################
def debug( message ):
""" Prints debug message to stdout """
print debug_prefix + " " + message
print(debug_prefix + " " + message)
def cleanup(sig,frame):
publisher.shutdown()

@ -20,7 +20,7 @@ import string
temp=sys.path[:]
sys.path.insert(0,os.path.abspath(os.path.dirname(sys.argv[0])+'/../common'))
if not os.getenv("TDEDIR") is None: sys.path.insert(0,os.getenv("TDEDIR")+"/share/apps/amarok/scripts/common")
if not os.getenv("TDEDIRS") is None: sys.path=[p+"/share/apps/amarok/scripts/common" for p in string.split(os.getenv("TDEDIRS"),os.pathsep)]+sys.path
if not os.getenv("TDEDIRS") is None: sys.path=[p+"/share/apps/amarok/scripts/common" for p in os.pathsep.split(os.getenv("TDEDIRS"))]+sys.path
from Publisher import *
sys.path=temp

Loading…
Cancel
Save