Applied fix: "Remove redundant parameters"

This commit is contained in:
Uriziel 2014-07-03 00:20:31 +02:00
parent 6a191f8e24
commit d6d09e403c
18 changed files with 358 additions and 356 deletions

View File

@ -515,7 +515,7 @@ class NSISScript(object):
installFiles = self.prepareInstallListTemplate(fileList) installFiles = self.prepareInstallListTemplate(fileList)
uninstallFiles = self.prepareDeleteListTemplate(fileList) uninstallFiles = self.prepareDeleteListTemplate(fileList)
if(os.path.isfile(SETUP_SCRIPT_PATH)): if os.path.isfile(SETUP_SCRIPT_PATH):
raise RuntimeError("Cannot create setup script, file exists at {}".format(SETUP_SCRIPT_PATH)) raise RuntimeError("Cannot create setup script, file exists at {}".format(SETUP_SCRIPT_PATH))
contents = Template(NSIS_SCRIPT_TEMPLATE).substitute( contents = Template(NSIS_SCRIPT_TEMPLATE).substitute(
version = syncplay.version, version = syncplay.version,
@ -527,7 +527,7 @@ class NSISScript(object):
outfile.write(contents) outfile.write(contents)
def compile(self): def compile(self):
if(not os.path.isfile(NSIS_COMPILE)): if not os.path.isfile(NSIS_COMPILE):
return "makensis.exe not found, won't create the installer" return "makensis.exe not found, won't create the installer"
subproc = subprocess.Popen([NSIS_COMPILE, SETUP_SCRIPT_PATH], env=os.environ) subproc = subprocess.Popen([NSIS_COMPILE, SETUP_SCRIPT_PATH], env=os.environ)
subproc.communicate() subproc.communicate()
@ -543,7 +543,7 @@ class NSISScript(object):
totalSize += sum(os.path.getsize(os.path.join(root, file_)) for file_ in files) totalSize += sum(os.path.getsize(os.path.join(root, file_)) for file_ in files)
for file_ in files: for file_ in files:
new_root = root.replace(OUT_DIR, "").strip("\\") new_root = root.replace(OUT_DIR, "").strip("\\")
if(not fileList.has_key(new_root)): if not fileList.has_key(new_root):
fileList[new_root] = [] fileList[new_root] = []
fileList[new_root].append(file_) fileList[new_root].append(file_)
return fileList, totalSize return fileList, totalSize

View File

@ -62,16 +62,16 @@ class SyncplayClient(object):
self.userlist = SyncplayUserlist(self.ui, self) self.userlist = SyncplayUserlist(self.ui, self)
self._protocol = None self._protocol = None
self._player = None self._player = None
if(config['room'] == None or config['room'] == ''): if config['room'] == None or config['room'] == '':
config['room'] = config['name'] # ticket #58 config['room'] = config['name'] # ticket #58
self.defaultRoom = config['room'] self.defaultRoom = config['room']
self.playerPositionBeforeLastSeek = 0.0 self.playerPositionBeforeLastSeek = 0.0
self.setUsername(config['name']) self.setUsername(config['name'])
self.setRoom(config['room']) self.setRoom(config['room'])
if(config['password']): if config['password']:
config['password'] = hashlib.md5(config['password']).hexdigest() config['password'] = hashlib.md5(config['password']).hexdigest()
self._serverPassword = config['password'] self._serverPassword = config['password']
if(not config['file']): if not config['file']:
self.__getUserlistOnLogon = True self.__getUserlistOnLogon = True
else: else:
self.__getUserlistOnLogon = False self.__getUserlistOnLogon = False
@ -99,7 +99,7 @@ class SyncplayClient(object):
self._protocol = protocol self._protocol = protocol
def destroyProtocol(self): def destroyProtocol(self):
if(self._protocol): if self._protocol:
self._protocol.drop() self._protocol.drop()
self._protocol = None self._protocol = None
@ -112,14 +112,14 @@ class SyncplayClient(object):
self._askPlayerTimer.start(when) self._askPlayerTimer.start(when)
def askPlayer(self): def askPlayer(self):
if(not self._running): if not self._running:
return return
if(self._player): if self._player:
self._player.askForStatus() self._player.askForStatus()
self.checkIfConnected() self.checkIfConnected()
def checkIfConnected(self): def checkIfConnected(self):
if(self._lastGlobalUpdate and self._protocol and time.time() - self._lastGlobalUpdate > constants.PROTOCOL_TIMEOUT): if self._lastGlobalUpdate and self._protocol and time.time() - self._lastGlobalUpdate > constants.PROTOCOL_TIMEOUT:
self._lastGlobalUpdate = None self._lastGlobalUpdate = None
self.ui.showErrorMessage(getMessage("server-timeout-error")) self.ui.showErrorMessage(getMessage("server-timeout-error"))
self._protocol.drop() self._protocol.drop()
@ -138,10 +138,10 @@ class SyncplayClient(object):
pauseChange, seeked = self._determinePlayerStateChange(paused, position) pauseChange, seeked = self._determinePlayerStateChange(paused, position)
self._playerPosition = position self._playerPosition = position
self._playerPaused = paused self._playerPaused = paused
if(self._lastGlobalUpdate): if self._lastGlobalUpdate:
self._lastPlayerUpdate = time.time() self._lastPlayerUpdate = time.time()
if((pauseChange or seeked) and self._protocol): if (pauseChange or seeked) and self._protocol:
if(seeked): if seeked:
self.playerPositionBeforeLastSeek = self.getGlobalPosition() self.playerPositionBeforeLastSeek = self.getGlobalPosition()
self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), seeked, None, True) self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), seeked, None, True)
@ -152,13 +152,13 @@ class SyncplayClient(object):
else: else:
position = self.getPlayerPosition() position = self.getPlayerPosition()
pauseChange, _ = self._determinePlayerStateChange(paused, position) pauseChange, _ = self._determinePlayerStateChange(paused, position)
if(self._lastGlobalUpdate): if self._lastGlobalUpdate:
return position, paused, _, pauseChange return position, paused, _, pauseChange
else: else:
return None, None, None, None return None, None, None, None
def _initPlayerState(self, position, paused): def _initPlayerState(self, position, paused):
if(self.userlist.currentUser.file): if self.userlist.currentUser.file:
self.setPosition(position) self.setPosition(position)
self._player.setPaused(paused) self._player.setPaused(paused)
madeChangeOnPlayer = True madeChangeOnPlayer = True
@ -192,7 +192,7 @@ class SyncplayClient(object):
def _serverSeeked(self, position, setBy): def _serverSeeked(self, position, setBy):
hideFromOSD = not constants.SHOW_SAME_ROOM_OSD hideFromOSD = not constants.SHOW_SAME_ROOM_OSD
if(self.getUsername() <> setBy): if self.getUsername() <> setBy:
self.playerPositionBeforeLastSeek = self.getPlayerPosition() self.playerPositionBeforeLastSeek = self.getPlayerPosition()
self.setPosition(position) self.setPosition(position)
madeChangeOnPlayer = True madeChangeOnPlayer = True
@ -204,11 +204,11 @@ class SyncplayClient(object):
def _slowDownToCoverTimeDifference(self, diff, setBy): def _slowDownToCoverTimeDifference(self, diff, setBy):
hideFromOSD = not constants.SHOW_SLOWDOWN_OSD hideFromOSD = not constants.SHOW_SLOWDOWN_OSD
if(self._config['slowdownThreshold'] < diff and not self._speedChanged): if self._config['slowdownThreshold'] < diff and not self._speedChanged:
self._player.setSpeed(constants.SLOWDOWN_RATE) self._player.setSpeed(constants.SLOWDOWN_RATE)
self._speedChanged = True self._speedChanged = True
self.ui.showMessage(getMessage("slowdown-notification").format(setBy), hideFromOSD) self.ui.showMessage(getMessage("slowdown-notification").format(setBy), hideFromOSD)
elif(self._speedChanged and diff < constants.SLOWDOWN_RESET_THRESHOLD): elif self._speedChanged and diff < constants.SLOWDOWN_RESET_THRESHOLD:
self._player.setSpeed(1.00) self._player.setSpeed(1.00)
self._speedChanged = False self._speedChanged = False
self.ui.showMessage(getMessage("revert-notification"), hideFromOSD) self.ui.showMessage(getMessage("revert-notification"), hideFromOSD)
@ -219,39 +219,39 @@ class SyncplayClient(object):
madeChangeOnPlayer = False madeChangeOnPlayer = False
pauseChanged = paused != self.getGlobalPaused() pauseChanged = paused != self.getGlobalPaused()
diff = self.getPlayerPosition() - position diff = self.getPlayerPosition() - position
if(self._lastGlobalUpdate is None): if self._lastGlobalUpdate is None:
madeChangeOnPlayer = self._initPlayerState(position, paused) madeChangeOnPlayer = self._initPlayerState(position, paused)
self._globalPaused = paused self._globalPaused = paused
self._globalPosition = position self._globalPosition = position
self._lastGlobalUpdate = time.time() self._lastGlobalUpdate = time.time()
if (doSeek): if doSeek:
madeChangeOnPlayer = self._serverSeeked(position, setBy) madeChangeOnPlayer = self._serverSeeked(position, setBy)
if (diff > self._config['rewindThreshold'] and not doSeek and not self._config['rewindThreshold'] == 0.0): if diff > self._config['rewindThreshold'] and not doSeek and not self._config['rewindThreshold'] == 0.0:
madeChangeOnPlayer = self._rewindPlayerDueToTimeDifference(position, setBy) madeChangeOnPlayer = self._rewindPlayerDueToTimeDifference(position, setBy)
if (self._player.speedSupported and not doSeek and not paused): if self._player.speedSupported and not doSeek and not paused:
if (self._config['slowMeOnDesync'] == constants.OPTION_ALWAYS or (self._config['slowMeOnDesync'] == constants.OPTION_AUTO and self._player.speedRecommended)): if self._config['slowMeOnDesync'] == constants.OPTION_ALWAYS or (self._config['slowMeOnDesync'] == constants.OPTION_AUTO and self._player.speedRecommended):
madeChangeOnPlayer = self._slowDownToCoverTimeDifference(diff, setBy) madeChangeOnPlayer = self._slowDownToCoverTimeDifference(diff, setBy)
if (paused == False and pauseChanged): if paused == False and pauseChanged:
madeChangeOnPlayer = self._serverUnpaused(setBy) madeChangeOnPlayer = self._serverUnpaused(setBy)
elif (paused == True and pauseChanged): elif paused == True and pauseChanged:
madeChangeOnPlayer = self._serverPaused(setBy) madeChangeOnPlayer = self._serverPaused(setBy)
return madeChangeOnPlayer return madeChangeOnPlayer
def _executePlaystateHooks(self, position, paused, doSeek, setBy, messageAge): def _executePlaystateHooks(self, position, paused, doSeek, setBy, messageAge):
if(self.userlist.hasRoomStateChanged() and not paused): if self.userlist.hasRoomStateChanged() and not paused:
self._warnings.checkWarnings() self._warnings.checkWarnings()
self.userlist.roomStateConfirmed() self.userlist.roomStateConfirmed()
def updateGlobalState(self, position, paused, doSeek, setBy, messageAge): def updateGlobalState(self, position, paused, doSeek, setBy, messageAge):
if(self.__getUserlistOnLogon): if self.__getUserlistOnLogon:
self.__getUserlistOnLogon = False self.__getUserlistOnLogon = False
self.getUserList() self.getUserList()
madeChangeOnPlayer = False madeChangeOnPlayer = False
if(not paused): if not paused:
position += messageAge position += messageAge
if(self._player): if self._player:
madeChangeOnPlayer = self._changePlayerStateAccordingToGlobalState(position, paused, doSeek, setBy) madeChangeOnPlayer = self._changePlayerStateAccordingToGlobalState(position, paused, doSeek, setBy)
if(madeChangeOnPlayer): if madeChangeOnPlayer:
self.askPlayer() self.askPlayer()
self._executePlaystateHooks(position, paused, doSeek, setBy, messageAge) self._executePlaystateHooks(position, paused, doSeek, setBy, messageAge)
@ -264,29 +264,29 @@ class SyncplayClient(object):
self.ui.showMessage(getMessage("current-offset-notification").format(self._userOffset)) self.ui.showMessage(getMessage("current-offset-notification").format(self._userOffset))
def onDisconnect(self): def onDisconnect(self):
if(self._config['pauseOnLeave']): if self._config['pauseOnLeave']:
self.setPaused(True) self.setPaused(True)
def removeUser(self, username): def removeUser(self, username):
if(self.userlist.isUserInYourRoom(username)): if self.userlist.isUserInYourRoom(username):
self.onDisconnect() self.onDisconnect()
self.userlist.removeUser(username) self.userlist.removeUser(username)
def getPlayerPosition(self): def getPlayerPosition(self):
if(not self._lastPlayerUpdate): if not self._lastPlayerUpdate:
if(self._lastGlobalUpdate): if self._lastGlobalUpdate:
return self.getGlobalPosition() return self.getGlobalPosition()
else: else:
return 0.0 return 0.0
position = self._playerPosition position = self._playerPosition
if(not self._playerPaused): if not self._playerPaused:
diff = time.time() - self._lastPlayerUpdate diff = time.time() - self._lastPlayerUpdate
position += diff position += diff
return position return position
def getPlayerPaused(self): def getPlayerPaused(self):
if(not self._lastPlayerUpdate): if not self._lastPlayerUpdate:
if(self._lastGlobalUpdate): if self._lastGlobalUpdate:
return self.getGlobalPaused() return self.getGlobalPaused()
else: else:
return True return True
@ -301,7 +301,7 @@ class SyncplayClient(object):
return position return position
def getGlobalPaused(self): def getGlobalPaused(self):
if(not self._lastGlobalUpdate): if not self._lastGlobalUpdate:
return True return True
return self._globalPaused return self._globalPaused
@ -318,19 +318,19 @@ class SyncplayClient(object):
self.sendFile() self.sendFile()
def __executePrivacySettings(self, filename, size): def __executePrivacySettings(self, filename, size):
if (self._config['filenamePrivacyMode'] == PRIVACY_SENDHASHED_MODE): if self._config['filenamePrivacyMode'] == PRIVACY_SENDHASHED_MODE:
filename = utils.hashFilename(filename) filename = utils.hashFilename(filename)
elif (self._config['filenamePrivacyMode'] == PRIVACY_DONTSEND_MODE): elif self._config['filenamePrivacyMode'] == PRIVACY_DONTSEND_MODE:
filename = PRIVACY_HIDDENFILENAME filename = PRIVACY_HIDDENFILENAME
if (self._config['filesizePrivacyMode'] == PRIVACY_SENDHASHED_MODE): if self._config['filesizePrivacyMode'] == PRIVACY_SENDHASHED_MODE:
size = utils.hashFilesize(size) size = utils.hashFilesize(size)
elif (self._config['filesizePrivacyMode'] == PRIVACY_DONTSEND_MODE): elif self._config['filesizePrivacyMode'] == PRIVACY_DONTSEND_MODE:
size = 0 size = 0
return filename, size return filename, size
def sendFile(self): def sendFile(self):
file_ = self.userlist.currentUser.file file_ = self.userlist.currentUser.file
if(self._protocol and self._protocol.logged and file_): if self._protocol and self._protocol.logged and file_:
self._protocol.sendFileSetting(file_) self._protocol.sendFileSetting(file_)
def setUsername(self, username): def setUsername(self, username):
@ -350,7 +350,7 @@ class SyncplayClient(object):
def sendRoom(self): def sendRoom(self):
room = self.userlist.currentUser.room room = self.userlist.currentUser.room
if(self._protocol and self._protocol.logged and room): if self._protocol and self._protocol.logged and room:
self._protocol.sendRoomSetting(room) self._protocol.sendRoomSetting(room)
self.getUserList() self.getUserList()
@ -358,7 +358,7 @@ class SyncplayClient(object):
return self.userlist.currentUser.room return self.userlist.currentUser.room
def getUserList(self): def getUserList(self):
if(self._protocol and self._protocol.logged): if self._protocol and self._protocol.logged:
self._protocol.sendList() self._protocol.sendList()
def showUserList(self): def showUserList(self):
@ -369,14 +369,14 @@ class SyncplayClient(object):
def setPosition(self, position): def setPosition(self, position):
position += self.getUserOffset() position += self.getUserOffset()
if(self._player and self.userlist.currentUser.file): if self._player and self.userlist.currentUser.file:
if(position < 0): if position < 0:
position = 0 position = 0
self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), True, None, True) self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), True, None, True)
self._player.setPosition(position) self._player.setPosition(position)
def setPaused(self, paused): def setPaused(self, paused):
if(self._player and self.userlist.currentUser.file): if self._player and self.userlist.currentUser.file:
self._player.setPaused(paused) self._player.setPaused(paused)
def start(self, host, port): def start(self, host, port):
@ -403,7 +403,7 @@ class SyncplayClient(object):
if self.ui: if self.ui:
self.ui.drop() self.ui.drop()
reactor.callLater(0.1, reactor.stop) reactor.callLater(0.1, reactor.stop)
if(promptForAction): if promptForAction:
self.ui.promptFor(getMessage("enter-to-exit-prompt")) self.ui.promptFor(getMessage("enter-to-exit-prompt"))
class _WarningManager(object): class _WarningManager(object):
@ -413,11 +413,13 @@ class SyncplayClient(object):
self._ui = ui self._ui = ui
self._warnings = { self._warnings = {
"room-files-not-same": { "room-files-not-same": {
"timer": task.LoopingCall(self.__displayMessageOnOSD, ("room-files-not-same"),), "timer": task.LoopingCall(self.__displayMessageOnOSD,
"room-files-not-same",),
"displayedFor": 0, "displayedFor": 0,
}, },
"alone-in-the-room": { "alone-in-the-room": {
"timer": task.LoopingCall(self.__displayMessageOnOSD, ("alone-in-the-room"),), "timer": task.LoopingCall(self.__displayMessageOnOSD,
"alone-in-the-room",),
"displayedFor": 0, "displayedFor": 0,
}, },
} }
@ -426,23 +428,23 @@ class SyncplayClient(object):
self._checkRoomForSameFiles() self._checkRoomForSameFiles()
def _checkRoomForSameFiles(self): def _checkRoomForSameFiles(self):
if (not self._userlist.areAllFilesInRoomSame()): if not self._userlist.areAllFilesInRoomSame():
self._ui.showMessage(getMessage("room-files-not-same"), True) self._ui.showMessage(getMessage("room-files-not-same"), True)
if(constants.SHOW_OSD_WARNINGS and not self._warnings["room-files-not-same"]['timer'].running): if constants.SHOW_OSD_WARNINGS and not self._warnings["room-files-not-same"]['timer'].running:
self._warnings["room-files-not-same"]['timer'].start(constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL, True) self._warnings["room-files-not-same"]['timer'].start(constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL, True)
elif(self._warnings["room-files-not-same"]['timer'].running): elif self._warnings["room-files-not-same"]['timer'].running:
self._warnings["room-files-not-same"]['timer'].stop() self._warnings["room-files-not-same"]['timer'].stop()
def _checkIfYouReAloneInTheRoom(self): def _checkIfYouReAloneInTheRoom(self):
if (self._userlist.areYouAloneInRoom()): if self._userlist.areYouAloneInRoom():
self._ui.showMessage(getMessage("alone-in-the-room"), True) self._ui.showMessage(getMessage("alone-in-the-room"), True)
if(constants.SHOW_OSD_WARNINGS and not self._warnings["alone-in-the-room"]['timer'].running): if constants.SHOW_OSD_WARNINGS and not self._warnings["alone-in-the-room"]['timer'].running:
self._warnings["alone-in-the-room"]['timer'].start(constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL, True) self._warnings["alone-in-the-room"]['timer'].start(constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL, True)
elif(self._warnings["alone-in-the-room"]['timer'].running): elif self._warnings["alone-in-the-room"]['timer'].running:
self._warnings["alone-in-the-room"]['timer'].stop() self._warnings["alone-in-the-room"]['timer'].stop()
def __displayMessageOnOSD(self, warningName): def __displayMessageOnOSD(self, warningName):
if (constants.OSD_WARNING_MESSAGE_DURATION > self._warnings[warningName]["displayedFor"]): if constants.OSD_WARNING_MESSAGE_DURATION > self._warnings[warningName]["displayedFor"]:
self._ui.showOSDMessage(getMessage(warningName), constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL) self._ui.showOSDMessage(getMessage(warningName), constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL)
self._warnings[warningName]["displayedFor"] += constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL self._warnings[warningName]["displayedFor"] += constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL
else: else:
@ -466,7 +468,7 @@ class SyncplayUser(object):
self.file = file_ self.file = file_
def isFileSame(self, file_): def isFileSame(self, file_):
if(not self.file): if not self.file:
return False return False
sameName = utils.sameFilename(self.file['name'], file_['name']) sameName = utils.sameFilename(self.file['name'], file_['name'])
sameSize = utils.sameFilesize(self.file['size'], file_['size']) sameSize = utils.sameFilesize(self.file['size'], file_['size'])
@ -477,7 +479,7 @@ class SyncplayUser(object):
return self.username.lower() < other.username.lower() return self.username.lower() < other.username.lower()
def __repr__(self, *args, **kwargs): def __repr__(self, *args, **kwargs):
if(self.file): if self.file:
return "{}: {} ({}, {})".format(self.username, self.file['name'], self.file['duration'], self.file['size']) return "{}: {} ({}, {})".format(self.username, self.file['name'], self.file['duration'], self.file['size'])
else: else:
return "{}".format(self.username) return "{}".format(self.username)
@ -491,60 +493,60 @@ class SyncplayUserlist(object):
self._roomUsersChanged = True self._roomUsersChanged = True
def isRoomSame(self, room): def isRoomSame(self, room):
if (room and self.currentUser.room and self.currentUser.room == room): if room and self.currentUser.room and self.currentUser.room == room:
return True return True
else: else:
return False return False
def __showUserChangeMessage(self, username, room, file_, oldRoom=None): def __showUserChangeMessage(self, username, room, file_, oldRoom=None):
if(room): if room:
if self.isRoomSame(room) or self.isRoomSame(oldRoom): if self.isRoomSame(room) or self.isRoomSame(oldRoom):
showOnOSD = constants.SHOW_SAME_ROOM_OSD showOnOSD = constants.SHOW_SAME_ROOM_OSD
else: else:
showOnOSD = constants.SHOW_DIFFERENT_ROOM_OSD showOnOSD = constants.SHOW_DIFFERENT_ROOM_OSD
hideFromOSD = not showOnOSD hideFromOSD = not showOnOSD
if(room and not file_): if room and not file_:
message = getMessage("room-join-notification").format(username, room) message = getMessage("room-join-notification").format(username, room)
self.ui.showMessage(message, hideFromOSD) self.ui.showMessage(message, hideFromOSD)
elif (room and file_): elif room and file_:
duration = utils.formatTime(file_['duration']) duration = utils.formatTime(file_['duration'])
message = getMessage("playing-notification").format(username, file_['name'], duration) message = getMessage("playing-notification").format(username, file_['name'], duration)
if(self.currentUser.room <> room or self.currentUser.username == username): if self.currentUser.room <> room or self.currentUser.username == username:
message += getMessage("playing-notification/room-addendum").format(room) message += getMessage("playing-notification/room-addendum").format(room)
self.ui.showMessage(message, hideFromOSD) self.ui.showMessage(message, hideFromOSD)
if(self.currentUser.file and not self.currentUser.isFileSame(file_) and self.currentUser.room == room): if self.currentUser.file and not self.currentUser.isFileSame(file_) and self.currentUser.room == room:
message = getMessage("file-different-notification").format(username) message = getMessage("file-different-notification").format(username)
self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS) self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS)
differences = [] differences = []
differentName = not utils.sameFilename(self.currentUser.file['name'], file_['name']) differentName = not utils.sameFilename(self.currentUser.file['name'], file_['name'])
differentSize = not utils.sameFilesize(self.currentUser.file['size'], file_['size']) differentSize = not utils.sameFilesize(self.currentUser.file['size'], file_['size'])
differentDuration = not utils.sameFileduration(self.currentUser.file['duration'], file_['duration']) differentDuration = not utils.sameFileduration(self.currentUser.file['duration'], file_['duration'])
if(differentName): if differentName:
differences.append("filename") differences.append("filename")
if(differentSize): if differentSize:
differences.append("size") differences.append("size")
if(differentDuration): if differentDuration:
differences.append("duration") differences.append("duration")
message = getMessage("file-differences-notification") + ", ".join(differences) message = getMessage("file-differences-notification") + ", ".join(differences)
self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS) self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS)
def addUser(self, username, room, file_, noMessage=False): def addUser(self, username, room, file_, noMessage=False):
if(username == self.currentUser.username): if username == self.currentUser.username:
return return
user = SyncplayUser(username, room, file_) user = SyncplayUser(username, room, file_)
self._users[username] = user self._users[username] = user
if(not noMessage): if not noMessage:
self.__showUserChangeMessage(username, room, file_) self.__showUserChangeMessage(username, room, file_)
self.userListChange() self.userListChange()
def removeUser(self, username): def removeUser(self, username):
hideFromOSD = not constants.SHOW_DIFFERENT_ROOM_OSD hideFromOSD = not constants.SHOW_DIFFERENT_ROOM_OSD
if(self._users.has_key(username)): if self._users.has_key(username):
user = self._users[username] user = self._users[username]
if user.room: if user.room:
if self.isRoomSame(user.room): if self.isRoomSame(user.room):
hideFromOSD = not constants.SHOW_SAME_ROOM_OSD hideFromOSD = not constants.SHOW_SAME_ROOM_OSD
if(self._users.has_key(username)): if self._users.has_key(username):
self._users.pop(username) self._users.pop(username)
message = getMessage("left-notification").format(username) message = getMessage("left-notification").format(username)
self.ui.showMessage(message, hideFromOSD) self.ui.showMessage(message, hideFromOSD)
@ -553,20 +555,20 @@ class SyncplayUserlist(object):
self.userListChange() self.userListChange()
def __displayModUserMessage(self, username, room, file_, user, oldRoom): def __displayModUserMessage(self, username, room, file_, user, oldRoom):
if (file_ and not user.isFileSame(file_)): if file_ and not user.isFileSame(file_):
self.__showUserChangeMessage(username, room, file_, oldRoom) self.__showUserChangeMessage(username, room, file_, oldRoom)
elif (room and room != user.room): elif room and room != user.room:
self.__showUserChangeMessage(username, room, None, oldRoom) self.__showUserChangeMessage(username, room, None, oldRoom)
def modUser(self, username, room, file_): def modUser(self, username, room, file_):
if(self._users.has_key(username)): if self._users.has_key(username):
user = self._users[username] user = self._users[username]
oldRoom = user.room if user.room else None oldRoom = user.room if user.room else None
self.__displayModUserMessage(username, room, file_, user, oldRoom) self.__displayModUserMessage(username, room, file_, user, oldRoom)
user.room = room user.room = room
if file_: if file_:
user.file = file_ user.file = file_
elif(username == self.currentUser.username): elif username == self.currentUser.username:
self.__showUserChangeMessage(username, room, file_) self.__showUserChangeMessage(username, room, file_)
else: else:
self.addUser(username, room, file_) self.addUser(username, room, file_)
@ -574,19 +576,19 @@ class SyncplayUserlist(object):
def areAllFilesInRoomSame(self): def areAllFilesInRoomSame(self):
for user in self._users.itervalues(): for user in self._users.itervalues():
if(user.room == self.currentUser.room and user.file and not self.currentUser.isFileSame(user.file)): if user.room == self.currentUser.room and user.file and not self.currentUser.isFileSame(user.file):
return False return False
return True return True
def areYouAloneInRoom(self): def areYouAloneInRoom(self):
for user in self._users.itervalues(): for user in self._users.itervalues():
if(user.room == self.currentUser.room): if user.room == self.currentUser.room:
return False return False
return True return True
def isUserInYourRoom(self, username): def isUserInYourRoom(self, username):
for user in self._users.itervalues(): for user in self._users.itervalues():
if(user.username == username and user.room == self.currentUser.room): if user.username == username and user.room == self.currentUser.room:
return True return True
return False return False
@ -603,10 +605,10 @@ class SyncplayUserlist(object):
def showUserList(self): def showUserList(self):
rooms = {} rooms = {}
for user in self._users.itervalues(): for user in self._users.itervalues():
if(user.room not in rooms): if user.room not in rooms:
rooms[user.room] = [] rooms[user.room] = []
rooms[user.room].append(user) rooms[user.room].append(user)
if(self.currentUser.room not in rooms): if self.currentUser.room not in rooms:
rooms[self.currentUser.room] = [] rooms[self.currentUser.room] = []
rooms[self.currentUser.room].append(self.currentUser) rooms[self.currentUser.room].append(self.currentUser)
rooms = self.sortList(rooms) rooms = self.sortList(rooms)
@ -628,14 +630,14 @@ class UiManager(object):
self.lastError = "" self.lastError = ""
def showMessage(self, message, noPlayer=False, noTimestamp=False): def showMessage(self, message, noPlayer=False, noTimestamp=False):
if(not noPlayer): self.showOSDMessage(message) if not noPlayer: self.showOSDMessage(message)
self.__ui.showMessage(message, noTimestamp) self.__ui.showMessage(message, noTimestamp)
def showUserList(self, currentUser, rooms): def showUserList(self, currentUser, rooms):
self.__ui.showUserList(currentUser, rooms) self.__ui.showUserList(currentUser, rooms)
def showOSDMessage(self, message, duration=constants.OSD_DURATION): def showOSDMessage(self, message, duration=constants.OSD_DURATION):
if(constants.SHOW_OSD and self._client._player): if constants.SHOW_OSD and self._client._player:
self._client._player.displayMessage(message, duration * 1000) self._client._player.displayMessage(message, duration * 1000)
def showErrorMessage(self, message, criticalerror=False): def showErrorMessage(self, message, criticalerror=False):

View File

@ -8,7 +8,7 @@ class SyncplayClientManager(object):
from syncplay.client import SyncplayClient #Imported later, so the proper reactor is installed from syncplay.client import SyncplayClient #Imported later, so the proper reactor is installed
interface = ui.getUi(graphical=not config["noGui"]) interface = ui.getUi(graphical=not config["noGui"])
syncplayClient = SyncplayClient(config["playerClass"], interface, config) syncplayClient = SyncplayClient(config["playerClass"], interface, config)
if(syncplayClient): if syncplayClient:
interface.addClient(syncplayClient) interface.addClient(syncplayClient)
syncplayClient.start(config['host'], config['port']) syncplayClient.start(config['host'], config['port'])
else: else:

View File

@ -294,20 +294,20 @@ def setLanguage(lang):
messages["current"] = lang messages["current"] = lang
def getMessage(type_, locale=None): def getMessage(type_, locale=None):
if(constants.SHOW_BUTTON_LABELS == False): if constants.SHOW_BUTTON_LABELS == False:
if("-guibuttonlabel" in type_): if "-guibuttonlabel" in type_:
return "" return ""
if(constants.SHOW_TOOLTIPS == False): if constants.SHOW_TOOLTIPS == False:
if("-tooltip" in type_): if "-tooltip" in type_:
return "" return ""
lang = messages["current"] lang = messages["current"]
if(locale and messages.has_key(locale)): if locale and messages.has_key(locale):
if(messages[locale].has_key(type_)): if messages[locale].has_key(type_):
return unicode(messages[locale][type_]) return unicode(messages[locale][type_])
if(lang and messages.has_key(lang)): if lang and messages.has_key(lang):
if(messages[lang].has_key(type_)): if messages[lang].has_key(type_):
return unicode(messages[lang][type_]) return unicode(messages[lang][type_])
if(messages["en"].has_key(type_)): if messages["en"].has_key(type_):
return unicode(messages["en"][type_]) return unicode(messages["en"][type_])
else: else:
raise KeyError() raise KeyError()

View File

@ -33,7 +33,7 @@ class MpcHcApi:
def waitForFileStateReady(f): #@NoSelf def waitForFileStateReady(f): #@NoSelf
@wraps(f) @wraps(f)
def wrapper(self, *args, **kwds): def wrapper(self, *args, **kwds):
if(not self.__locks.fileReady.wait(constants.MPC_LOCK_WAIT_TIME)): if not self.__locks.fileReady.wait(constants.MPC_LOCK_WAIT_TIME):
raise self.PlayerNotReadyException() raise self.PlayerNotReadyException()
return f(self, *args, **kwds) return f(self, *args, **kwds)
return wrapper return wrapper
@ -41,7 +41,7 @@ class MpcHcApi:
def startMpc(self, path, args=()): def startMpc(self, path, args=()):
args = "%s /slave %s" % (" ".join(args), str(self.__listener.hwnd)) args = "%s /slave %s" % (" ".join(args), str(self.__listener.hwnd))
win32api.ShellExecute(0, "open", path, args, None, 1) win32api.ShellExecute(0, "open", path, args, None, 1)
if(not self.__locks.mpcStart.wait(constants.MPC_OPEN_MAX_WAIT_TIME)): if not self.__locks.mpcStart.wait(constants.MPC_OPEN_MAX_WAIT_TIME):
raise self.NoSlaveDetectedException(getMessage("mpc-slave-error")) raise self.NoSlaveDetectedException(getMessage("mpc-slave-error"))
self.__mpcExistenceChecking.start() self.__mpcExistenceChecking.start()
@ -49,7 +49,7 @@ class MpcHcApi:
self.__listener.SendCommand(self.CMD_OPENFILE, filePath) self.__listener.SendCommand(self.CMD_OPENFILE, filePath)
def isPaused(self): def isPaused(self):
return (self.playState <> self.__MPC_PLAYSTATE.PS_PLAY and self.playState <> None) return self.playState <> self.__MPC_PLAYSTATE.PS_PLAY and self.playState <> None
def askForVersion(self): def askForVersion(self):
self.__listener.SendCommand(self.CMD_GETVERSION) self.__listener.SendCommand(self.CMD_GETVERSION)
@ -95,59 +95,59 @@ class MpcHcApi:
self.__listener.SendCommand(cmd, value) self.__listener.SendCommand(cmd, value)
def handleCommand(self, cmd, value): def handleCommand(self, cmd, value):
if (cmd == self.CMD_CONNECT): if cmd == self.CMD_CONNECT:
self.__listener.mpcHandle = int(value) self.__listener.mpcHandle = int(value)
self.__locks.mpcStart.set() self.__locks.mpcStart.set()
if(self.callbacks.onConnected): if self.callbacks.onConnected:
thread.start_new_thread(self.callbacks.onConnected, ()) thread.start_new_thread(self.callbacks.onConnected, ())
elif(cmd == self.CMD_STATE): elif cmd == self.CMD_STATE:
self.loadState = int(value) self.loadState = int(value)
fileNotReady = self.loadState == self.__MPC_LOADSTATE.MLS_CLOSING or self.loadState == self.__MPC_LOADSTATE.MLS_LOADING fileNotReady = self.loadState == self.__MPC_LOADSTATE.MLS_CLOSING or self.loadState == self.__MPC_LOADSTATE.MLS_LOADING
if(fileNotReady): if fileNotReady:
self.playState = None self.playState = None
self.__locks.fileReady.clear() self.__locks.fileReady.clear()
else: else:
self.__locks.fileReady.set() self.__locks.fileReady.set()
if(self.callbacks.onFileStateChange): if self.callbacks.onFileStateChange:
thread.start_new_thread(self.callbacks.onFileStateChange, (self.loadState,)) thread.start_new_thread(self.callbacks.onFileStateChange, (self.loadState,))
elif(cmd == self.CMD_PLAYMODE): elif cmd == self.CMD_PLAYMODE:
self.playState = int(value) self.playState = int(value)
if(self.callbacks.onUpdatePlaystate): if self.callbacks.onUpdatePlaystate:
thread.start_new_thread(self.callbacks.onUpdatePlaystate, (self.playState,)) thread.start_new_thread(self.callbacks.onUpdatePlaystate, (self.playState,))
elif(cmd == self.CMD_NOWPLAYING): elif cmd == self.CMD_NOWPLAYING:
value = re.split(r'(?<!\\)\|', value) value = re.split(r'(?<!\\)\|', value)
if self.filePath == value[3]: if self.filePath == value[3]:
return return
self.filePath = value[3] self.filePath = value[3]
self.filePlaying = value[3].split('\\').pop() self.filePlaying = value[3].split('\\').pop()
self.fileDuration = float(value[4]) self.fileDuration = float(value[4])
if(self.callbacks.onUpdatePath): if self.callbacks.onUpdatePath:
thread.start_new_thread(self.callbacks.onUpdatePath, (self.onUpdatePath,)) thread.start_new_thread(self.callbacks.onUpdatePath, (self.onUpdatePath,))
if(self.callbacks.onUpdateFilename): if self.callbacks.onUpdateFilename:
thread.start_new_thread(self.callbacks.onUpdateFilename, (self.filePlaying,)) thread.start_new_thread(self.callbacks.onUpdateFilename, (self.filePlaying,))
if(self.callbacks.onUpdateFileDuration): if self.callbacks.onUpdateFileDuration:
thread.start_new_thread(self.callbacks.onUpdateFileDuration, (self.fileDuration,)) thread.start_new_thread(self.callbacks.onUpdateFileDuration, (self.fileDuration,))
elif(cmd == self.CMD_CURRENTPOSITION): elif cmd == self.CMD_CURRENTPOSITION:
self.lastFilePosition = float(value) self.lastFilePosition = float(value)
if(self.callbacks.onGetCurrentPosition): if self.callbacks.onGetCurrentPosition:
thread.start_new_thread(self.callbacks.onGetCurrentPosition, (self.lastFilePosition,)) thread.start_new_thread(self.callbacks.onGetCurrentPosition, (self.lastFilePosition,))
elif(cmd == self.CMD_NOTIFYSEEK): elif cmd == self.CMD_NOTIFYSEEK:
if(self.lastFilePosition <> float(value)): #Notify seek is sometimes sent twice if self.lastFilePosition <> float(value): #Notify seek is sometimes sent twice
self.lastFilePosition = float(value) self.lastFilePosition = float(value)
if(self.callbacks.onSeek): if self.callbacks.onSeek:
thread.start_new_thread(self.callbacks.onSeek, (self.lastFilePosition,)) thread.start_new_thread(self.callbacks.onSeek, (self.lastFilePosition,))
elif(cmd == self.CMD_DISCONNECT): elif cmd == self.CMD_DISCONNECT:
if(self.callbacks.onMpcClosed): if self.callbacks.onMpcClosed:
thread.start_new_thread(self.callbacks.onMpcClosed, (None,)) thread.start_new_thread(self.callbacks.onMpcClosed, (None,))
elif(cmd == self.CMD_VERSION): elif cmd == self.CMD_VERSION:
if(self.callbacks.onVersion): if self.callbacks.onVersion:
self.version = value self.version = value
thread.start_new_thread(self.callbacks.onVersion, (value,)) thread.start_new_thread(self.callbacks.onVersion, (value,))
@ -174,10 +174,10 @@ class MpcHcApi:
self.fileReady = threading.Event() self.fileReady = threading.Event()
def __mpcReadyInSlaveMode(self): def __mpcReadyInSlaveMode(self):
while(True): while True:
time.sleep(10) time.sleep(10)
if not win32gui.IsWindow(self.__listener.mpcHandle): if not win32gui.IsWindow(self.__listener.mpcHandle):
if(self.callbacks.onMpcClosed): if self.callbacks.onMpcClosed:
self.callbacks.onMpcClosed(None) self.callbacks.onMpcClosed(None)
break break
@ -281,14 +281,14 @@ class MpcHcApi:
def SendCommand(self, cmd, message=u''): def SendCommand(self, cmd, message=u''):
#print "API:\t<out\t 0x%X\t" % int(cmd), message #print "API:\t<out\t 0x%X\t" % int(cmd), message
if not win32gui.IsWindow(self.mpcHandle): if not win32gui.IsWindow(self.mpcHandle):
if(self.__mpcApi.callbacks.onMpcClosed): if self.__mpcApi.callbacks.onMpcClosed:
self.__mpcApi.callbacks.onMpcClosed(None) self.__mpcApi.callbacks.onMpcClosed(None)
cs = self.__COPYDATASTRUCT() cs = self.__COPYDATASTRUCT()
cs.dwData = cmd; cs.dwData = cmd;
if(isinstance(message, (unicode, str))): if isinstance(message, (unicode, str)):
message = ctypes.create_unicode_buffer(message, len(message) + 1) message = ctypes.create_unicode_buffer(message, len(message) + 1)
elif(isinstance(message, ctypes.Structure)): elif isinstance(message, ctypes.Structure):
pass pass
else: else:
raise TypeError raise TypeError
@ -314,7 +314,7 @@ class MPCHCAPIPlayer(BasePlayer):
self.__client = client self.__client = client
self._mpcApi = MpcHcApi() self._mpcApi = MpcHcApi()
self._mpcApi.callbacks.onUpdateFilename = lambda _: self.__makePing() self._mpcApi.callbacks.onUpdateFilename = lambda _: self.__makePing()
self._mpcApi.callbacks.onMpcClosed = lambda _: self.reactor.callFromThread(self.__client.stop, (False),) self._mpcApi.callbacks.onMpcClosed = lambda _: self.reactor.callFromThread(self.__client.stop, False,)
self._mpcApi.callbacks.onFileStateChange = lambda _: self.__lockAsking() self._mpcApi.callbacks.onFileStateChange = lambda _: self.__lockAsking()
self._mpcApi.callbacks.onUpdatePlaystate = lambda _: self.__unlockAsking() self._mpcApi.callbacks.onUpdatePlaystate = lambda _: self.__unlockAsking()
self._mpcApi.callbacks.onGetCurrentPosition = lambda _: self.__onGetPosition() self._mpcApi.callbacks.onGetCurrentPosition = lambda _: self.__onGetPosition()
@ -336,7 +336,7 @@ class MPCHCAPIPlayer(BasePlayer):
def run(client, playerPath, filePath, args): def run(client, playerPath, filePath, args):
args.extend(['/open', '/new']) args.extend(['/open', '/new'])
mpc = MPCHCAPIPlayer(client) mpc = MPCHCAPIPlayer(client)
mpc._mpcApi.callbacks.onConnected = lambda: mpc.initPlayer(filePath if(filePath) else None) mpc._mpcApi.callbacks.onConnected = lambda: mpc.initPlayer(filePath if filePath else None)
mpc._mpcApi.startMpc(MPCHCAPIPlayer.getExpandedPath(playerPath), args) mpc._mpcApi.startMpc(MPCHCAPIPlayer.getExpandedPath(playerPath), args)
client.initPlayer(mpc) client.initPlayer(mpc)
return mpc return mpc
@ -358,12 +358,12 @@ class MPCHCAPIPlayer(BasePlayer):
def __dropIfNotSufficientVersion(self): def __dropIfNotSufficientVersion(self):
self._mpcApi.askForVersion() self._mpcApi.askForVersion()
if(not self.__versionUpdate.wait(0.1) or not self._mpcApi.version): if not self.__versionUpdate.wait(0.1) or not self._mpcApi.version:
self.reactor.callFromThread(self.__client.ui.showErrorMessage, getMessage("mpc-version-insufficient-error").format(constants.MPC_MIN_VER), True) self.reactor.callFromThread(self.__client.ui.showErrorMessage, getMessage("mpc-version-insufficient-error").format(constants.MPC_MIN_VER), True)
self.reactor.callFromThread(self.__client.stop, True) self.reactor.callFromThread(self.__client.stop, True)
def __testMpcReady(self): def __testMpcReady(self):
if(not self.__preventAsking.wait(10)): if not self.__preventAsking.wait(10):
raise Exception(getMessage("player-file-open-error")) raise Exception(getMessage("player-file-open-error"))
def __makePing(self): def __makePing(self):
@ -378,14 +378,14 @@ class MPCHCAPIPlayer(BasePlayer):
def initPlayer(self, filePath): def initPlayer(self, filePath):
self.__dropIfNotSufficientVersion() self.__dropIfNotSufficientVersion()
if(not self._mpcApi.version): if not self._mpcApi.version:
return return
self.__mpcVersion = self._mpcApi.version.split('.') self.__mpcVersion = self._mpcApi.version.split('.')
if(self.__mpcVersion[0:3] == ['1', '6', '4']): if self.__mpcVersion[0:3] == ['1', '6', '4']:
self.__switchPauseCalls = True self.__switchPauseCalls = True
if(self.__mpcVersion[0:3] >= ['1', '6', '5']): if self.__mpcVersion[0:3] >= ['1', '6', '5']:
self.speedSupported = True self.speedSupported = True
if(filePath): if filePath:
self.openFile(filePath) self.openFile(filePath)
def openFile(self, filePath): def openFile(self, filePath):
@ -417,12 +417,12 @@ class MPCHCAPIPlayer(BasePlayer):
@retry(MpcHcApi.PlayerNotReadyException, constants.MPC_MAX_RETRIES, constants.MPC_RETRY_WAIT_TIME, 1) @retry(MpcHcApi.PlayerNotReadyException, constants.MPC_MAX_RETRIES, constants.MPC_RETRY_WAIT_TIME, 1)
def askForStatus(self): def askForStatus(self):
if(self._mpcApi.filePlaying and self.__preventAsking.wait(0) and self.__fileUpdate.acquire(0)): if self._mpcApi.filePlaying and self.__preventAsking.wait(0) and self.__fileUpdate.acquire(0):
self.__fileUpdate.release() self.__fileUpdate.release()
position = self.__getPosition() position = self.__getPosition()
paused = self._mpcApi.isPaused() paused = self._mpcApi.isPaused()
position = float(position) position = float(position)
if(self.__preventAsking.wait(0) and self.__fileUpdate.acquire(0)): if self.__preventAsking.wait(0) and self.__fileUpdate.acquire(0):
self.__client.updatePlayerStatus(paused, position) self.__client.updatePlayerStatus(paused, position)
self.__fileUpdate.release() self.__fileUpdate.release()
return return
@ -444,9 +444,9 @@ class MPCHCAPIPlayer(BasePlayer):
def _setPausedAccordinglyToServer(self): def _setPausedAccordinglyToServer(self):
self.__forcePause() self.__forcePause()
self.setPaused(self.__client.getGlobalPaused()) self.setPaused(self.__client.getGlobalPaused())
if(self._mpcApi.isPaused() <> self.__client.getGlobalPaused()): if self._mpcApi.isPaused() <> self.__client.getGlobalPaused():
self.__refreshMpcPlayState() self.__refreshMpcPlayState()
if(self._mpcApi.isPaused() <> self.__client.getGlobalPaused()): if self._mpcApi.isPaused() <> self.__client.getGlobalPaused():
self.__setUpStateForNewlyOpenedFile() self.__setUpStateForNewlyOpenedFile()
@retry(MpcHcApi.PlayerNotReadyException, constants.MPC_MAX_RETRIES, constants.MPC_RETRY_WAIT_TIME, 1) @retry(MpcHcApi.PlayerNotReadyException, constants.MPC_MAX_RETRIES, constants.MPC_RETRY_WAIT_TIME, 1)
@ -469,31 +469,31 @@ class MPCHCAPIPlayer(BasePlayer):
@staticmethod @staticmethod
def getIconPath(path): def getIconPath(path):
if(MPCHCAPIPlayer.getExpandedPath(path).lower().endswith(u'mpc-hc64.exe'.lower())): if MPCHCAPIPlayer.getExpandedPath(path).lower().endswith(u'mpc-hc64.exe'.lower()):
return constants.MPC64_ICONPATH return constants.MPC64_ICONPATH
else: else:
return constants.MPC_ICONPATH return constants.MPC_ICONPATH
@staticmethod @staticmethod
def isValidPlayerPath(path): def isValidPlayerPath(path):
if(MPCHCAPIPlayer.getExpandedPath(path)): if MPCHCAPIPlayer.getExpandedPath(path):
return True return True
return False return False
@staticmethod @staticmethod
def getExpandedPath(path): def getExpandedPath(path):
if(os.path.isfile(path)): if os.path.isfile(path):
if(path.lower().endswith(u'mpc-hc.exe'.lower()) or path.lower().endswith(u'mpc-hc64.exe'.lower())): if path.lower().endswith(u'mpc-hc.exe'.lower()) or path.lower().endswith(u'mpc-hc64.exe'.lower()):
return path return path
if(os.path.isfile(path + u"mpc-hc.exe")): if os.path.isfile(path + u"mpc-hc.exe"):
path += u"mpc-hc.exe" path += u"mpc-hc.exe"
return path return path
if(os.path.isfile(path + u"\\mpc-hc.exe")): if os.path.isfile(path + u"\\mpc-hc.exe"):
path += u"\\mpc-hc.exe" path += u"\\mpc-hc.exe"
return path return path
if(os.path.isfile(path + u"mpc-hc64.exe")): if os.path.isfile(path + u"mpc-hc64.exe"):
path += u"mpc-hc64.exe" path += u"mpc-hc64.exe"
return path return path
if(os.path.isfile(path + u"\\mpc-hc64.exe")): if os.path.isfile(path + u"\\mpc-hc64.exe"):
path += u"\\mpc-hc64.exe" path += u"\\mpc-hc64.exe"
return path return path

View File

@ -29,7 +29,7 @@ class MpvPlayer(MplayerPlayer):
@staticmethod @staticmethod
def isValidPlayerPath(path): def isValidPlayerPath(path):
if("mpv" in path and MpvPlayer.getExpandedPath(path)): if "mpv" in path and MpvPlayer.getExpandedPath(path):
return True return True
return False return False

View File

@ -12,17 +12,17 @@ class PlayerFactory(object):
def getPlayerByPath(self, path): def getPlayerByPath(self, path):
for player in self._players: for player in self._players:
if(player.isValidPlayerPath(path)): if player.isValidPlayerPath(path):
return player return player
def getPlayerIconByPath(self, path): def getPlayerIconByPath(self, path):
for player in self._players: for player in self._players:
if(player.isValidPlayerPath(path)): if player.isValidPlayerPath(path):
return player.getIconPath(path) return player.getIconPath(path)
return None return None
def getExpandedPlayerPathByPath(self, path): def getExpandedPlayerPathByPath(self, path):
for player in self._players: for player in self._players:
if(player.isValidPlayerPath(path)): if player.isValidPlayerPath(path):
return player.getExpandedPath(path) return player.getExpandedPath(path)
return None return None

View File

@ -43,15 +43,15 @@ class VlcPlayer(BasePlayer):
self._listener = self.__Listener(self, playerPath, filePath, args, self._vlcready, self._vlcclosed) self._listener = self.__Listener(self, playerPath, filePath, args, self._vlcready, self._vlcclosed)
except ValueError: except ValueError:
self._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True) self._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True)
self.reactor.callFromThread(self._client.stop, (True),) self.reactor.callFromThread(self._client.stop, True,)
return return
self._listener.setDaemon(True) self._listener.setDaemon(True)
self._listener.start() self._listener.start()
if(not self._vlcready.wait(constants.VLC_OPEN_MAX_WAIT_TIME)): if not self._vlcready.wait(constants.VLC_OPEN_MAX_WAIT_TIME):
self._vlcready.set() self._vlcready.set()
self._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True) self._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True)
self.reactor.callFromThread(self._client.stop, (True),) self.reactor.callFromThread(self._client.stop, True,)
self.reactor.callFromThread(self._client.initPlayer, (self),) self.reactor.callFromThread(self._client.initPlayer, self,)
def _fileUpdateClearEvents(self): def _fileUpdateClearEvents(self):
self._durationAsk.clear() self._durationAsk.clear()
@ -114,7 +114,7 @@ class VlcPlayer(BasePlayer):
return all(ord(c) < 128 for c in s) return all(ord(c) < 128 for c in s)
def openFile(self, filePath): def openFile(self, filePath):
if (self._isASCII(filePath) == True): if self._isASCII(filePath) == True:
self._listener.sendLine('load-file: {}'.format(filePath.encode('ascii', 'ignore'))) self._listener.sendLine('load-file: {}'.format(filePath.encode('ascii', 'ignore')))
else: else:
fileURL = self.getMRL(filePath) fileURL = self.getMRL(filePath)
@ -130,39 +130,39 @@ class VlcPlayer(BasePlayer):
if match: if match:
name, value = match.group('command'), match.group('argument') name, value = match.group('command'), match.group('argument')
if(line == "filepath-change-notification"): if line == "filepath-change-notification":
self._filechanged = True self._filechanged = True
t = threading.Thread(target=self._onFileUpdate) t = threading.Thread(target=self._onFileUpdate)
t.setDaemon(True) t.setDaemon(True)
t.start() t.start()
elif (name == "filepath" and value != "no-input"): elif name == "filepath" and value != "no-input":
self._filechanged = True self._filechanged = True
if("file://" in value): if "file://" in value:
value = value.replace("file://", "") value = value.replace("file://", "")
if(not os.path.isfile(value)): if not os.path.isfile(value):
value = value.lstrip("/") value = value.lstrip("/")
self._filepath = value self._filepath = value
self._pathAsk.set() self._pathAsk.set()
elif(name == "duration" and (value != "no-input")): elif name == "duration" and (value != "no-input"):
self._duration = float(value.replace(",", ".")) self._duration = float(value.replace(",", "."))
self._durationAsk.set() self._durationAsk.set()
elif(name == "playstate"): elif name == "playstate":
self._paused = bool(value != 'playing') if(value != "no-input" and self._filechanged == False) else self._client.getGlobalPaused() self._paused = bool(value != 'playing') if(value != "no-input" and self._filechanged == False) else self._client.getGlobalPaused()
self._pausedAsk.set() self._pausedAsk.set()
elif(name == "position"): elif name == "position":
self._position = float(value.replace(",", ".")) if (value != "no-input" and self._filechanged == False) else self._client.getGlobalPosition() self._position = float(value.replace(",", ".")) if (value != "no-input" and self._filechanged == False) else self._client.getGlobalPosition()
self._positionAsk.set() self._positionAsk.set()
elif(name == "filename"): elif name == "filename":
self._filechanged = True self._filechanged = True
self._filename = value.decode('utf-8') self._filename = value.decode('utf-8')
self._filenameAsk.set() self._filenameAsk.set()
elif(line.startswith("interface-version: ")): elif line.startswith("interface-version: "):
interface_version = line[19:24] interface_version = line[19:24]
if (int(interface_version.replace(".", "")) < int(constants.VLC_INTERFACE_MIN_VERSION.replace(".", ""))): if int(interface_version.replace(".", "")) < int(constants.VLC_INTERFACE_MIN_VERSION.replace(".", "")):
self._client.ui.showErrorMessage(getMessage("vlc-interface-version-mismatch").format(str(interface_version), str(constants.VLC_INTERFACE_MIN_VERSION))) self._client.ui.showErrorMessage(getMessage("vlc-interface-version-mismatch").format(str(interface_version), str(constants.VLC_INTERFACE_MIN_VERSION)))
elif (line[:16] == "VLC media player"): elif line[:16] == "VLC media player":
vlc_version = line[17:22] vlc_version = line[17:22]
if (int(vlc_version.replace(".", "")) < int(constants.VLC_MIN_VERSION.replace(".", ""))): if int(vlc_version.replace(".", "")) < int(constants.VLC_MIN_VERSION.replace(".", "")):
self._client.ui.showErrorMessage(getMessage("vlc-version-mismatch").format(str(vlc_version), str(constants.VLC_MIN_VERSION))) self._client.ui.showErrorMessage(getMessage("vlc-version-mismatch").format(str(vlc_version), str(constants.VLC_MIN_VERSION)))
self._vlcready.set() self._vlcready.set()
self._listener.sendLine("get-interface-version") self._listener.sendLine("get-interface-version")
@ -184,7 +184,7 @@ class VlcPlayer(BasePlayer):
@staticmethod @staticmethod
def isValidPlayerPath(path): def isValidPlayerPath(path):
if("vlc" in path.lower() and VlcPlayer.getExpandedPath(path)): if "vlc" in path.lower() and VlcPlayer.getExpandedPath(path):
return True return True
return False return False
@ -218,14 +218,14 @@ class VlcPlayer(BasePlayer):
self._positionAsk.set() self._positionAsk.set()
self._vlcready.set() self._vlcready.set()
self._pausedAsk.set() self._pausedAsk.set()
self.reactor.callFromThread(self._client.stop, (False),) self.reactor.callFromThread(self._client.stop, False,)
class __Listener(threading.Thread, asynchat.async_chat): class __Listener(threading.Thread, asynchat.async_chat):
def __init__(self, playerController, playerPath, filePath, args, vlcReady, vlcClosed): def __init__(self, playerController, playerPath, filePath, args, vlcReady, vlcClosed):
self.__playerController = playerController self.__playerController = playerController
call = [playerPath] call = [playerPath]
if(filePath): if filePath:
if (self.__playerController._isASCII(filePath) == True): if self.__playerController._isASCII(filePath) == True:
call.append(filePath) call.append(filePath)
else: else:
call.append(self.__playerController.getMRL(filePath)) call.append(self.__playerController.getMRL(filePath))
@ -238,7 +238,7 @@ class VlcPlayer(BasePlayer):
for line in interfacefile: for line in interfacefile:
if "local connectorversion" in line: if "local connectorversion" in line:
interface_version = line[26:31] interface_version = line[26:31]
if (int(interface_version.replace(".", "")) >= int(constants.VLC_INTERFACE_MIN_VERSION.replace(".", ""))): if int(interface_version.replace(".", "")) >= int(constants.VLC_INTERFACE_MIN_VERSION.replace(".", "")):
return True return True
else: else:
playerController._client.ui.showErrorMessage(getMessage("vlc-interface-oldversion-ignored")) playerController._client.ui.showErrorMessage(getMessage("vlc-interface-oldversion-ignored"))
@ -266,7 +266,7 @@ class VlcPlayer(BasePlayer):
playerController.SLAVE_ARGS.append('--lua-config=syncplay={{modulepath=\"{}\",port=\"{}\"}}'.format(playerController.vlcModulePath, str(playerController.vlcport))) playerController.SLAVE_ARGS.append('--lua-config=syncplay={{modulepath=\"{}\",port=\"{}\"}}'.format(playerController.vlcModulePath, str(playerController.vlcport)))
call.extend(playerController.SLAVE_ARGS) call.extend(playerController.SLAVE_ARGS)
if(args): if args:
call.extend(args) call.extend(args)
self._vlcready = vlcReady self._vlcready = vlcReady
@ -317,11 +317,11 @@ class VlcPlayer(BasePlayer):
self._ibuffer = [] self._ibuffer = []
def sendLine(self, line): def sendLine(self, line):
if(self.connected): if self.connected:
# print "send: {}".format(line) # print "send: {}".format(line)
try: try:
self.push(line + "\n") self.push(line + "\n")
except: except:
pass pass
if(line == "close-vlc"): if line == "close-vlc":
self._vlcclosed.set() self._vlcclosed.set()

View File

@ -76,15 +76,15 @@ class SyncClientProtocol(JSONCommandProtocol):
def handleHello(self, hello): def handleHello(self, hello):
username, roomName, version, motd = self._extractHelloArguments(hello) username, roomName, version, motd = self._extractHelloArguments(hello)
if(not username or not roomName or not version): if not username or not roomName or not version:
self.dropWithError(getMessage("hello-server-error").format(hello)) self.dropWithError(getMessage("hello-server-error").format(hello))
elif(version.split(".")[0:2] != syncplay.version.split(".")[0:2]): elif version.split(".")[0:2] != syncplay.version.split(".")[0:2]:
self.dropWithError(getMessage("version-mismatch-server-error".format(hello))) self.dropWithError(getMessage("version-mismatch-server-error".format(hello)))
else: else:
self._client.setUsername(username) self._client.setUsername(username)
self._client.setRoom(roomName) self._client.setRoom(roomName)
self.logged = True self.logged = True
if(motd): if motd:
self._client.ui.showMessage(motd, True, True) self._client.ui.showMessage(motd, True, True)
self._client.ui.showMessage(getMessage("connected-successful-notification")) self._client.ui.showMessage(getMessage("connected-successful-notification"))
self._client.sendFile() self._client.sendFile()
@ -93,9 +93,9 @@ class SyncClientProtocol(JSONCommandProtocol):
hello = {} hello = {}
hello["username"] = self._client.getUsername() hello["username"] = self._client.getUsername()
password = self._client.getPassword() password = self._client.getPassword()
if(password): hello["password"] = password if password: hello["password"] = password
room = self._client.getRoom() room = self._client.getRoom()
if(room): hello["room"] = {"name" :room} if room: hello["room"] = {"name" :room}
hello["version"] = syncplay.version hello["version"] = syncplay.version
self.sendMessage({"Hello": hello}) self.sendMessage({"Hello": hello})
@ -105,10 +105,10 @@ class SyncClientProtocol(JSONCommandProtocol):
settings = user[1] settings = user[1]
room = settings["room"]["name"] if settings.has_key("room") else None room = settings["room"]["name"] if settings.has_key("room") else None
file_ = settings["file"] if settings.has_key("file") else None file_ = settings["file"] if settings.has_key("file") else None
if(settings.has_key("event")): if settings.has_key("event"):
if(settings["event"].has_key("joined")): if settings["event"].has_key("joined"):
self._client.userlist.addUser(username, room, file_) self._client.userlist.addUser(username, room, file_)
elif(settings["event"].has_key("left")): elif settings["event"].has_key("left"):
self._client.removeUser(username) self._client.removeUser(username)
else: else:
self._client.userlist.modUser(username, room, file_) self._client.userlist.modUser(username, room, file_)
@ -128,7 +128,7 @@ class SyncClientProtocol(JSONCommandProtocol):
def sendRoomSetting(self, roomName, password=None): def sendRoomSetting(self, roomName, password=None):
setting = {} setting = {}
setting["name"] = roomName setting["name"] = roomName
if(password): setting["password"] = password if password: setting["password"] = password
self.sendSet({"room": setting}) self.sendSet({"room": setting})
def sendFileSetting(self, file_): def sendFileSetting(self, file_):
@ -156,9 +156,9 @@ class SyncClientProtocol(JSONCommandProtocol):
return position, paused, doSeek, setBy return position, paused, doSeek, setBy
def _handleStatePing(self, state): def _handleStatePing(self, state):
if (state["ping"].has_key("latencyCalculation")): if state["ping"].has_key("latencyCalculation"):
latencyCalculation = state["ping"]["latencyCalculation"] latencyCalculation = state["ping"]["latencyCalculation"]
if ("clientLatencyCalculation" in state["ping"]): if "clientLatencyCalculation" in state["ping"]:
timestamp = state["ping"]["clientLatencyCalculation"] timestamp = state["ping"]["clientLatencyCalculation"]
senderRtt = state["ping"]["serverRtt"] senderRtt = state["ping"]["serverRtt"]
self._pingService.receiveMessage(timestamp, senderRtt) self._pingService.receiveMessage(timestamp, senderRtt)
@ -168,19 +168,19 @@ class SyncClientProtocol(JSONCommandProtocol):
def handleState(self, state): def handleState(self, state):
position, paused, doSeek, setBy = None, None, None, None position, paused, doSeek, setBy = None, None, None, None
messageAge = 0 messageAge = 0
if(state.has_key("ignoringOnTheFly")): if state.has_key("ignoringOnTheFly"):
ignore = state["ignoringOnTheFly"] ignore = state["ignoringOnTheFly"]
if(ignore.has_key("server")): if ignore.has_key("server"):
self.serverIgnoringOnTheFly = ignore["server"] self.serverIgnoringOnTheFly = ignore["server"]
self.clientIgnoringOnTheFly = 0 self.clientIgnoringOnTheFly = 0
elif(ignore.has_key("client")): elif ignore.has_key("client"):
if(ignore['client']) == self.clientIgnoringOnTheFly: if(ignore['client']) == self.clientIgnoringOnTheFly:
self.clientIgnoringOnTheFly = 0 self.clientIgnoringOnTheFly = 0
if(state.has_key("playstate")): if state.has_key("playstate"):
position, paused, doSeek, setBy = self._extractStatePlaystateArguments(state) position, paused, doSeek, setBy = self._extractStatePlaystateArguments(state)
if(state.has_key("ping")): if state.has_key("ping"):
messageAge, latencyCalculation = self._handleStatePing(state) messageAge, latencyCalculation = self._handleStatePing(state)
if(position is not None and paused is not None and not self.clientIgnoringOnTheFly): if position is not None and paused is not None and not self.clientIgnoringOnTheFly:
self._client.updateGlobalState(position, paused, doSeek, setBy, messageAge) self._client.updateGlobalState(position, paused, doSeek, setBy, messageAge)
position, paused, doSeek, stateChange = self._client.getLocalState() position, paused, doSeek, stateChange = self._client.getLocalState()
self.sendState(position, paused, doSeek, latencyCalculation, stateChange) self.sendState(position, paused, doSeek, latencyCalculation, stateChange)
@ -189,24 +189,24 @@ class SyncClientProtocol(JSONCommandProtocol):
state = {} state = {}
positionAndPausedIsSet = position is not None and paused is not None positionAndPausedIsSet = position is not None and paused is not None
clientIgnoreIsNotSet = self.clientIgnoringOnTheFly == 0 or self.serverIgnoringOnTheFly != 0 clientIgnoreIsNotSet = self.clientIgnoringOnTheFly == 0 or self.serverIgnoringOnTheFly != 0
if(clientIgnoreIsNotSet and positionAndPausedIsSet): if clientIgnoreIsNotSet and positionAndPausedIsSet:
state["playstate"] = {} state["playstate"] = {}
state["playstate"]["position"] = position state["playstate"]["position"] = position
state["playstate"]["paused"] = paused state["playstate"]["paused"] = paused
if(doSeek): state["playstate"]["doSeek"] = doSeek if doSeek: state["playstate"]["doSeek"] = doSeek
state["ping"] = {} state["ping"] = {}
if(latencyCalculation): if latencyCalculation:
state["ping"]["latencyCalculation"] = latencyCalculation state["ping"]["latencyCalculation"] = latencyCalculation
state["ping"]["clientLatencyCalculation"] = self._pingService.newTimestamp() state["ping"]["clientLatencyCalculation"] = self._pingService.newTimestamp()
state["ping"]["clientRtt"] = self._pingService.getRtt() state["ping"]["clientRtt"] = self._pingService.getRtt()
if(stateChange): if stateChange:
self.clientIgnoringOnTheFly += 1 self.clientIgnoringOnTheFly += 1
if(self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly): if self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly:
state["ignoringOnTheFly"] = {} state["ignoringOnTheFly"] = {}
if(self.serverIgnoringOnTheFly): if self.serverIgnoringOnTheFly:
state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly
self.serverIgnoringOnTheFly = 0 self.serverIgnoringOnTheFly = 0
if(self.clientIgnoringOnTheFly): if self.clientIgnoringOnTheFly:
state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly
self.sendMessage({"State": state}) self.sendMessage({"State": state})
@ -236,7 +236,7 @@ class SyncServerProtocol(JSONCommandProtocol):
def requireLogged(f): # @NoSelf def requireLogged(f): # @NoSelf
@wraps(f) @wraps(f)
def wrapper(self, *args, **kwds): def wrapper(self, *args, **kwds):
if(not self._logged): if not self._logged:
self.dropWithError(getMessage("not-known-server-error")) self.dropWithError(getMessage("not-known-server-error"))
return f(self, *args, **kwds) return f(self, *args, **kwds)
return wrapper return wrapper
@ -258,7 +258,7 @@ class SyncServerProtocol(JSONCommandProtocol):
username = username.strip() username = username.strip()
serverPassword = hello["password"] if hello.has_key("password") else None serverPassword = hello["password"] if hello.has_key("password") else None
room = hello["room"] if hello.has_key("room") else None room = hello["room"] if hello.has_key("room") else None
if(room): if room:
roomName = room["name"] if room.has_key("name") else None roomName = room["name"] if room.has_key("name") else None
roomName = roomName.strip() roomName = roomName.strip()
roomPassword = room["password"] if room.has_key("password") else None roomPassword = room["password"] if room.has_key("password") else None
@ -266,23 +266,23 @@ class SyncServerProtocol(JSONCommandProtocol):
return username, serverPassword, roomName, roomPassword, version return username, serverPassword, roomName, roomPassword, version
def _checkPassword(self, serverPassword): def _checkPassword(self, serverPassword):
if(self._factory.password): if self._factory.password:
if(not serverPassword): if not serverPassword:
self.dropWithError(getMessage("password-required-server-error")) self.dropWithError(getMessage("password-required-server-error"))
return False return False
if(serverPassword != self._factory.password): if serverPassword != self._factory.password:
self.dropWithError(getMessage("wrong-password-server-error")) self.dropWithError(getMessage("wrong-password-server-error"))
return False return False
return True return True
def handleHello(self, hello): def handleHello(self, hello):
username, serverPassword, roomName, roomPassword, version = self._extractHelloArguments(hello) username, serverPassword, roomName, roomPassword, version = self._extractHelloArguments(hello)
if(not username or not roomName or not version): if not username or not roomName or not version:
self.dropWithError(getMessage("hello-server-error")) self.dropWithError(getMessage("hello-server-error"))
elif(version.split(".")[0:2] != syncplay.version.split(".")[0:2]): elif version.split(".")[0:2] != syncplay.version.split(".")[0:2]:
self.dropWithError(getMessage("version-mismatch-server-error")) self.dropWithError(getMessage("version-mismatch-server-error"))
else: else:
if(not self._checkPassword(serverPassword)): if not self._checkPassword(serverPassword):
return return
self._factory.addWatcher(self, username, roomName, roomPassword) self._factory.addWatcher(self, username, roomName, roomPassword)
self._logged = True self._logged = True
@ -297,7 +297,7 @@ class SyncServerProtocol(JSONCommandProtocol):
hello["username"] = username hello["username"] = username
userIp = self.transport.getPeer().host userIp = self.transport.getPeer().host
room = self._watcher.getRoom() room = self._watcher.getRoom()
if(room): hello["room"] = {"name": room.getName()} if room: hello["room"] = {"name": room.getName()}
hello["version"] = syncplay.version hello["version"] = syncplay.version
hello["motd"] = self._factory.getMotd(userIp, username, room, clientVersion) hello["motd"] = self._factory.getMotd(userIp, username, room, clientVersion)
self.sendMessage({"Hello": hello}) self.sendMessage({"Hello": hello})
@ -320,9 +320,9 @@ class SyncServerProtocol(JSONCommandProtocol):
user = {} user = {}
user[username] = {} user[username] = {}
user[username]["room"] = room user[username]["room"] = room
if(file_): if file_:
user[username]["file"] = file_ user[username]["file"] = file_
if(event): if event:
user[username]["event"] = event user[username]["event"] = event
self.sendSet({"user": user}) self.sendSet({"user": user})
@ -346,7 +346,7 @@ class SyncServerProtocol(JSONCommandProtocol):
self.sendList() self.sendList()
def sendState(self, position, paused, doSeek, setBy, forced=False): def sendState(self, position, paused, doSeek, setBy, forced=False):
if(self._clientLatencyCalculationArrivalTime): if self._clientLatencyCalculationArrivalTime:
processingTime = time.time() - self._clientLatencyCalculationArrivalTime processingTime = time.time() - self._clientLatencyCalculationArrivalTime
else: else:
processingTime = 0 processingTime = 0
@ -360,23 +360,23 @@ class SyncServerProtocol(JSONCommandProtocol):
"latencyCalculation": self._pingService.newTimestamp(), "latencyCalculation": self._pingService.newTimestamp(),
"serverRtt": self._pingService.getRtt() "serverRtt": self._pingService.getRtt()
} }
if(self._clientLatencyCalculation): if self._clientLatencyCalculation:
ping["clientLatencyCalculation"] = self._clientLatencyCalculation + processingTime ping["clientLatencyCalculation"] = self._clientLatencyCalculation + processingTime
self._clientLatencyCalculation = 0 self._clientLatencyCalculation = 0
state = { state = {
"ping": ping, "ping": ping,
"playstate": playstate, "playstate": playstate,
} }
if(forced): if forced:
self.serverIgnoringOnTheFly += 1 self.serverIgnoringOnTheFly += 1
if(self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly): if self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly:
state["ignoringOnTheFly"] = {} state["ignoringOnTheFly"] = {}
if(self.serverIgnoringOnTheFly): if self.serverIgnoringOnTheFly:
state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly
if(self.clientIgnoringOnTheFly): if self.clientIgnoringOnTheFly:
state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly
self.clientIgnoringOnTheFly = 0 self.clientIgnoringOnTheFly = 0
if(self.serverIgnoringOnTheFly == 0 or forced): if self.serverIgnoringOnTheFly == 0 or forced:
self.sendMessage({"State": state}) self.sendMessage({"State": state})
@ -389,22 +389,22 @@ class SyncServerProtocol(JSONCommandProtocol):
@requireLogged @requireLogged
def handleState(self, state): def handleState(self, state):
position, paused, doSeek, latencyCalculation = None, None, None, None position, paused, doSeek, latencyCalculation = None, None, None, None
if(state.has_key("ignoringOnTheFly")): if state.has_key("ignoringOnTheFly"):
ignore = state["ignoringOnTheFly"] ignore = state["ignoringOnTheFly"]
if(ignore.has_key("server")): if ignore.has_key("server"):
if(self.serverIgnoringOnTheFly == ignore["server"]): if self.serverIgnoringOnTheFly == ignore["server"]:
self.serverIgnoringOnTheFly = 0 self.serverIgnoringOnTheFly = 0
if(ignore.has_key("client")): if ignore.has_key("client"):
self.clientIgnoringOnTheFly = ignore["client"] self.clientIgnoringOnTheFly = ignore["client"]
if(state.has_key("playstate")): if state.has_key("playstate"):
position, paused, doSeek = self._extractStatePlaystateArguments(state) position, paused, doSeek = self._extractStatePlaystateArguments(state)
if(state.has_key("ping")): if state.has_key("ping"):
latencyCalculation = state["ping"]["latencyCalculation"] if state["ping"].has_key("latencyCalculation") else 0 latencyCalculation = state["ping"]["latencyCalculation"] if state["ping"].has_key("latencyCalculation") else 0
clientRtt = state["ping"]["clientRtt"] if state["ping"].has_key("clientRtt") else 0 clientRtt = state["ping"]["clientRtt"] if state["ping"].has_key("clientRtt") else 0
self._clientLatencyCalculation = state["ping"]["clientLatencyCalculation"] if state["ping"].has_key("clientLatencyCalculation") else 0 self._clientLatencyCalculation = state["ping"]["clientLatencyCalculation"] if state["ping"].has_key("clientLatencyCalculation") else 0
self._clientLatencyCalculationArrivalTime = time.time() self._clientLatencyCalculationArrivalTime = time.time()
self._pingService.receiveMessage(latencyCalculation, clientRtt) self._pingService.receiveMessage(latencyCalculation, clientRtt)
if(self.serverIgnoringOnTheFly == 0): if self.serverIgnoringOnTheFly == 0:
self._watcher.updateState(position, paused, doSeek, self._pingService.getLastForwardDelay()) self._watcher.updateState(position, paused, doSeek, self._pingService.getLastForwardDelay())
def handleError(self, error): def handleError(self, error):
@ -424,15 +424,15 @@ class PingService(object):
return time.time() return time.time()
def receiveMessage(self, timestamp, senderRtt): def receiveMessage(self, timestamp, senderRtt):
if(not timestamp): if not timestamp:
return return
self._rtt = time.time() - timestamp self._rtt = time.time() - timestamp
if(self._rtt < 0 or senderRtt < 0): if self._rtt < 0 or senderRtt < 0:
return return
if(not self._avrRtt): if not self._avrRtt:
self._avrRtt = self._rtt self._avrRtt = self._rtt
self._avrRtt = self._avrRtt * PING_MOVING_AVERAGE_WEIGHT + self._rtt * (1 - PING_MOVING_AVERAGE_WEIGHT) self._avrRtt = self._avrRtt * PING_MOVING_AVERAGE_WEIGHT + self._rtt * (1 - PING_MOVING_AVERAGE_WEIGHT)
if(senderRtt < self._rtt): if senderRtt < self._rtt:
self._fd = self._avrRtt / 2 + (self._rtt - senderRtt) self._fd = self._avrRtt / 2 + (self._rtt - senderRtt)
else: else:
self._fd = self._avrRtt / 2 self._fd = self._avrRtt / 2

View File

@ -16,11 +16,11 @@ from pprint import pprint
class SyncFactory(Factory): class SyncFactory(Factory):
def __init__(self, password='', motdFilePath=None, isolateRooms=False): def __init__(self, password='', motdFilePath=None, isolateRooms=False):
print getMessage("welcome-server-notification").format(syncplay.version) print getMessage("welcome-server-notification").format(syncplay.version)
if(password): if password:
password = hashlib.md5(password).hexdigest() password = hashlib.md5(password).hexdigest()
self.password = password self.password = password
self._motdFilePath = motdFilePath self._motdFilePath = motdFilePath
if(not isolateRooms): if not isolateRooms:
self._roomManager = RoomManager() self._roomManager = RoomManager()
else: else:
self._roomManager = PublicRoomManager() self._roomManager = PublicRoomManager()
@ -40,7 +40,7 @@ class SyncFactory(Factory):
if constants.WARN_OLD_CLIENTS: if constants.WARN_OLD_CLIENTS:
if int(clientVersion.replace(".", "")) < int(constants.RECENT_CLIENT_THRESHOLD.replace(".", "")): if int(clientVersion.replace(".", "")) < int(constants.RECENT_CLIENT_THRESHOLD.replace(".", "")):
oldClient = True oldClient = True
if(self._motdFilePath and os.path.isfile(self._motdFilePath)): if self._motdFilePath and os.path.isfile(self._motdFilePath):
tmpl = codecs.open(self._motdFilePath, "r", "utf-8-sig").read() tmpl = codecs.open(self._motdFilePath, "r", "utf-8-sig").read()
args = dict(version=syncplay.version, userIp=userIp, username=username, room=room) args = dict(version=syncplay.version, userIp=userIp, username=username, room=room)
try: try:
@ -129,7 +129,7 @@ class RoomManager(object):
def removeWatcher(self, watcher): def removeWatcher(self, watcher):
oldRoom = watcher.getRoom() oldRoom = watcher.getRoom()
if(oldRoom): if oldRoom:
oldRoom.removeWatcher(watcher) oldRoom.removeWatcher(watcher)
self._deleteRoomIfEmpty(oldRoom) self._deleteRoomIfEmpty(oldRoom)
@ -219,7 +219,7 @@ class Room(object):
watcher.setRoom(self) watcher.setRoom(self)
def removeWatcher(self, watcher): def removeWatcher(self, watcher):
if(watcher.getName() not in self._watchers): if watcher.getName() not in self._watchers:
return return
del self._watchers[watcher.getName()] del self._watchers[watcher.getName()]
watcher.setRoom(None) watcher.setRoom(None)
@ -300,7 +300,7 @@ class Watcher(object):
self._sendStateTimer.start(constants.SERVER_STATE_INTERVAL) self._sendStateTimer.start(constants.SERVER_STATE_INTERVAL)
def _deactivateStateTimer(self): def _deactivateStateTimer(self):
if(self._sendStateTimer and self._sendStateTimer.running): if self._sendStateTimer and self._sendStateTimer.running:
self._sendStateTimer.stop() self._sendStateTimer.stop()
def sendState(self, position, paused, doSeek, setBy, forcedUpdate): def sendState(self, position, paused, doSeek, setBy, forcedUpdate):
@ -321,7 +321,7 @@ class Watcher(object):
if pauseChanged: if pauseChanged:
self.getRoom().setPaused(Room.STATE_PAUSED if paused else Room.STATE_PLAYING, self) self.getRoom().setPaused(Room.STATE_PAUSED if paused else Room.STATE_PLAYING, self)
if position is not None: if position is not None:
if(not paused): if not paused:
position += messageAge position += messageAge
self.setPosition(position) self.setPosition(position)
if doSeek or pauseChanged: if doSeek or pauseChanged:
@ -332,7 +332,7 @@ class ConfigurationGetter(object):
def getConfiguration(self): def getConfiguration(self):
self._prepareArgParser() self._prepareArgParser()
self._args = self._argparser.parse_args() self._args = self._argparser.parse_args()
if(self._args.port == None): if self._args.port == None:
self._args.port = constants.DEFAULT_PORT self._args.port = constants.DEFAULT_PORT
return self._args return self._args

View File

@ -76,64 +76,64 @@ class ConfigurationGetter(object):
def _validateArguments(self): def _validateArguments(self):
def _isPortValid(varToTest): def _isPortValid(varToTest):
try: try:
if (varToTest == "" or varToTest is None): if varToTest == "" or varToTest is None:
return False return False
if (str(varToTest).isdigit() == False): if str(varToTest).isdigit() == False:
return False return False
varToTest = int(varToTest) varToTest = int(varToTest)
if (varToTest > 65535 or varToTest < 1): if varToTest > 65535 or varToTest < 1:
return False return False
return True return True
except: except:
return False return False
for key in self._boolean: for key in self._boolean:
if(self._config[key] == "True"): if self._config[key] == "True":
self._config[key] = True self._config[key] = True
elif(self._config[key] == "False"): elif self._config[key] == "False":
self._config[key] = False self._config[key] = False
for key in self._required: for key in self._required:
if(key == "playerPath"): if key == "playerPath":
player = None player = None
if self._config["playerPath"]: if self._config["playerPath"]:
player = self._playerFactory.getPlayerByPath(self._config["playerPath"]) player = self._playerFactory.getPlayerByPath(self._config["playerPath"])
if(player): if player:
self._config["playerClass"] = player self._config["playerClass"] = player
else: else:
raise InvalidConfigValue("Player path is not set properly") raise InvalidConfigValue("Player path is not set properly")
if player.__name__ in ['MpvPlayer', 'MplayerPlayer']: if player.__name__ in ['MpvPlayer', 'MplayerPlayer']:
if not self._config['file']: if not self._config['file']:
raise InvalidConfigValue("File must be selected before starting your player") raise InvalidConfigValue("File must be selected before starting your player")
elif(key == "host"): elif key == "host":
self._config["host"], self._config["port"] = self._splitPortAndHost(self._config["host"]) self._config["host"], self._config["port"] = self._splitPortAndHost(self._config["host"])
hostNotValid = (self._config["host"] == "" or self._config["host"] is None) hostNotValid = (self._config["host"] == "" or self._config["host"] is None)
portNotValid = (_isPortValid(self._config["port"]) == False) portNotValid = (_isPortValid(self._config["port"]) == False)
if(hostNotValid): if hostNotValid:
raise InvalidConfigValue("Hostname can't be empty") raise InvalidConfigValue("Hostname can't be empty")
elif(portNotValid): elif portNotValid:
raise InvalidConfigValue("Port must be valid") raise InvalidConfigValue("Port must be valid")
elif(self._config[key] == "" or self._config[key] is None): elif self._config[key] == "" or self._config[key] is None:
raise InvalidConfigValue("{} can't be empty".format(key.capitalize())) raise InvalidConfigValue("{} can't be empty".format(key.capitalize()))
def _overrideConfigWithArgs(self, args): def _overrideConfigWithArgs(self, args):
for key, val in vars(args).items(): for key, val in vars(args).items():
if(val): if val:
if(key == "force_gui_prompt"): if key == "force_gui_prompt":
key = "forceGuiPrompt" key = "forceGuiPrompt"
if(key == "no_store"): if key == "no_store":
key = "noStore" key = "noStore"
if(key == "player_path"): if key == "player_path":
key = "playerPath" key = "playerPath"
if(key == "_args"): if key == "_args":
key = "playerArgs" key = "playerArgs"
if(key == "no_gui"): if key == "no_gui":
key = "noGui" key = "noGui"
if(key == "clear_gui_data"): if key == "clear_gui_data":
key = "clearGUIData" key = "clearGUIData"
self._config[key] = val self._config[key] = val
def _splitPortAndHost(self, host): def _splitPortAndHost(self, host):
port = constants.DEFAULT_PORT if not self._config["port"] else self._config["port"] port = constants.DEFAULT_PORT if not self._config["port"] else self._config["port"]
if(host): if host:
if ':' in host: if ':' in host:
host, port = host.split(':', 1) host, port = host.split(':', 1)
try: try:
@ -148,21 +148,21 @@ class ConfigurationGetter(object):
def _checkForPortableFile(self): def _checkForPortableFile(self):
path = utils.findWorkingDir() path = utils.findWorkingDir()
for name in constants.CONFIG_NAMES: for name in constants.CONFIG_NAMES:
if(os.path.isfile(os.path.join(path, name))): if os.path.isfile(os.path.join(path, name)):
return os.path.join(path, name) return os.path.join(path, name)
def _getConfigurationFilePath(self): def _getConfigurationFilePath(self):
configFile = self._checkForPortableFile() configFile = self._checkForPortableFile()
if not configFile: if not configFile:
for name in constants.CONFIG_NAMES: for name in constants.CONFIG_NAMES:
if(configFile and os.path.isfile(configFile)): if configFile and os.path.isfile(configFile):
break break
if(os.name <> 'nt'): if os.name <> 'nt':
configFile = os.path.join(os.getenv('HOME', '.'), name) configFile = os.path.join(os.getenv('HOME', '.'), name)
else: else:
configFile = os.path.join(os.getenv('APPDATA', '.'), name) configFile = os.path.join(os.getenv('APPDATA', '.'), name)
if(configFile and not os.path.isfile(configFile)): if configFile and not os.path.isfile(configFile):
if(os.name <> 'nt'): if os.name <> 'nt':
configFile = os.path.join(os.getenv('HOME', '.'), constants.DEFAULT_CONFIG_NAME_LINUX) configFile = os.path.join(os.getenv('HOME', '.'), constants.DEFAULT_CONFIG_NAME_LINUX)
else: else:
configFile = os.path.join(os.getenv('APPDATA', '.'), constants.DEFAULT_CONFIG_NAME_WINDOWS) configFile = os.path.join(os.getenv('APPDATA', '.'), constants.DEFAULT_CONFIG_NAME_WINDOWS)
@ -171,16 +171,16 @@ class ConfigurationGetter(object):
def _parseConfigFile(self, iniPath, createConfig=True): def _parseConfigFile(self, iniPath, createConfig=True):
parser = SafeConfigParserUnicode() parser = SafeConfigParserUnicode()
if(not os.path.isfile(iniPath)): if not os.path.isfile(iniPath):
if(createConfig): if createConfig:
open(iniPath, 'w').close() open(iniPath, 'w').close()
else: else:
return return
parser.readfp(codecs.open(iniPath, "r", "utf_8_sig")) parser.readfp(codecs.open(iniPath, "r", "utf_8_sig"))
for section, options in self._iniStructure.items(): for section, options in self._iniStructure.items():
if(parser.has_section(section)): if parser.has_section(section):
for option in options: for option in options:
if(parser.has_option(section, option)): if parser.has_option(section, option):
self._config[option] = parser.get(section, option) self._config[option] = parser.get(section, option)
def _checkConfig(self): def _checkConfig(self):
@ -195,39 +195,39 @@ class ConfigurationGetter(object):
sys.exit() sys.exit()
def _promptForMissingArguments(self, error=None): def _promptForMissingArguments(self, error=None):
if(self._config['noGui'] or not GuiConfiguration): if self._config['noGui'] or not GuiConfiguration:
if error: if error:
print "{}!".format(error) print "{}!".format(error)
print getMessage("missing-arguments-error") print getMessage("missing-arguments-error")
sys.exit() sys.exit()
elif(GuiConfiguration): elif GuiConfiguration:
gc = GuiConfiguration(self._config, error=error) gc = GuiConfiguration(self._config, error=error)
gc.setAvailablePaths(self._playerFactory.getAvailablePlayerPaths()) gc.setAvailablePaths(self._playerFactory.getAvailablePlayerPaths())
gc.run() gc.run()
return gc.getProcessedConfiguration() return gc.getProcessedConfiguration()
def __wasOptionChanged(self, parser, section, option): def __wasOptionChanged(self, parser, section, option):
if (parser.has_option(section, option)): if parser.has_option(section, option):
if (parser.get(section, option) != unicode(self._config[option])): if parser.get(section, option) != unicode(self._config[option]):
return True return True
else: else:
return True return True
def _saveConfig(self, iniPath): def _saveConfig(self, iniPath):
changed = False changed = False
if(self._config['noStore']): if self._config['noStore']:
return return
parser = SafeConfigParserUnicode() parser = SafeConfigParserUnicode()
parser.readfp(codecs.open(iniPath, "r", "utf_8_sig")) parser.readfp(codecs.open(iniPath, "r", "utf_8_sig"))
for section, options in self._iniStructure.items(): for section, options in self._iniStructure.items():
if(not parser.has_section(section)): if not parser.has_section(section):
parser.add_section(section) parser.add_section(section)
changed = True changed = True
for option in options: for option in options:
if(self.__wasOptionChanged(parser, section, option)): if self.__wasOptionChanged(parser, section, option):
changed = True changed = True
parser.set(section, option, unicode(self._config[option]).replace('%', '%%')) parser.set(section, option, unicode(self._config[option]).replace('%', '%%'))
if(changed): if changed:
parser.write(codecs.open(iniPath, "wb", "utf_8_sig")) parser.write(codecs.open(iniPath, "wb", "utf_8_sig"))
@ -239,7 +239,7 @@ class ConfigurationGetter(object):
pass pass
try: try:
if(self._config['noGui'] == False): if self._config['noGui'] == False:
for key, value in self._promptForMissingArguments().items(): for key, value in self._promptForMissingArguments().items():
self._config[key] = value self._config[key] = value
except GuiConfiguration.WindowClosed: except GuiConfiguration.WindowClosed:
@ -267,7 +267,7 @@ class ConfigurationGetter(object):
for location in locations: for location in locations:
for name in constants.CONFIG_NAMES: for name in constants.CONFIG_NAMES:
path = location + os.path.sep + name path = location + os.path.sep + name
if(os.path.isfile(path) and (os.name == 'nt' or path != os.path.join(os.getenv('HOME', '.'), constants.DEFAULT_CONFIG_NAME_LINUX))): if os.path.isfile(path) and (os.name == 'nt' or path != os.path.join(os.getenv('HOME', '.'), constants.DEFAULT_CONFIG_NAME_LINUX)):
loadedPaths.append("'" + os.path.normpath(path) + "'") loadedPaths.append("'" + os.path.normpath(path) + "'")
self._parseConfigFile(path, createConfig=False) self._parseConfigFile(path, createConfig=False)
self._checkConfig() self._checkConfig()
@ -298,23 +298,23 @@ class ConfigurationGetter(object):
self._argparser.add_argument('_args', metavar='options', type=str, nargs='*', help=getMessage("args-argument")) self._argparser.add_argument('_args', metavar='options', type=str, nargs='*', help=getMessage("args-argument"))
args = self._argparser.parse_args() args = self._argparser.parse_args()
self._overrideConfigWithArgs(args) self._overrideConfigWithArgs(args)
if(self._config['file'] and self._config['file'][:2] == "--"): if self._config['file'] and self._config['file'][:2] == "--":
self._config['playerArgs'].insert(0, self._config['file']) self._config['playerArgs'].insert(0, self._config['file'])
self._config['file'] = None self._config['file'] = None
# Arguments not validated yet - booleans are still text values # Arguments not validated yet - booleans are still text values
if self._config['language']: if self._config['language']:
setLanguage(self._config['language']) setLanguage(self._config['language'])
if((self._config['forceGuiPrompt'] == "True" or not self._config['file']) and GuiConfiguration and not self._config['noGui']): if (self._config['forceGuiPrompt'] == "True" or not self._config['file']) and GuiConfiguration and not self._config['noGui']:
self._forceGuiPrompt() self._forceGuiPrompt()
self._checkConfig() self._checkConfig()
self._saveConfig(iniPath) self._saveConfig(iniPath)
if(self._config['file']): if self._config['file']:
self._config['loadedRelativePaths'] = self._loadRelativeConfiguration() self._config['loadedRelativePaths'] = self._loadRelativeConfiguration()
if self._config['language']: if self._config['language']:
setLanguage(self._config['language']) setLanguage(self._config['language'])
if not GuiConfiguration: if not GuiConfiguration:
self._config['noGui'] = True self._config['noGui'] = True
if(not self._config['noGui']): if not self._config['noGui']:
from syncplay.vendor import qt4reactor from syncplay.vendor import qt4reactor
if QCoreApplication.instance() is None: if QCoreApplication.instance() is None:
self.app = QtGui.QApplication(sys.argv) self.app = QtGui.QApplication(sys.argv)
@ -336,5 +336,5 @@ class SafeConfigParserUnicode(SafeConfigParser):
continue continue
if (value is not None) or (self._optcre == self.OPTCRE): if (value is not None) or (self._optcre == self.OPTCRE):
key = " = ".join((key, unicode(value).replace('\n', '\n\t'))) key = " = ".join((key, unicode(value).replace('\n', '\n\t')))
fp.write("%s\n" % (key)) fp.write("%s\n" % key)
fp.write("\n") fp.write("\n")

View File

@ -56,7 +56,7 @@ class ConfigDialog(QtGui.QDialog):
self.setFixedSize(self.sizeHint()) self.setFixedSize(self.sizeHint())
def runButtonTextUpdate(self): def runButtonTextUpdate(self):
if (self.donotstoreCheckbox.isChecked()): if self.donotstoreCheckbox.isChecked():
self.runButton.setText(getMessage("run-label")) self.runButton.setText(getMessage("run-label"))
else: else:
self.runButton.setText(getMessage("storeandrun-label")) self.runButton.setText(getMessage("storeandrun-label"))
@ -68,7 +68,7 @@ class ConfigDialog(QtGui.QDialog):
settings = QSettings("Syncplay", "PlayerList") settings = QSettings("Syncplay", "PlayerList")
settings.beginGroup("PlayerList") settings.beginGroup("PlayerList")
savedPlayers = settings.value("PlayerList", []) savedPlayers = settings.value("PlayerList", [])
if(not isinstance(savedPlayers, list)): if not isinstance(savedPlayers, list):
savedPlayers = [] savedPlayers = []
playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers))) playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers)))
settings.endGroup() settings.endGroup()
@ -85,7 +85,7 @@ class ConfigDialog(QtGui.QDialog):
self.executablepathCombobox.addItem(foundpath) self.executablepathCombobox.addItem(foundpath)
for path in playerpathlist: for path in playerpathlist:
if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))): if os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath)):
self.executablepathCombobox.addItem(path) self.executablepathCombobox.addItem(path)
if foundpath == "": if foundpath == "":
foundpath = path foundpath = path
@ -95,7 +95,7 @@ class ConfigDialog(QtGui.QDialog):
playerpathlist.append(os.path.normcase(os.path.normpath(foundpath))) playerpathlist.append(os.path.normcase(os.path.normpath(foundpath)))
settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist)))) settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist))))
settings.endGroup() settings.endGroup()
return(foundpath) return foundpath
def updateExecutableIcon(self): def updateExecutableIcon(self):
currentplayerpath = unicode(self.executablepathCombobox.currentText()) currentplayerpath = unicode(self.executablepathCombobox.currentText())
@ -148,9 +148,9 @@ class ConfigDialog(QtGui.QDialog):
morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false"))) morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
settings.endGroup() settings.endGroup()
if morestate == "true": if morestate == "true":
return(True) return True
else: else:
return(False) return False
def saveMoreState(self, morestate): def saveMoreState(self, morestate):
settings = QSettings("Syncplay", "MoreSettings") settings = QSettings("Syncplay", "MoreSettings")
@ -161,11 +161,11 @@ class ConfigDialog(QtGui.QDialog):
def browseMediapath(self): def browseMediapath(self):
self.loadMediaBrowseSettings() self.loadMediaBrowseSettings()
options = QtGui.QFileDialog.Options() options = QtGui.QFileDialog.Options()
if (os.path.isdir(self.mediadirectory)): if os.path.isdir(self.mediadirectory):
defaultdirectory = self.mediadirectory defaultdirectory = self.mediadirectory
elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)):
defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)):
defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
else: else:
defaultdirectory = "" defaultdirectory = ""
@ -240,13 +240,13 @@ class ConfigDialog(QtGui.QDialog):
def dragEnterEvent(self, event): def dragEnterEvent(self, event):
data = event.mimeData() data = event.mimeData()
urls = data.urls() urls = data.urls()
if (urls and urls[0].scheme() == 'file'): if urls and urls[0].scheme() == 'file':
event.acceptProposedAction() event.acceptProposedAction()
def dropEvent(self, event): def dropEvent(self, event):
data = event.mimeData() data = event.mimeData()
urls = data.urls() urls = data.urls()
if (urls and urls[0].scheme() == 'file'): if urls and urls[0].scheme() == 'file':
if sys.platform.startswith('linux'): if sys.platform.startswith('linux'):
dropfilepath = unicode(urls[0].path()) dropfilepath = unicode(urls[0].path())
else: else:
@ -285,9 +285,9 @@ class ConfigDialog(QtGui.QDialog):
self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint) self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))
if(config['host'] == None): if config['host'] == None:
host = "" host = ""
elif(":" in config['host']): elif ":" in config['host']:
host = config['host'] host = config['host']
else: else:
host = config['host'] + ":" + str(config['port']) host = config['host'] + ":" + str(config['port'])

View File

@ -5,7 +5,7 @@ except ImportError:
from syncplay.ui.consoleUI import ConsoleUI from syncplay.ui.consoleUI import ConsoleUI
def getUi(graphical=True): def getUi(graphical=True):
if(graphical): #TODO: Add graphical ui if graphical: #TODO: Add graphical ui
ui = GraphicalUI() ui = GraphicalUI()
else: else:
ui = ConsoleUI() ui = ConsoleUI()

View File

@ -28,10 +28,10 @@ class ConsoleUI(threading.Thread):
while True: while True:
data = raw_input().decode(sys.stdin.encoding) data = raw_input().decode(sys.stdin.encoding)
data = data.rstrip('\n\r') data = data.rstrip('\n\r')
if(not self.promptMode.isSet()): if not self.promptMode.isSet():
self.PromptResult = data self.PromptResult = data
self.promptMode.set() self.promptMode.set()
elif(self._syncplayClient): elif self._syncplayClient:
self._executeCommand(data) self._executeCommand(data)
except EOFError: except EOFError:
pass pass
@ -50,12 +50,12 @@ class ConsoleUI(threading.Thread):
self.showMessage(message, True) self.showMessage(message, True)
for user in rooms[room]: for user in rooms[room]:
username = "*<{}>*".format(user.username) if user == currentUser else "<{}>".format(user.username) username = "*<{}>*".format(user.username) if user == currentUser else "<{}>".format(user.username)
if(user.file): if user.file:
message = u"{} is playing:".format(username) message = u"{} is playing:".format(username)
self.showMessage(message, True) self.showMessage(message, True)
message = u" File: '{}' ({})".format(user.file['name'], formatTime(user.file['duration'])) message = u" File: '{}' ({})".format(user.file['name'], formatTime(user.file['duration']))
if(currentUser.file): if currentUser.file:
if(user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']): if user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']:
message += " (their file size is different from yours!)" message += " (their file size is different from yours!)"
self.showMessage(message, True) self.showMessage(message, True)
else: else:
@ -67,7 +67,7 @@ class ConsoleUI(threading.Thread):
def showMessage(self, message, noTimestamp=False): def showMessage(self, message, noTimestamp=False):
message = message.encode(sys.stdout.encoding, 'replace') message = message.encode(sys.stdout.encoding, 'replace')
if(noTimestamp): if noTimestamp:
print(message) print(message)
else: else:
print(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message) print(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message)
@ -79,8 +79,8 @@ class ConsoleUI(threading.Thread):
print("ERROR:\t" + message) print("ERROR:\t" + message)
def _extractSign(self, m): def _extractSign(self, m):
if(m): if m:
if(m == "-"): if m == "-":
return -1 return -1
else: else:
return 1 return 1
@ -90,23 +90,23 @@ class ConsoleUI(threading.Thread):
def _tryAdvancedCommands(self, data): def _tryAdvancedCommands(self, data):
o = re.match(constants.UI_OFFSET_REGEX, data) o = re.match(constants.UI_OFFSET_REGEX, data)
s = re.match(constants.UI_SEEK_REGEX, data) s = re.match(constants.UI_SEEK_REGEX, data)
if(o): if o:
sign = self._extractSign(o.group('sign')) sign = self._extractSign(o.group('sign'))
t = utils.parseTime(o.group('time')) t = utils.parseTime(o.group('time'))
if(t is None): if t is None:
return return
if (o.group('sign') == "/"): if o.group('sign') == "/":
t = self._syncplayClient.getPlayerPosition() - t t = self._syncplayClient.getPlayerPosition() - t
elif(sign): elif sign:
t = self._syncplayClient.getUserOffset() + sign * t t = self._syncplayClient.getUserOffset() + sign * t
self._syncplayClient.setUserOffset(t) self._syncplayClient.setUserOffset(t)
return True return True
elif s: elif s:
sign = self._extractSign(s.group('sign')) sign = self._extractSign(s.group('sign'))
t = utils.parseTime(s.group('time')) t = utils.parseTime(s.group('time'))
if(t is None): if t is None:
return return
if(sign): if sign:
t = self._syncplayClient.getGlobalPosition() + sign * t t = self._syncplayClient.getGlobalPosition() + sign * t
self._syncplayClient.setPosition(t) self._syncplayClient.setPosition(t)
return True return True
@ -114,17 +114,17 @@ class ConsoleUI(threading.Thread):
def _executeCommand(self, data): def _executeCommand(self, data):
command = re.match(constants.UI_COMMAND_REGEX, data) command = re.match(constants.UI_COMMAND_REGEX, data)
if(not command): if not command:
return return
if(command.group('command') in constants.COMMANDS_UNDO): if command.group('command') in constants.COMMANDS_UNDO:
tmp_pos = self._syncplayClient.getPlayerPosition() tmp_pos = self._syncplayClient.getPlayerPosition()
self._syncplayClient.setPosition(self._syncplayClient.playerPositionBeforeLastSeek) self._syncplayClient.setPosition(self._syncplayClient.playerPositionBeforeLastSeek)
self._syncplayClient.playerPositionBeforeLastSeek = tmp_pos self._syncplayClient.playerPositionBeforeLastSeek = tmp_pos
elif (command.group('command') in constants.COMMANDS_LIST): elif command.group('command') in constants.COMMANDS_LIST:
self._syncplayClient.getUserList() self._syncplayClient.getUserList()
elif (command.group('command') in constants.COMMANDS_PAUSE): elif command.group('command') in constants.COMMANDS_PAUSE:
self._syncplayClient.setPaused(not self._syncplayClient.getPlayerPaused()) self._syncplayClient.setPaused(not self._syncplayClient.getPlayerPaused())
elif (command.group('command') in constants.COMMANDS_ROOM): elif command.group('command') in constants.COMMANDS_ROOM:
room = command.group('parameter') room = command.group('parameter')
if room == None: if room == None:
if self._syncplayClient.userlist.currentUser.file: if self._syncplayClient.userlist.currentUser.file:
@ -135,9 +135,9 @@ class ConsoleUI(threading.Thread):
self._syncplayClient.setRoom(room) self._syncplayClient.setRoom(room)
self._syncplayClient.sendRoom() self._syncplayClient.sendRoom()
else: else:
if(self._tryAdvancedCommands(data)): if self._tryAdvancedCommands(data):
return return
if (command.group('command') not in constants.COMMANDS_HELP): if command.group('command') not in constants.COMMANDS_HELP:
self.showMessage(getMessage("unrecognized-command-notification")) self.showMessage(getMessage("unrecognized-command-notification"))
self.showMessage(getMessage("commandlist-notification"), True) self.showMessage(getMessage("commandlist-notification"), True)
self.showMessage(getMessage("commandlist-notification/room"), True) self.showMessage(getMessage("commandlist-notification/room"), True)

View File

@ -23,7 +23,7 @@ class MainWindow(QtGui.QMainWindow):
message = message.replace("&lt;", "<span style=\"color:#367AA9;font-weight:bold;\">&lt;") message = message.replace("&lt;", "<span style=\"color:#367AA9;font-weight:bold;\">&lt;")
message = message.replace("&gt;", "&gt;</span>") message = message.replace("&gt;", "&gt;</span>")
message = message.replace("\n", "<br />") message = message.replace("\n", "<br />")
if(noTimestamp): if noTimestamp:
self.newMessage(message + "<br />") self.newMessage(message + "<br />")
else: else:
self.newMessage(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message + "<br />") self.newMessage(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message + "<br />")
@ -36,7 +36,7 @@ class MainWindow(QtGui.QMainWindow):
for room in rooms: for room in rooms:
roomitem = QtGui.QStandardItem(room) roomitem = QtGui.QStandardItem(room)
if (room == currentUser.room): if room == currentUser.room:
font = QtGui.QFont() font = QtGui.QFont()
font.setWeight(QtGui.QFont.Bold) font.setWeight(QtGui.QFont.Bold)
roomitem.setFont(font) roomitem.setFont(font)
@ -47,9 +47,9 @@ class MainWindow(QtGui.QMainWindow):
for user in rooms[room]: for user in rooms[room]:
useritem = QtGui.QStandardItem(user.username) useritem = QtGui.QStandardItem(user.username)
fileitem = QtGui.QStandardItem("") fileitem = QtGui.QStandardItem("")
if (user.file): if user.file:
fileitem = QtGui.QStandardItem(u"{} ({})".format(user.file['name'], formatTime(user.file['duration']))) fileitem = QtGui.QStandardItem(u"{} ({})".format(user.file['name'], formatTime(user.file['duration'])))
if (currentUser.file): if currentUser.file:
sameName = sameFilename(user.file['name'], currentUser.file['name']) sameName = sameFilename(user.file['name'], currentUser.file['name'])
sameSize = sameFilesize(user.file['size'], currentUser.file['size']) sameSize = sameFilesize(user.file['size'], currentUser.file['size'])
sameDuration = sameFileduration(user.file['duration'], currentUser.file['duration']) sameDuration = sameFileduration(user.file['duration'], currentUser.file['duration'])
@ -57,20 +57,20 @@ class MainWindow(QtGui.QMainWindow):
differentName = not sameName differentName = not sameName
differentSize = not sameSize differentSize = not sameSize
differentDuration = not sameDuration differentDuration = not sameDuration
if (sameName or sameRoom): if sameName or sameRoom:
if (differentSize and sameDuration): if differentSize and sameDuration:
fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentsize-note"))) fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentsize-note")))
elif (differentSize and differentDuration): elif differentSize and differentDuration:
fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentsizeandduration-note"))) fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentsizeandduration-note")))
elif (differentDuration): elif differentDuration:
fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentduration-note"))) fileitem = QtGui.QStandardItem(u"{} ({}) ({})".format(user.file['name'], formatTime(user.file['duration']), getMessage("differentduration-note")))
if (sameRoom and (differentName or differentSize or differentDuration)): if sameRoom and (differentName or differentSize or differentDuration):
fileitem.setForeground(QtGui.QBrush(QtGui.QColor('red'))) fileitem.setForeground(QtGui.QBrush(QtGui.QColor('red')))
else: else:
fileitem = QtGui.QStandardItem(getMessage("nofile-note")) fileitem = QtGui.QStandardItem(getMessage("nofile-note"))
if (room == currentUser.room): if room == currentUser.room:
fileitem.setForeground(QtGui.QBrush(QtGui.QColor('blue'))) fileitem.setForeground(QtGui.QBrush(QtGui.QColor('blue')))
if(currentUser.username == user.username): if currentUser.username == user.username:
font = QtGui.QFont() font = QtGui.QFont()
font.setWeight(QtGui.QFont.Bold) font.setWeight(QtGui.QFont.Bold)
useritem.setFont(font) useritem.setFont(font)
@ -86,7 +86,7 @@ class MainWindow(QtGui.QMainWindow):
self.listTreeView.resizeColumnToContents(1) self.listTreeView.resizeColumnToContents(1)
def roomClicked(self, item): def roomClicked(self, item):
while(item.parent().row() != -1): while item.parent().row() != -1:
item = item.parent() item = item.parent()
self.joinRoom(item.sibling(item.row(), 0).data()) self.joinRoom(item.sibling(item.row(), 0).data())
@ -114,18 +114,18 @@ class MainWindow(QtGui.QMainWindow):
else: else:
room = self._syncplayClient.defaultRoom room = self._syncplayClient.defaultRoom
self.roomInput.setText(room) self.roomInput.setText(room)
if(room != self._syncplayClient.getRoom()): if room != self._syncplayClient.getRoom():
self._syncplayClient.setRoom(room) self._syncplayClient.setRoom(room)
self._syncplayClient.sendRoom() self._syncplayClient.sendRoom()
def seekPosition(self): def seekPosition(self):
s = re.match(constants.UI_SEEK_REGEX, self.seekInput.text()) s = re.match(constants.UI_SEEK_REGEX, self.seekInput.text())
if(s): if s:
sign = self._extractSign(s.group('sign')) sign = self._extractSign(s.group('sign'))
t = utils.parseTime(s.group('time')) t = utils.parseTime(s.group('time'))
if(t is None): if t is None:
return return
if(sign): if sign:
t = self._syncplayClient.getGlobalPosition() + sign * t t = self._syncplayClient.getGlobalPosition() + sign * t
self._syncplayClient.setPosition(t) self._syncplayClient.setPosition(t)
@ -168,11 +168,11 @@ class MainWindow(QtGui.QMainWindow):
def browseMediapath(self): def browseMediapath(self):
self.loadMediaBrowseSettings() self.loadMediaBrowseSettings()
options = QtGui.QFileDialog.Options() options = QtGui.QFileDialog.Options()
if (os.path.isdir(self.mediadirectory)): if os.path.isdir(self.mediadirectory):
defaultdirectory = self.mediadirectory defaultdirectory = self.mediadirectory
elif (os.path.isdir(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MoviesLocation))): elif os.path.isdir(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MoviesLocation)):
defaultdirectory = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MoviesLocation) defaultdirectory = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MoviesLocation)
elif (os.path.isdir(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation))): elif os.path.isdir(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation)):
defaultdirectory = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation) defaultdirectory = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.HomeLocation)
else: else:
defaultdirectory = "" defaultdirectory = ""
@ -187,8 +187,8 @@ class MainWindow(QtGui.QMainWindow):
self._syncplayClient._player.openFile(fileName) self._syncplayClient._player.openFile(fileName)
def _extractSign(self, m): def _extractSign(self, m):
if(m): if m:
if(m == "-"): if m == "-":
return -1 return -1
else: else:
return 1 return 1
@ -201,14 +201,14 @@ class MainWindow(QtGui.QMainWindow):
"") "")
if ok and newoffset != '': if ok and newoffset != '':
o = re.match(constants.UI_OFFSET_REGEX, "o " + newoffset) o = re.match(constants.UI_OFFSET_REGEX, "o " + newoffset)
if(o): if o:
sign = self._extractSign(o.group('sign')) sign = self._extractSign(o.group('sign'))
t = utils.parseTime(o.group('time')) t = utils.parseTime(o.group('time'))
if(t is None): if t is None:
return return
if (o.group('sign') == "/"): if o.group('sign') == "/":
t = self._syncplayClient.getPlayerPosition() - t t = self._syncplayClient.getPlayerPosition() - t
elif(sign): elif sign:
t = self._syncplayClient.getUserOffset() + sign * t t = self._syncplayClient.getUserOffset() + sign * t
self._syncplayClient.setUserOffset(t) self._syncplayClient.setUserOffset(t)
else: else:
@ -400,7 +400,7 @@ class MainWindow(QtGui.QMainWindow):
def dragEnterEvent(self, event): def dragEnterEvent(self, event):
data = event.mimeData() data = event.mimeData()
urls = data.urls() urls = data.urls()
if (urls and urls[0].scheme() == 'file'): if urls and urls[0].scheme() == 'file':
event.acceptProposedAction() event.acceptProposedAction()
def dropEvent(self, event): def dropEvent(self, event):
@ -410,7 +410,7 @@ class MainWindow(QtGui.QMainWindow):
rewindFile = True rewindFile = True
data = event.mimeData() data = event.mimeData()
urls = data.urls() urls = data.urls()
if (urls and urls[0].scheme() == 'file'): if urls and urls[0].scheme() == 'file':
if sys.platform.startswith('linux'): if sys.platform.startswith('linux'):
dropfilepath = unicode(urls[0].path()) dropfilepath = unicode(urls[0].path())
else: else:

View File

@ -58,14 +58,14 @@ def parseTime(timeStr):
time_params = {} time_params = {}
for (name, param) in parts.iteritems(): for (name, param) in parts.iteritems():
if param: if param:
if(name == "miliseconds"): if name == "miliseconds":
time_params["microseconds"] = int(param) * 1000 time_params["microseconds"] = int(param) * 1000
else: else:
time_params[name] = int(param) time_params[name] = int(param)
return datetime.timedelta(**time_params).total_seconds() return datetime.timedelta(**time_params).total_seconds()
def formatTime(timeInSeconds, weeksAsTitles=True): def formatTime(timeInSeconds, weeksAsTitles=True):
if(timeInSeconds < 0): if timeInSeconds < 0:
timeInSeconds = -timeInSeconds timeInSeconds = -timeInSeconds
sign = '-' sign = '-'
else: else:
@ -81,11 +81,11 @@ def formatTime(timeInSeconds, weeksAsTitles=True):
hours = (timeInSeconds % 86400) // 3600 hours = (timeInSeconds % 86400) // 3600
minutes = (timeInSeconds % 3600) // 60 minutes = (timeInSeconds % 3600) // 60
seconds = timeInSeconds % 60 seconds = timeInSeconds % 60
if(weeks > 0): if weeks > 0:
formattedTime = '{0:}{1:.0f}w, {2:.0f}d, {3:02.0f}:{4:02.0f}:{5:02.0f}'.format(sign, weeks, days, hours, minutes, seconds) formattedTime = '{0:}{1:.0f}w, {2:.0f}d, {3:02.0f}:{4:02.0f}:{5:02.0f}'.format(sign, weeks, days, hours, minutes, seconds)
elif(days > 0): elif days > 0:
formattedTime = '{0:}{1:.0f}d, {2:02.0f}:{3:02.0f}:{4:02.0f}'.format(sign, days, hours, minutes, seconds) formattedTime = '{0:}{1:.0f}d, {2:02.0f}:{3:02.0f}:{4:02.0f}'.format(sign, days, hours, minutes, seconds)
elif(hours > 0): elif hours > 0:
formattedTime = '{0:}{1:02.0f}:{2:02.0f}:{3:02.0f}'.format(sign, hours, minutes, seconds) formattedTime = '{0:}{1:02.0f}:{2:02.0f}:{3:02.0f}'.format(sign, hours, minutes, seconds)
else: else:
formattedTime = '{0:}{1:02.0f}:{2:02.0f}'.format(sign, minutes, seconds) formattedTime = '{0:}{1:02.0f}:{2:02.0f}'.format(sign, minutes, seconds)
@ -114,7 +114,7 @@ def blackholeStdoutForFrozenWindow():
_error = None _error = None
def write(self, text, fname='.syncplay.log'): def write(self, text, fname='.syncplay.log'):
if self._file is None and self._error is None: if self._file is None and self._error is None:
if(os.name <> 'nt'): if os.name <> 'nt':
path = os.path.join(os.getenv('HOME', '.'), fname) path = os.path.join(os.getenv('HOME', '.'), fname)
else: else:
path = os.path.join(os.getenv('APPDATA', '.'), fname) path = os.path.join(os.getenv('APPDATA', '.'), fname)

View File

@ -5,7 +5,7 @@ import site, sys
# libpath # libpath
try: try:
if ((sys.version_info.major != 2) or (sys.version_info.minor < 7)): if (sys.version_info.major != 2) or (sys.version_info.minor < 7):
raise Exception("You must run Syncplay with Python 2.7!") raise Exception("You must run Syncplay with Python 2.7!")
except AttributeError: except AttributeError:
import warnings import warnings
@ -14,7 +14,7 @@ except AttributeError:
from syncplay.clientManager import SyncplayClientManager from syncplay.clientManager import SyncplayClientManager
from syncplay.utils import blackholeStdoutForFrozenWindow from syncplay.utils import blackholeStdoutForFrozenWindow
if(__name__ == '__main__'): if __name__ == '__main__':
blackholeStdoutForFrozenWindow() blackholeStdoutForFrozenWindow()
SyncplayClientManager().run() SyncplayClientManager().run()

View File

@ -6,7 +6,7 @@ import site, sys
# libpath # libpath
try: try:
if ((sys.version_info.major != 2) or (sys.version_info.minor < 7)): if (sys.version_info.major != 2) or (sys.version_info.minor < 7):
raise Exception("You must run Syncplay with Python 2.7!") raise Exception("You must run Syncplay with Python 2.7!")
except AttributeError: except AttributeError:
import warnings import warnings