mirror of
https://github.com/Syncplay/syncplay
synced 2025-01-20 14:00:46 +00:00
Applied fix: "Remove redundant parameters"
This commit is contained in:
parent
6a191f8e24
commit
d6d09e403c
@ -515,7 +515,7 @@ class NSISScript(object):
|
||||
installFiles = self.prepareInstallListTemplate(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))
|
||||
contents = Template(NSIS_SCRIPT_TEMPLATE).substitute(
|
||||
version = syncplay.version,
|
||||
@ -527,7 +527,7 @@ class NSISScript(object):
|
||||
outfile.write(contents)
|
||||
|
||||
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"
|
||||
subproc = subprocess.Popen([NSIS_COMPILE, SETUP_SCRIPT_PATH], env=os.environ)
|
||||
subproc.communicate()
|
||||
@ -543,7 +543,7 @@ class NSISScript(object):
|
||||
totalSize += sum(os.path.getsize(os.path.join(root, file_)) for file_ in files)
|
||||
for file_ in files:
|
||||
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].append(file_)
|
||||
return fileList, totalSize
|
||||
|
@ -62,16 +62,16 @@ class SyncplayClient(object):
|
||||
self.userlist = SyncplayUserlist(self.ui, self)
|
||||
self._protocol = None
|
||||
self._player = None
|
||||
if(config['room'] == None or config['room'] == ''):
|
||||
if config['room'] == None or config['room'] == '':
|
||||
config['room'] = config['name'] # ticket #58
|
||||
self.defaultRoom = config['room']
|
||||
self.playerPositionBeforeLastSeek = 0.0
|
||||
self.setUsername(config['name'])
|
||||
self.setRoom(config['room'])
|
||||
if(config['password']):
|
||||
if config['password']:
|
||||
config['password'] = hashlib.md5(config['password']).hexdigest()
|
||||
self._serverPassword = config['password']
|
||||
if(not config['file']):
|
||||
if not config['file']:
|
||||
self.__getUserlistOnLogon = True
|
||||
else:
|
||||
self.__getUserlistOnLogon = False
|
||||
@ -99,7 +99,7 @@ class SyncplayClient(object):
|
||||
self._protocol = protocol
|
||||
|
||||
def destroyProtocol(self):
|
||||
if(self._protocol):
|
||||
if self._protocol:
|
||||
self._protocol.drop()
|
||||
self._protocol = None
|
||||
|
||||
@ -112,14 +112,14 @@ class SyncplayClient(object):
|
||||
self._askPlayerTimer.start(when)
|
||||
|
||||
def askPlayer(self):
|
||||
if(not self._running):
|
||||
if not self._running:
|
||||
return
|
||||
if(self._player):
|
||||
if self._player:
|
||||
self._player.askForStatus()
|
||||
self.checkIfConnected()
|
||||
|
||||
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.ui.showErrorMessage(getMessage("server-timeout-error"))
|
||||
self._protocol.drop()
|
||||
@ -138,10 +138,10 @@ class SyncplayClient(object):
|
||||
pauseChange, seeked = self._determinePlayerStateChange(paused, position)
|
||||
self._playerPosition = position
|
||||
self._playerPaused = paused
|
||||
if(self._lastGlobalUpdate):
|
||||
if self._lastGlobalUpdate:
|
||||
self._lastPlayerUpdate = time.time()
|
||||
if((pauseChange or seeked) and self._protocol):
|
||||
if(seeked):
|
||||
if (pauseChange or seeked) and self._protocol:
|
||||
if seeked:
|
||||
self.playerPositionBeforeLastSeek = self.getGlobalPosition()
|
||||
self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), seeked, None, True)
|
||||
|
||||
@ -152,13 +152,13 @@ class SyncplayClient(object):
|
||||
else:
|
||||
position = self.getPlayerPosition()
|
||||
pauseChange, _ = self._determinePlayerStateChange(paused, position)
|
||||
if(self._lastGlobalUpdate):
|
||||
if self._lastGlobalUpdate:
|
||||
return position, paused, _, pauseChange
|
||||
else:
|
||||
return None, None, None, None
|
||||
|
||||
def _initPlayerState(self, position, paused):
|
||||
if(self.userlist.currentUser.file):
|
||||
if self.userlist.currentUser.file:
|
||||
self.setPosition(position)
|
||||
self._player.setPaused(paused)
|
||||
madeChangeOnPlayer = True
|
||||
@ -192,7 +192,7 @@ class SyncplayClient(object):
|
||||
|
||||
def _serverSeeked(self, position, setBy):
|
||||
hideFromOSD = not constants.SHOW_SAME_ROOM_OSD
|
||||
if(self.getUsername() <> setBy):
|
||||
if self.getUsername() <> setBy:
|
||||
self.playerPositionBeforeLastSeek = self.getPlayerPosition()
|
||||
self.setPosition(position)
|
||||
madeChangeOnPlayer = True
|
||||
@ -204,11 +204,11 @@ class SyncplayClient(object):
|
||||
|
||||
def _slowDownToCoverTimeDifference(self, diff, setBy):
|
||||
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._speedChanged = True
|
||||
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._speedChanged = False
|
||||
self.ui.showMessage(getMessage("revert-notification"), hideFromOSD)
|
||||
@ -219,39 +219,39 @@ class SyncplayClient(object):
|
||||
madeChangeOnPlayer = False
|
||||
pauseChanged = paused != self.getGlobalPaused()
|
||||
diff = self.getPlayerPosition() - position
|
||||
if(self._lastGlobalUpdate is None):
|
||||
if self._lastGlobalUpdate is None:
|
||||
madeChangeOnPlayer = self._initPlayerState(position, paused)
|
||||
self._globalPaused = paused
|
||||
self._globalPosition = position
|
||||
self._lastGlobalUpdate = time.time()
|
||||
if (doSeek):
|
||||
if doSeek:
|
||||
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)
|
||||
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._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):
|
||||
madeChangeOnPlayer = self._slowDownToCoverTimeDifference(diff, setBy)
|
||||
if (paused == False and pauseChanged):
|
||||
if paused == False and pauseChanged:
|
||||
madeChangeOnPlayer = self._serverUnpaused(setBy)
|
||||
elif (paused == True and pauseChanged):
|
||||
elif paused == True and pauseChanged:
|
||||
madeChangeOnPlayer = self._serverPaused(setBy)
|
||||
return madeChangeOnPlayer
|
||||
|
||||
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.userlist.roomStateConfirmed()
|
||||
|
||||
def updateGlobalState(self, position, paused, doSeek, setBy, messageAge):
|
||||
if(self.__getUserlistOnLogon):
|
||||
if self.__getUserlistOnLogon:
|
||||
self.__getUserlistOnLogon = False
|
||||
self.getUserList()
|
||||
madeChangeOnPlayer = False
|
||||
if(not paused):
|
||||
if not paused:
|
||||
position += messageAge
|
||||
if(self._player):
|
||||
if self._player:
|
||||
madeChangeOnPlayer = self._changePlayerStateAccordingToGlobalState(position, paused, doSeek, setBy)
|
||||
if(madeChangeOnPlayer):
|
||||
if madeChangeOnPlayer:
|
||||
self.askPlayer()
|
||||
self._executePlaystateHooks(position, paused, doSeek, setBy, messageAge)
|
||||
|
||||
@ -264,29 +264,29 @@ class SyncplayClient(object):
|
||||
self.ui.showMessage(getMessage("current-offset-notification").format(self._userOffset))
|
||||
|
||||
def onDisconnect(self):
|
||||
if(self._config['pauseOnLeave']):
|
||||
if self._config['pauseOnLeave']:
|
||||
self.setPaused(True)
|
||||
|
||||
def removeUser(self, username):
|
||||
if(self.userlist.isUserInYourRoom(username)):
|
||||
if self.userlist.isUserInYourRoom(username):
|
||||
self.onDisconnect()
|
||||
self.userlist.removeUser(username)
|
||||
|
||||
def getPlayerPosition(self):
|
||||
if(not self._lastPlayerUpdate):
|
||||
if(self._lastGlobalUpdate):
|
||||
if not self._lastPlayerUpdate:
|
||||
if self._lastGlobalUpdate:
|
||||
return self.getGlobalPosition()
|
||||
else:
|
||||
return 0.0
|
||||
position = self._playerPosition
|
||||
if(not self._playerPaused):
|
||||
if not self._playerPaused:
|
||||
diff = time.time() - self._lastPlayerUpdate
|
||||
position += diff
|
||||
return position
|
||||
|
||||
def getPlayerPaused(self):
|
||||
if(not self._lastPlayerUpdate):
|
||||
if(self._lastGlobalUpdate):
|
||||
if not self._lastPlayerUpdate:
|
||||
if self._lastGlobalUpdate:
|
||||
return self.getGlobalPaused()
|
||||
else:
|
||||
return True
|
||||
@ -301,7 +301,7 @@ class SyncplayClient(object):
|
||||
return position
|
||||
|
||||
def getGlobalPaused(self):
|
||||
if(not self._lastGlobalUpdate):
|
||||
if not self._lastGlobalUpdate:
|
||||
return True
|
||||
return self._globalPaused
|
||||
|
||||
@ -318,19 +318,19 @@ class SyncplayClient(object):
|
||||
self.sendFile()
|
||||
|
||||
def __executePrivacySettings(self, filename, size):
|
||||
if (self._config['filenamePrivacyMode'] == PRIVACY_SENDHASHED_MODE):
|
||||
if self._config['filenamePrivacyMode'] == PRIVACY_SENDHASHED_MODE:
|
||||
filename = utils.hashFilename(filename)
|
||||
elif (self._config['filenamePrivacyMode'] == PRIVACY_DONTSEND_MODE):
|
||||
elif self._config['filenamePrivacyMode'] == PRIVACY_DONTSEND_MODE:
|
||||
filename = PRIVACY_HIDDENFILENAME
|
||||
if (self._config['filesizePrivacyMode'] == PRIVACY_SENDHASHED_MODE):
|
||||
if self._config['filesizePrivacyMode'] == PRIVACY_SENDHASHED_MODE:
|
||||
size = utils.hashFilesize(size)
|
||||
elif (self._config['filesizePrivacyMode'] == PRIVACY_DONTSEND_MODE):
|
||||
elif self._config['filesizePrivacyMode'] == PRIVACY_DONTSEND_MODE:
|
||||
size = 0
|
||||
return filename, size
|
||||
|
||||
def sendFile(self):
|
||||
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_)
|
||||
|
||||
def setUsername(self, username):
|
||||
@ -350,7 +350,7 @@ class SyncplayClient(object):
|
||||
|
||||
def sendRoom(self):
|
||||
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.getUserList()
|
||||
|
||||
@ -358,7 +358,7 @@ class SyncplayClient(object):
|
||||
return self.userlist.currentUser.room
|
||||
|
||||
def getUserList(self):
|
||||
if(self._protocol and self._protocol.logged):
|
||||
if self._protocol and self._protocol.logged:
|
||||
self._protocol.sendList()
|
||||
|
||||
def showUserList(self):
|
||||
@ -369,14 +369,14 @@ class SyncplayClient(object):
|
||||
|
||||
def setPosition(self, position):
|
||||
position += self.getUserOffset()
|
||||
if(self._player and self.userlist.currentUser.file):
|
||||
if(position < 0):
|
||||
if self._player and self.userlist.currentUser.file:
|
||||
if position < 0:
|
||||
position = 0
|
||||
self._protocol.sendState(self.getPlayerPosition(), self.getPlayerPaused(), True, None, True)
|
||||
self._player.setPosition(position)
|
||||
|
||||
def setPaused(self, paused):
|
||||
if(self._player and self.userlist.currentUser.file):
|
||||
if self._player and self.userlist.currentUser.file:
|
||||
self._player.setPaused(paused)
|
||||
|
||||
def start(self, host, port):
|
||||
@ -403,7 +403,7 @@ class SyncplayClient(object):
|
||||
if self.ui:
|
||||
self.ui.drop()
|
||||
reactor.callLater(0.1, reactor.stop)
|
||||
if(promptForAction):
|
||||
if promptForAction:
|
||||
self.ui.promptFor(getMessage("enter-to-exit-prompt"))
|
||||
|
||||
class _WarningManager(object):
|
||||
@ -413,11 +413,13 @@ class SyncplayClient(object):
|
||||
self._ui = ui
|
||||
self._warnings = {
|
||||
"room-files-not-same": {
|
||||
"timer": task.LoopingCall(self.__displayMessageOnOSD, ("room-files-not-same"),),
|
||||
"timer": task.LoopingCall(self.__displayMessageOnOSD,
|
||||
"room-files-not-same",),
|
||||
"displayedFor": 0,
|
||||
},
|
||||
"alone-in-the-room": {
|
||||
"timer": task.LoopingCall(self.__displayMessageOnOSD, ("alone-in-the-room"),),
|
||||
"timer": task.LoopingCall(self.__displayMessageOnOSD,
|
||||
"alone-in-the-room",),
|
||||
"displayedFor": 0,
|
||||
},
|
||||
}
|
||||
@ -426,23 +428,23 @@ class SyncplayClient(object):
|
||||
self._checkRoomForSameFiles()
|
||||
|
||||
def _checkRoomForSameFiles(self):
|
||||
if (not self._userlist.areAllFilesInRoomSame()):
|
||||
if not self._userlist.areAllFilesInRoomSame():
|
||||
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)
|
||||
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()
|
||||
|
||||
def _checkIfYouReAloneInTheRoom(self):
|
||||
if (self._userlist.areYouAloneInRoom()):
|
||||
if self._userlist.areYouAloneInRoom():
|
||||
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)
|
||||
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()
|
||||
|
||||
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._warnings[warningName]["displayedFor"] += constants.WARNING_OSD_MESSAGES_LOOP_INTERVAL
|
||||
else:
|
||||
@ -466,7 +468,7 @@ class SyncplayUser(object):
|
||||
self.file = file_
|
||||
|
||||
def isFileSame(self, file_):
|
||||
if(not self.file):
|
||||
if not self.file:
|
||||
return False
|
||||
sameName = utils.sameFilename(self.file['name'], file_['name'])
|
||||
sameSize = utils.sameFilesize(self.file['size'], file_['size'])
|
||||
@ -477,7 +479,7 @@ class SyncplayUser(object):
|
||||
return self.username.lower() < other.username.lower()
|
||||
|
||||
def __repr__(self, *args, **kwargs):
|
||||
if(self.file):
|
||||
if self.file:
|
||||
return "{}: {} ({}, {})".format(self.username, self.file['name'], self.file['duration'], self.file['size'])
|
||||
else:
|
||||
return "{}".format(self.username)
|
||||
@ -491,60 +493,60 @@ class SyncplayUserlist(object):
|
||||
self._roomUsersChanged = True
|
||||
|
||||
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
|
||||
else:
|
||||
return False
|
||||
|
||||
def __showUserChangeMessage(self, username, room, file_, oldRoom=None):
|
||||
if(room):
|
||||
if room:
|
||||
if self.isRoomSame(room) or self.isRoomSame(oldRoom):
|
||||
showOnOSD = constants.SHOW_SAME_ROOM_OSD
|
||||
else:
|
||||
showOnOSD = constants.SHOW_DIFFERENT_ROOM_OSD
|
||||
hideFromOSD = not showOnOSD
|
||||
if(room and not file_):
|
||||
if room and not file_:
|
||||
message = getMessage("room-join-notification").format(username, room)
|
||||
self.ui.showMessage(message, hideFromOSD)
|
||||
elif (room and file_):
|
||||
elif room and file_:
|
||||
duration = utils.formatTime(file_['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)
|
||||
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)
|
||||
self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS)
|
||||
differences = []
|
||||
differentName = not utils.sameFilename(self.currentUser.file['name'], file_['name'])
|
||||
differentSize = not utils.sameFilesize(self.currentUser.file['size'], file_['size'])
|
||||
differentDuration = not utils.sameFileduration(self.currentUser.file['duration'], file_['duration'])
|
||||
if(differentName):
|
||||
if differentName:
|
||||
differences.append("filename")
|
||||
if(differentSize):
|
||||
if differentSize:
|
||||
differences.append("size")
|
||||
if(differentDuration):
|
||||
if differentDuration:
|
||||
differences.append("duration")
|
||||
message = getMessage("file-differences-notification") + ", ".join(differences)
|
||||
self.ui.showMessage(message, not constants.SHOW_OSD_WARNINGS)
|
||||
|
||||
def addUser(self, username, room, file_, noMessage=False):
|
||||
if(username == self.currentUser.username):
|
||||
if username == self.currentUser.username:
|
||||
return
|
||||
user = SyncplayUser(username, room, file_)
|
||||
self._users[username] = user
|
||||
if(not noMessage):
|
||||
if not noMessage:
|
||||
self.__showUserChangeMessage(username, room, file_)
|
||||
self.userListChange()
|
||||
|
||||
def removeUser(self, username):
|
||||
hideFromOSD = not constants.SHOW_DIFFERENT_ROOM_OSD
|
||||
if(self._users.has_key(username)):
|
||||
if self._users.has_key(username):
|
||||
user = self._users[username]
|
||||
if user.room:
|
||||
if self.isRoomSame(user.room):
|
||||
hideFromOSD = not constants.SHOW_SAME_ROOM_OSD
|
||||
if(self._users.has_key(username)):
|
||||
if self._users.has_key(username):
|
||||
self._users.pop(username)
|
||||
message = getMessage("left-notification").format(username)
|
||||
self.ui.showMessage(message, hideFromOSD)
|
||||
@ -553,20 +555,20 @@ class SyncplayUserlist(object):
|
||||
self.userListChange()
|
||||
|
||||
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)
|
||||
elif (room and room != user.room):
|
||||
elif room and room != user.room:
|
||||
self.__showUserChangeMessage(username, room, None, oldRoom)
|
||||
|
||||
def modUser(self, username, room, file_):
|
||||
if(self._users.has_key(username)):
|
||||
if self._users.has_key(username):
|
||||
user = self._users[username]
|
||||
oldRoom = user.room if user.room else None
|
||||
self.__displayModUserMessage(username, room, file_, user, oldRoom)
|
||||
user.room = room
|
||||
if file_:
|
||||
user.file = file_
|
||||
elif(username == self.currentUser.username):
|
||||
elif username == self.currentUser.username:
|
||||
self.__showUserChangeMessage(username, room, file_)
|
||||
else:
|
||||
self.addUser(username, room, file_)
|
||||
@ -574,19 +576,19 @@ class SyncplayUserlist(object):
|
||||
|
||||
def areAllFilesInRoomSame(self):
|
||||
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 True
|
||||
|
||||
def areYouAloneInRoom(self):
|
||||
for user in self._users.itervalues():
|
||||
if(user.room == self.currentUser.room):
|
||||
if user.room == self.currentUser.room:
|
||||
return False
|
||||
return True
|
||||
|
||||
def isUserInYourRoom(self, username):
|
||||
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 False
|
||||
|
||||
@ -603,10 +605,10 @@ class SyncplayUserlist(object):
|
||||
def showUserList(self):
|
||||
rooms = {}
|
||||
for user in self._users.itervalues():
|
||||
if(user.room not in rooms):
|
||||
if user.room not in rooms:
|
||||
rooms[user.room] = []
|
||||
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].append(self.currentUser)
|
||||
rooms = self.sortList(rooms)
|
||||
@ -628,14 +630,14 @@ class UiManager(object):
|
||||
self.lastError = ""
|
||||
|
||||
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)
|
||||
|
||||
def showUserList(self, currentUser, rooms):
|
||||
self.__ui.showUserList(currentUser, rooms)
|
||||
|
||||
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)
|
||||
|
||||
def showErrorMessage(self, message, criticalerror=False):
|
||||
|
@ -8,9 +8,9 @@ class SyncplayClientManager(object):
|
||||
from syncplay.client import SyncplayClient #Imported later, so the proper reactor is installed
|
||||
interface = ui.getUi(graphical=not config["noGui"])
|
||||
syncplayClient = SyncplayClient(config["playerClass"], interface, config)
|
||||
if(syncplayClient):
|
||||
if syncplayClient:
|
||||
interface.addClient(syncplayClient)
|
||||
syncplayClient.start(config['host'], config['port'])
|
||||
else:
|
||||
interface.showErrorMessage(getMessage("unable-to-start-client-error"), True)
|
||||
|
||||
|
||||
|
@ -294,20 +294,20 @@ def setLanguage(lang):
|
||||
messages["current"] = lang
|
||||
|
||||
def getMessage(type_, locale=None):
|
||||
if(constants.SHOW_BUTTON_LABELS == False):
|
||||
if("-guibuttonlabel" in type_):
|
||||
if constants.SHOW_BUTTON_LABELS == False:
|
||||
if "-guibuttonlabel" in type_:
|
||||
return ""
|
||||
if(constants.SHOW_TOOLTIPS == False):
|
||||
if("-tooltip" in type_):
|
||||
if constants.SHOW_TOOLTIPS == False:
|
||||
if "-tooltip" in type_:
|
||||
return ""
|
||||
lang = messages["current"]
|
||||
if(locale and messages.has_key(locale)):
|
||||
if(messages[locale].has_key(type_)):
|
||||
if locale and messages.has_key(locale):
|
||||
if messages[locale].has_key(type_):
|
||||
return unicode(messages[locale][type_])
|
||||
if(lang and messages.has_key(lang)):
|
||||
if(messages[lang].has_key(type_)):
|
||||
if lang and messages.has_key(lang):
|
||||
if messages[lang].has_key(type_):
|
||||
return unicode(messages[lang][type_])
|
||||
if(messages["en"].has_key(type_)):
|
||||
if messages["en"].has_key(type_):
|
||||
return unicode(messages["en"][type_])
|
||||
else:
|
||||
raise KeyError()
|
||||
|
@ -33,7 +33,7 @@ class MpcHcApi:
|
||||
def waitForFileStateReady(f): #@NoSelf
|
||||
@wraps(f)
|
||||
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()
|
||||
return f(self, *args, **kwds)
|
||||
return wrapper
|
||||
@ -41,7 +41,7 @@ class MpcHcApi:
|
||||
def startMpc(self, path, args=()):
|
||||
args = "%s /slave %s" % (" ".join(args), str(self.__listener.hwnd))
|
||||
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"))
|
||||
self.__mpcExistenceChecking.start()
|
||||
|
||||
@ -49,7 +49,7 @@ class MpcHcApi:
|
||||
self.__listener.SendCommand(self.CMD_OPENFILE, filePath)
|
||||
|
||||
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):
|
||||
self.__listener.SendCommand(self.CMD_GETVERSION)
|
||||
@ -95,61 +95,61 @@ class MpcHcApi:
|
||||
self.__listener.SendCommand(cmd, value)
|
||||
|
||||
def handleCommand(self, cmd, value):
|
||||
if (cmd == self.CMD_CONNECT):
|
||||
if cmd == self.CMD_CONNECT:
|
||||
self.__listener.mpcHandle = int(value)
|
||||
self.__locks.mpcStart.set()
|
||||
if(self.callbacks.onConnected):
|
||||
thread.start_new_thread(self.callbacks.onConnected, ())
|
||||
if self.callbacks.onConnected:
|
||||
thread.start_new_thread(self.callbacks.onConnected, ())
|
||||
|
||||
elif(cmd == self.CMD_STATE):
|
||||
elif cmd == self.CMD_STATE:
|
||||
self.loadState = int(value)
|
||||
fileNotReady = self.loadState == self.__MPC_LOADSTATE.MLS_CLOSING or self.loadState == self.__MPC_LOADSTATE.MLS_LOADING
|
||||
if(fileNotReady):
|
||||
if fileNotReady:
|
||||
self.playState = None
|
||||
self.__locks.fileReady.clear()
|
||||
else:
|
||||
self.__locks.fileReady.set()
|
||||
if(self.callbacks.onFileStateChange):
|
||||
thread.start_new_thread(self.callbacks.onFileStateChange, (self.loadState,))
|
||||
if self.callbacks.onFileStateChange:
|
||||
thread.start_new_thread(self.callbacks.onFileStateChange, (self.loadState,))
|
||||
|
||||
elif(cmd == self.CMD_PLAYMODE):
|
||||
elif cmd == self.CMD_PLAYMODE:
|
||||
self.playState = int(value)
|
||||
if(self.callbacks.onUpdatePlaystate):
|
||||
if self.callbacks.onUpdatePlaystate:
|
||||
thread.start_new_thread(self.callbacks.onUpdatePlaystate, (self.playState,))
|
||||
|
||||
elif(cmd == self.CMD_NOWPLAYING):
|
||||
elif cmd == self.CMD_NOWPLAYING:
|
||||
value = re.split(r'(?<!\\)\|', value)
|
||||
if self.filePath == value[3]:
|
||||
return
|
||||
self.filePath = value[3]
|
||||
self.filePlaying = value[3].split('\\').pop()
|
||||
self.fileDuration = float(value[4])
|
||||
if(self.callbacks.onUpdatePath):
|
||||
thread.start_new_thread(self.callbacks.onUpdatePath, (self.onUpdatePath,))
|
||||
if(self.callbacks.onUpdateFilename):
|
||||
thread.start_new_thread(self.callbacks.onUpdateFilename, (self.filePlaying,))
|
||||
if(self.callbacks.onUpdateFileDuration):
|
||||
thread.start_new_thread(self.callbacks.onUpdateFileDuration, (self.fileDuration,))
|
||||
if self.callbacks.onUpdatePath:
|
||||
thread.start_new_thread(self.callbacks.onUpdatePath, (self.onUpdatePath,))
|
||||
if self.callbacks.onUpdateFilename:
|
||||
thread.start_new_thread(self.callbacks.onUpdateFilename, (self.filePlaying,))
|
||||
if self.callbacks.onUpdateFileDuration:
|
||||
thread.start_new_thread(self.callbacks.onUpdateFileDuration, (self.fileDuration,))
|
||||
|
||||
elif(cmd == self.CMD_CURRENTPOSITION):
|
||||
elif cmd == self.CMD_CURRENTPOSITION:
|
||||
self.lastFilePosition = float(value)
|
||||
if(self.callbacks.onGetCurrentPosition):
|
||||
thread.start_new_thread(self.callbacks.onGetCurrentPosition, (self.lastFilePosition,))
|
||||
if self.callbacks.onGetCurrentPosition:
|
||||
thread.start_new_thread(self.callbacks.onGetCurrentPosition, (self.lastFilePosition,))
|
||||
|
||||
elif(cmd == self.CMD_NOTIFYSEEK):
|
||||
if(self.lastFilePosition <> float(value)): #Notify seek is sometimes sent twice
|
||||
elif cmd == self.CMD_NOTIFYSEEK:
|
||||
if self.lastFilePosition <> float(value): #Notify seek is sometimes sent twice
|
||||
self.lastFilePosition = float(value)
|
||||
if(self.callbacks.onSeek):
|
||||
if self.callbacks.onSeek:
|
||||
thread.start_new_thread(self.callbacks.onSeek, (self.lastFilePosition,))
|
||||
|
||||
elif(cmd == self.CMD_DISCONNECT):
|
||||
if(self.callbacks.onMpcClosed):
|
||||
thread.start_new_thread(self.callbacks.onMpcClosed, (None,))
|
||||
elif cmd == self.CMD_DISCONNECT:
|
||||
if self.callbacks.onMpcClosed:
|
||||
thread.start_new_thread(self.callbacks.onMpcClosed, (None,))
|
||||
|
||||
elif(cmd == self.CMD_VERSION):
|
||||
if(self.callbacks.onVersion):
|
||||
self.version = value
|
||||
thread.start_new_thread(self.callbacks.onVersion, (value,))
|
||||
elif cmd == self.CMD_VERSION:
|
||||
if self.callbacks.onVersion:
|
||||
self.version = value
|
||||
thread.start_new_thread(self.callbacks.onVersion, (value,))
|
||||
|
||||
class PlayerNotReadyException(Exception):
|
||||
pass
|
||||
@ -174,10 +174,10 @@ class MpcHcApi:
|
||||
self.fileReady = threading.Event()
|
||||
|
||||
def __mpcReadyInSlaveMode(self):
|
||||
while(True):
|
||||
while True:
|
||||
time.sleep(10)
|
||||
if not win32gui.IsWindow(self.__listener.mpcHandle):
|
||||
if(self.callbacks.onMpcClosed):
|
||||
if self.callbacks.onMpcClosed:
|
||||
self.callbacks.onMpcClosed(None)
|
||||
break
|
||||
|
||||
@ -281,14 +281,14 @@ class MpcHcApi:
|
||||
def SendCommand(self, cmd, message=u''):
|
||||
#print "API:\t<out\t 0x%X\t" % int(cmd), message
|
||||
if not win32gui.IsWindow(self.mpcHandle):
|
||||
if(self.__mpcApi.callbacks.onMpcClosed):
|
||||
if self.__mpcApi.callbacks.onMpcClosed:
|
||||
self.__mpcApi.callbacks.onMpcClosed(None)
|
||||
cs = self.__COPYDATASTRUCT()
|
||||
cs.dwData = cmd;
|
||||
|
||||
if(isinstance(message, (unicode, str))):
|
||||
if isinstance(message, (unicode, str)):
|
||||
message = ctypes.create_unicode_buffer(message, len(message) + 1)
|
||||
elif(isinstance(message, ctypes.Structure)):
|
||||
elif isinstance(message, ctypes.Structure):
|
||||
pass
|
||||
else:
|
||||
raise TypeError
|
||||
@ -314,7 +314,7 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
self.__client = client
|
||||
self._mpcApi = MpcHcApi()
|
||||
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.onUpdatePlaystate = lambda _: self.__unlockAsking()
|
||||
self._mpcApi.callbacks.onGetCurrentPosition = lambda _: self.__onGetPosition()
|
||||
@ -336,7 +336,7 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
def run(client, playerPath, filePath, args):
|
||||
args.extend(['/open', '/new'])
|
||||
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)
|
||||
client.initPlayer(mpc)
|
||||
return mpc
|
||||
@ -358,12 +358,12 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
|
||||
def __dropIfNotSufficientVersion(self):
|
||||
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.stop, True)
|
||||
|
||||
def __testMpcReady(self):
|
||||
if(not self.__preventAsking.wait(10)):
|
||||
if not self.__preventAsking.wait(10):
|
||||
raise Exception(getMessage("player-file-open-error"))
|
||||
|
||||
def __makePing(self):
|
||||
@ -378,14 +378,14 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
|
||||
def initPlayer(self, filePath):
|
||||
self.__dropIfNotSufficientVersion()
|
||||
if(not self._mpcApi.version):
|
||||
if not self._mpcApi.version:
|
||||
return
|
||||
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
|
||||
if(self.__mpcVersion[0:3] >= ['1', '6', '5']):
|
||||
if self.__mpcVersion[0:3] >= ['1', '6', '5']:
|
||||
self.speedSupported = True
|
||||
if(filePath):
|
||||
if filePath:
|
||||
self.openFile(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)
|
||||
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()
|
||||
position = self.__getPosition()
|
||||
paused = self._mpcApi.isPaused()
|
||||
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.__fileUpdate.release()
|
||||
return
|
||||
@ -444,9 +444,9 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
def _setPausedAccordinglyToServer(self):
|
||||
self.__forcePause()
|
||||
self.setPaused(self.__client.getGlobalPaused())
|
||||
if(self._mpcApi.isPaused() <> self.__client.getGlobalPaused()):
|
||||
if self._mpcApi.isPaused() <> self.__client.getGlobalPaused():
|
||||
self.__refreshMpcPlayState()
|
||||
if(self._mpcApi.isPaused() <> self.__client.getGlobalPaused()):
|
||||
if self._mpcApi.isPaused() <> self.__client.getGlobalPaused():
|
||||
self.__setUpStateForNewlyOpenedFile()
|
||||
|
||||
@retry(MpcHcApi.PlayerNotReadyException, constants.MPC_MAX_RETRIES, constants.MPC_RETRY_WAIT_TIME, 1)
|
||||
@ -469,31 +469,31 @@ class MPCHCAPIPlayer(BasePlayer):
|
||||
|
||||
@staticmethod
|
||||
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
|
||||
else:
|
||||
return constants.MPC_ICONPATH
|
||||
|
||||
@staticmethod
|
||||
def isValidPlayerPath(path):
|
||||
if(MPCHCAPIPlayer.getExpandedPath(path)):
|
||||
if MPCHCAPIPlayer.getExpandedPath(path):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def getExpandedPath(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 os.path.isfile(path):
|
||||
if path.lower().endswith(u'mpc-hc.exe'.lower()) or path.lower().endswith(u'mpc-hc64.exe'.lower()):
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
return path
|
||||
|
@ -29,7 +29,7 @@ class MpvPlayer(MplayerPlayer):
|
||||
|
||||
@staticmethod
|
||||
def isValidPlayerPath(path):
|
||||
if("mpv" in path and MpvPlayer.getExpandedPath(path)):
|
||||
if "mpv" in path and MpvPlayer.getExpandedPath(path):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
@ -12,17 +12,17 @@ class PlayerFactory(object):
|
||||
|
||||
def getPlayerByPath(self, path):
|
||||
for player in self._players:
|
||||
if(player.isValidPlayerPath(path)):
|
||||
if player.isValidPlayerPath(path):
|
||||
return player
|
||||
|
||||
def getPlayerIconByPath(self, path):
|
||||
for player in self._players:
|
||||
if(player.isValidPlayerPath(path)):
|
||||
if player.isValidPlayerPath(path):
|
||||
return player.getIconPath(path)
|
||||
return None
|
||||
|
||||
def getExpandedPlayerPathByPath(self, path):
|
||||
for player in self._players:
|
||||
if(player.isValidPlayerPath(path)):
|
||||
if player.isValidPlayerPath(path):
|
||||
return player.getExpandedPath(path)
|
||||
return None
|
||||
|
@ -43,15 +43,15 @@ class VlcPlayer(BasePlayer):
|
||||
self._listener = self.__Listener(self, playerPath, filePath, args, self._vlcready, self._vlcclosed)
|
||||
except ValueError:
|
||||
self._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True)
|
||||
self.reactor.callFromThread(self._client.stop, (True),)
|
||||
self.reactor.callFromThread(self._client.stop, True,)
|
||||
return
|
||||
self._listener.setDaemon(True)
|
||||
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._client.ui.showErrorMessage(getMessage("vlc-failed-connection"), True)
|
||||
self.reactor.callFromThread(self._client.stop, (True),)
|
||||
self.reactor.callFromThread(self._client.initPlayer, (self),)
|
||||
self.reactor.callFromThread(self._client.stop, True,)
|
||||
self.reactor.callFromThread(self._client.initPlayer, self,)
|
||||
|
||||
def _fileUpdateClearEvents(self):
|
||||
self._durationAsk.clear()
|
||||
@ -114,7 +114,7 @@ class VlcPlayer(BasePlayer):
|
||||
return all(ord(c) < 128 for c in s)
|
||||
|
||||
def openFile(self, filePath):
|
||||
if (self._isASCII(filePath) == True):
|
||||
if self._isASCII(filePath) == True:
|
||||
self._listener.sendLine('load-file: {}'.format(filePath.encode('ascii', 'ignore')))
|
||||
else:
|
||||
fileURL = self.getMRL(filePath)
|
||||
@ -130,39 +130,39 @@ class VlcPlayer(BasePlayer):
|
||||
if match:
|
||||
name, value = match.group('command'), match.group('argument')
|
||||
|
||||
if(line == "filepath-change-notification"):
|
||||
if line == "filepath-change-notification":
|
||||
self._filechanged = True
|
||||
t = threading.Thread(target=self._onFileUpdate)
|
||||
t.setDaemon(True)
|
||||
t.start()
|
||||
elif (name == "filepath" and value != "no-input"):
|
||||
elif name == "filepath" and value != "no-input":
|
||||
self._filechanged = True
|
||||
if("file://" in value):
|
||||
if "file://" in value:
|
||||
value = value.replace("file://", "")
|
||||
if(not os.path.isfile(value)):
|
||||
if not os.path.isfile(value):
|
||||
value = value.lstrip("/")
|
||||
self._filepath = value
|
||||
self._pathAsk.set()
|
||||
elif(name == "duration" and (value != "no-input")):
|
||||
elif name == "duration" and (value != "no-input"):
|
||||
self._duration = float(value.replace(",", "."))
|
||||
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._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._positionAsk.set()
|
||||
elif(name == "filename"):
|
||||
elif name == "filename":
|
||||
self._filechanged = True
|
||||
self._filename = value.decode('utf-8')
|
||||
self._filenameAsk.set()
|
||||
elif(line.startswith("interface-version: ")):
|
||||
elif line.startswith("interface-version: "):
|
||||
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)))
|
||||
elif (line[:16] == "VLC media player"):
|
||||
elif line[:16] == "VLC media player":
|
||||
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._vlcready.set()
|
||||
self._listener.sendLine("get-interface-version")
|
||||
@ -184,7 +184,7 @@ class VlcPlayer(BasePlayer):
|
||||
|
||||
@staticmethod
|
||||
def isValidPlayerPath(path):
|
||||
if("vlc" in path.lower() and VlcPlayer.getExpandedPath(path)):
|
||||
if "vlc" in path.lower() and VlcPlayer.getExpandedPath(path):
|
||||
return True
|
||||
return False
|
||||
|
||||
@ -218,14 +218,14 @@ class VlcPlayer(BasePlayer):
|
||||
self._positionAsk.set()
|
||||
self._vlcready.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):
|
||||
def __init__(self, playerController, playerPath, filePath, args, vlcReady, vlcClosed):
|
||||
self.__playerController = playerController
|
||||
call = [playerPath]
|
||||
if(filePath):
|
||||
if (self.__playerController._isASCII(filePath) == True):
|
||||
if filePath:
|
||||
if self.__playerController._isASCII(filePath) == True:
|
||||
call.append(filePath)
|
||||
else:
|
||||
call.append(self.__playerController.getMRL(filePath))
|
||||
@ -238,7 +238,7 @@ class VlcPlayer(BasePlayer):
|
||||
for line in interfacefile:
|
||||
if "local connectorversion" in line:
|
||||
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
|
||||
else:
|
||||
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)))
|
||||
|
||||
call.extend(playerController.SLAVE_ARGS)
|
||||
if(args):
|
||||
if args:
|
||||
call.extend(args)
|
||||
|
||||
self._vlcready = vlcReady
|
||||
@ -317,11 +317,11 @@ class VlcPlayer(BasePlayer):
|
||||
self._ibuffer = []
|
||||
|
||||
def sendLine(self, line):
|
||||
if(self.connected):
|
||||
if self.connected:
|
||||
# print "send: {}".format(line)
|
||||
try:
|
||||
self.push(line + "\n")
|
||||
except:
|
||||
pass
|
||||
if(line == "close-vlc"):
|
||||
if line == "close-vlc":
|
||||
self._vlcclosed.set()
|
||||
|
@ -76,15 +76,15 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
|
||||
def handleHello(self, 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))
|
||||
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)))
|
||||
else:
|
||||
self._client.setUsername(username)
|
||||
self._client.setRoom(roomName)
|
||||
self.logged = True
|
||||
if(motd):
|
||||
if motd:
|
||||
self._client.ui.showMessage(motd, True, True)
|
||||
self._client.ui.showMessage(getMessage("connected-successful-notification"))
|
||||
self._client.sendFile()
|
||||
@ -93,9 +93,9 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
hello = {}
|
||||
hello["username"] = self._client.getUsername()
|
||||
password = self._client.getPassword()
|
||||
if(password): hello["password"] = password
|
||||
if password: hello["password"] = password
|
||||
room = self._client.getRoom()
|
||||
if(room): hello["room"] = {"name" :room}
|
||||
if room: hello["room"] = {"name" :room}
|
||||
hello["version"] = syncplay.version
|
||||
self.sendMessage({"Hello": hello})
|
||||
|
||||
@ -105,10 +105,10 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
settings = user[1]
|
||||
room = settings["room"]["name"] if settings.has_key("room") else None
|
||||
file_ = settings["file"] if settings.has_key("file") else None
|
||||
if(settings.has_key("event")):
|
||||
if(settings["event"].has_key("joined")):
|
||||
if settings.has_key("event"):
|
||||
if settings["event"].has_key("joined"):
|
||||
self._client.userlist.addUser(username, room, file_)
|
||||
elif(settings["event"].has_key("left")):
|
||||
elif settings["event"].has_key("left"):
|
||||
self._client.removeUser(username)
|
||||
else:
|
||||
self._client.userlist.modUser(username, room, file_)
|
||||
@ -128,7 +128,7 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
def sendRoomSetting(self, roomName, password=None):
|
||||
setting = {}
|
||||
setting["name"] = roomName
|
||||
if(password): setting["password"] = password
|
||||
if password: setting["password"] = password
|
||||
self.sendSet({"room": setting})
|
||||
|
||||
def sendFileSetting(self, file_):
|
||||
@ -156,9 +156,9 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
return position, paused, doSeek, setBy
|
||||
|
||||
def _handleStatePing(self, state):
|
||||
if (state["ping"].has_key("latencyCalculation")):
|
||||
if state["ping"].has_key("latencyCalculation"):
|
||||
latencyCalculation = state["ping"]["latencyCalculation"]
|
||||
if ("clientLatencyCalculation" in state["ping"]):
|
||||
if "clientLatencyCalculation" in state["ping"]:
|
||||
timestamp = state["ping"]["clientLatencyCalculation"]
|
||||
senderRtt = state["ping"]["serverRtt"]
|
||||
self._pingService.receiveMessage(timestamp, senderRtt)
|
||||
@ -168,19 +168,19 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
def handleState(self, state):
|
||||
position, paused, doSeek, setBy = None, None, None, None
|
||||
messageAge = 0
|
||||
if(state.has_key("ignoringOnTheFly")):
|
||||
if state.has_key("ignoringOnTheFly"):
|
||||
ignore = state["ignoringOnTheFly"]
|
||||
if(ignore.has_key("server")):
|
||||
if ignore.has_key("server"):
|
||||
self.serverIgnoringOnTheFly = ignore["server"]
|
||||
self.clientIgnoringOnTheFly = 0
|
||||
elif(ignore.has_key("client")):
|
||||
elif ignore.has_key("client"):
|
||||
if(ignore['client']) == self.clientIgnoringOnTheFly:
|
||||
self.clientIgnoringOnTheFly = 0
|
||||
if(state.has_key("playstate")):
|
||||
if state.has_key("playstate"):
|
||||
position, paused, doSeek, setBy = self._extractStatePlaystateArguments(state)
|
||||
if(state.has_key("ping")):
|
||||
if state.has_key("ping"):
|
||||
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)
|
||||
position, paused, doSeek, stateChange = self._client.getLocalState()
|
||||
self.sendState(position, paused, doSeek, latencyCalculation, stateChange)
|
||||
@ -189,24 +189,24 @@ class SyncClientProtocol(JSONCommandProtocol):
|
||||
state = {}
|
||||
positionAndPausedIsSet = position is not None and paused is not None
|
||||
clientIgnoreIsNotSet = self.clientIgnoringOnTheFly == 0 or self.serverIgnoringOnTheFly != 0
|
||||
if(clientIgnoreIsNotSet and positionAndPausedIsSet):
|
||||
if clientIgnoreIsNotSet and positionAndPausedIsSet:
|
||||
state["playstate"] = {}
|
||||
state["playstate"]["position"] = position
|
||||
state["playstate"]["paused"] = paused
|
||||
if(doSeek): state["playstate"]["doSeek"] = doSeek
|
||||
if doSeek: state["playstate"]["doSeek"] = doSeek
|
||||
state["ping"] = {}
|
||||
if(latencyCalculation):
|
||||
if latencyCalculation:
|
||||
state["ping"]["latencyCalculation"] = latencyCalculation
|
||||
state["ping"]["clientLatencyCalculation"] = self._pingService.newTimestamp()
|
||||
state["ping"]["clientRtt"] = self._pingService.getRtt()
|
||||
if(stateChange):
|
||||
if stateChange:
|
||||
self.clientIgnoringOnTheFly += 1
|
||||
if(self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly):
|
||||
if self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"] = {}
|
||||
if(self.serverIgnoringOnTheFly):
|
||||
if self.serverIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly
|
||||
self.serverIgnoringOnTheFly = 0
|
||||
if(self.clientIgnoringOnTheFly):
|
||||
if self.clientIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly
|
||||
self.sendMessage({"State": state})
|
||||
|
||||
@ -236,7 +236,7 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
def requireLogged(f): # @NoSelf
|
||||
@wraps(f)
|
||||
def wrapper(self, *args, **kwds):
|
||||
if(not self._logged):
|
||||
if not self._logged:
|
||||
self.dropWithError(getMessage("not-known-server-error"))
|
||||
return f(self, *args, **kwds)
|
||||
return wrapper
|
||||
@ -258,7 +258,7 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
username = username.strip()
|
||||
serverPassword = hello["password"] if hello.has_key("password") 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 = roomName.strip()
|
||||
roomPassword = room["password"] if room.has_key("password") else None
|
||||
@ -266,23 +266,23 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
return username, serverPassword, roomName, roomPassword, version
|
||||
|
||||
def _checkPassword(self, serverPassword):
|
||||
if(self._factory.password):
|
||||
if(not serverPassword):
|
||||
if self._factory.password:
|
||||
if not serverPassword:
|
||||
self.dropWithError(getMessage("password-required-server-error"))
|
||||
return False
|
||||
if(serverPassword != self._factory.password):
|
||||
if serverPassword != self._factory.password:
|
||||
self.dropWithError(getMessage("wrong-password-server-error"))
|
||||
return False
|
||||
return True
|
||||
|
||||
def handleHello(self, 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"))
|
||||
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"))
|
||||
else:
|
||||
if(not self._checkPassword(serverPassword)):
|
||||
if not self._checkPassword(serverPassword):
|
||||
return
|
||||
self._factory.addWatcher(self, username, roomName, roomPassword)
|
||||
self._logged = True
|
||||
@ -297,7 +297,7 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
hello["username"] = username
|
||||
userIp = self.transport.getPeer().host
|
||||
room = self._watcher.getRoom()
|
||||
if(room): hello["room"] = {"name": room.getName()}
|
||||
if room: hello["room"] = {"name": room.getName()}
|
||||
hello["version"] = syncplay.version
|
||||
hello["motd"] = self._factory.getMotd(userIp, username, room, clientVersion)
|
||||
self.sendMessage({"Hello": hello})
|
||||
@ -320,9 +320,9 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
user = {}
|
||||
user[username] = {}
|
||||
user[username]["room"] = room
|
||||
if(file_):
|
||||
if file_:
|
||||
user[username]["file"] = file_
|
||||
if(event):
|
||||
if event:
|
||||
user[username]["event"] = event
|
||||
self.sendSet({"user": user})
|
||||
|
||||
@ -346,7 +346,7 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
self.sendList()
|
||||
|
||||
def sendState(self, position, paused, doSeek, setBy, forced=False):
|
||||
if(self._clientLatencyCalculationArrivalTime):
|
||||
if self._clientLatencyCalculationArrivalTime:
|
||||
processingTime = time.time() - self._clientLatencyCalculationArrivalTime
|
||||
else:
|
||||
processingTime = 0
|
||||
@ -360,23 +360,23 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
"latencyCalculation": self._pingService.newTimestamp(),
|
||||
"serverRtt": self._pingService.getRtt()
|
||||
}
|
||||
if(self._clientLatencyCalculation):
|
||||
if self._clientLatencyCalculation:
|
||||
ping["clientLatencyCalculation"] = self._clientLatencyCalculation + processingTime
|
||||
self._clientLatencyCalculation = 0
|
||||
state = {
|
||||
"ping": ping,
|
||||
"playstate": playstate,
|
||||
}
|
||||
if(forced):
|
||||
if forced:
|
||||
self.serverIgnoringOnTheFly += 1
|
||||
if(self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly):
|
||||
if self.serverIgnoringOnTheFly or self.clientIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"] = {}
|
||||
if(self.serverIgnoringOnTheFly):
|
||||
if self.serverIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"]["server"] = self.serverIgnoringOnTheFly
|
||||
if(self.clientIgnoringOnTheFly):
|
||||
if self.clientIgnoringOnTheFly:
|
||||
state["ignoringOnTheFly"]["client"] = self.clientIgnoringOnTheFly
|
||||
self.clientIgnoringOnTheFly = 0
|
||||
if(self.serverIgnoringOnTheFly == 0 or forced):
|
||||
if self.serverIgnoringOnTheFly == 0 or forced:
|
||||
self.sendMessage({"State": state})
|
||||
|
||||
|
||||
@ -389,22 +389,22 @@ class SyncServerProtocol(JSONCommandProtocol):
|
||||
@requireLogged
|
||||
def handleState(self, state):
|
||||
position, paused, doSeek, latencyCalculation = None, None, None, None
|
||||
if(state.has_key("ignoringOnTheFly")):
|
||||
if state.has_key("ignoringOnTheFly"):
|
||||
ignore = state["ignoringOnTheFly"]
|
||||
if(ignore.has_key("server")):
|
||||
if(self.serverIgnoringOnTheFly == ignore["server"]):
|
||||
if ignore.has_key("server"):
|
||||
if self.serverIgnoringOnTheFly == ignore["server"]:
|
||||
self.serverIgnoringOnTheFly = 0
|
||||
if(ignore.has_key("client")):
|
||||
if ignore.has_key("client"):
|
||||
self.clientIgnoringOnTheFly = ignore["client"]
|
||||
if(state.has_key("playstate")):
|
||||
if state.has_key("playstate"):
|
||||
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
|
||||
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._clientLatencyCalculationArrivalTime = time.time()
|
||||
self._pingService.receiveMessage(latencyCalculation, clientRtt)
|
||||
if(self.serverIgnoringOnTheFly == 0):
|
||||
if self.serverIgnoringOnTheFly == 0:
|
||||
self._watcher.updateState(position, paused, doSeek, self._pingService.getLastForwardDelay())
|
||||
|
||||
def handleError(self, error):
|
||||
@ -424,15 +424,15 @@ class PingService(object):
|
||||
return time.time()
|
||||
|
||||
def receiveMessage(self, timestamp, senderRtt):
|
||||
if(not timestamp):
|
||||
if not timestamp:
|
||||
return
|
||||
self._rtt = time.time() - timestamp
|
||||
if(self._rtt < 0 or senderRtt < 0):
|
||||
if self._rtt < 0 or senderRtt < 0:
|
||||
return
|
||||
if(not self._avrRtt):
|
||||
if not self._avrRtt:
|
||||
self._avrRtt = self._rtt
|
||||
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)
|
||||
else:
|
||||
self._fd = self._avrRtt / 2
|
||||
|
@ -16,11 +16,11 @@ from pprint import pprint
|
||||
class SyncFactory(Factory):
|
||||
def __init__(self, password='', motdFilePath=None, isolateRooms=False):
|
||||
print getMessage("welcome-server-notification").format(syncplay.version)
|
||||
if(password):
|
||||
if password:
|
||||
password = hashlib.md5(password).hexdigest()
|
||||
self.password = password
|
||||
self._motdFilePath = motdFilePath
|
||||
if(not isolateRooms):
|
||||
if not isolateRooms:
|
||||
self._roomManager = RoomManager()
|
||||
else:
|
||||
self._roomManager = PublicRoomManager()
|
||||
@ -40,7 +40,7 @@ class SyncFactory(Factory):
|
||||
if constants.WARN_OLD_CLIENTS:
|
||||
if int(clientVersion.replace(".", "")) < int(constants.RECENT_CLIENT_THRESHOLD.replace(".", "")):
|
||||
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()
|
||||
args = dict(version=syncplay.version, userIp=userIp, username=username, room=room)
|
||||
try:
|
||||
@ -129,7 +129,7 @@ class RoomManager(object):
|
||||
|
||||
def removeWatcher(self, watcher):
|
||||
oldRoom = watcher.getRoom()
|
||||
if(oldRoom):
|
||||
if oldRoom:
|
||||
oldRoom.removeWatcher(watcher)
|
||||
self._deleteRoomIfEmpty(oldRoom)
|
||||
|
||||
@ -219,7 +219,7 @@ class Room(object):
|
||||
watcher.setRoom(self)
|
||||
|
||||
def removeWatcher(self, watcher):
|
||||
if(watcher.getName() not in self._watchers):
|
||||
if watcher.getName() not in self._watchers:
|
||||
return
|
||||
del self._watchers[watcher.getName()]
|
||||
watcher.setRoom(None)
|
||||
@ -300,7 +300,7 @@ class Watcher(object):
|
||||
self._sendStateTimer.start(constants.SERVER_STATE_INTERVAL)
|
||||
|
||||
def _deactivateStateTimer(self):
|
||||
if(self._sendStateTimer and self._sendStateTimer.running):
|
||||
if self._sendStateTimer and self._sendStateTimer.running:
|
||||
self._sendStateTimer.stop()
|
||||
|
||||
def sendState(self, position, paused, doSeek, setBy, forcedUpdate):
|
||||
@ -321,7 +321,7 @@ class Watcher(object):
|
||||
if pauseChanged:
|
||||
self.getRoom().setPaused(Room.STATE_PAUSED if paused else Room.STATE_PLAYING, self)
|
||||
if position is not None:
|
||||
if(not paused):
|
||||
if not paused:
|
||||
position += messageAge
|
||||
self.setPosition(position)
|
||||
if doSeek or pauseChanged:
|
||||
@ -332,7 +332,7 @@ class ConfigurationGetter(object):
|
||||
def getConfiguration(self):
|
||||
self._prepareArgParser()
|
||||
self._args = self._argparser.parse_args()
|
||||
if(self._args.port == None):
|
||||
if self._args.port == None:
|
||||
self._args.port = constants.DEFAULT_PORT
|
||||
return self._args
|
||||
|
||||
|
@ -76,64 +76,64 @@ class ConfigurationGetter(object):
|
||||
def _validateArguments(self):
|
||||
def _isPortValid(varToTest):
|
||||
try:
|
||||
if (varToTest == "" or varToTest is None):
|
||||
if varToTest == "" or varToTest is None:
|
||||
return False
|
||||
if (str(varToTest).isdigit() == False):
|
||||
if str(varToTest).isdigit() == False:
|
||||
return False
|
||||
varToTest = int(varToTest)
|
||||
if (varToTest > 65535 or varToTest < 1):
|
||||
if varToTest > 65535 or varToTest < 1:
|
||||
return False
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
for key in self._boolean:
|
||||
if(self._config[key] == "True"):
|
||||
if self._config[key] == "True":
|
||||
self._config[key] = True
|
||||
elif(self._config[key] == "False"):
|
||||
elif self._config[key] == "False":
|
||||
self._config[key] = False
|
||||
for key in self._required:
|
||||
if(key == "playerPath"):
|
||||
if key == "playerPath":
|
||||
player = None
|
||||
if self._config["playerPath"]:
|
||||
player = self._playerFactory.getPlayerByPath(self._config["playerPath"])
|
||||
if(player):
|
||||
if player:
|
||||
self._config["playerClass"] = player
|
||||
else:
|
||||
raise InvalidConfigValue("Player path is not set properly")
|
||||
if player.__name__ in ['MpvPlayer', 'MplayerPlayer']:
|
||||
if not self._config['file']:
|
||||
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"])
|
||||
hostNotValid = (self._config["host"] == "" or self._config["host"] is None)
|
||||
portNotValid = (_isPortValid(self._config["port"]) == False)
|
||||
if(hostNotValid):
|
||||
if hostNotValid:
|
||||
raise InvalidConfigValue("Hostname can't be empty")
|
||||
elif(portNotValid):
|
||||
elif portNotValid:
|
||||
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()))
|
||||
|
||||
def _overrideConfigWithArgs(self, args):
|
||||
for key, val in vars(args).items():
|
||||
if(val):
|
||||
if(key == "force_gui_prompt"):
|
||||
if val:
|
||||
if key == "force_gui_prompt":
|
||||
key = "forceGuiPrompt"
|
||||
if(key == "no_store"):
|
||||
if key == "no_store":
|
||||
key = "noStore"
|
||||
if(key == "player_path"):
|
||||
if key == "player_path":
|
||||
key = "playerPath"
|
||||
if(key == "_args"):
|
||||
if key == "_args":
|
||||
key = "playerArgs"
|
||||
if(key == "no_gui"):
|
||||
if key == "no_gui":
|
||||
key = "noGui"
|
||||
if(key == "clear_gui_data"):
|
||||
if key == "clear_gui_data":
|
||||
key = "clearGUIData"
|
||||
self._config[key] = val
|
||||
|
||||
def _splitPortAndHost(self, host):
|
||||
port = constants.DEFAULT_PORT if not self._config["port"] else self._config["port"]
|
||||
if(host):
|
||||
if host:
|
||||
if ':' in host:
|
||||
host, port = host.split(':', 1)
|
||||
try:
|
||||
@ -148,21 +148,21 @@ class ConfigurationGetter(object):
|
||||
def _checkForPortableFile(self):
|
||||
path = utils.findWorkingDir()
|
||||
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)
|
||||
|
||||
def _getConfigurationFilePath(self):
|
||||
configFile = self._checkForPortableFile()
|
||||
if not configFile:
|
||||
for name in constants.CONFIG_NAMES:
|
||||
if(configFile and os.path.isfile(configFile)):
|
||||
if configFile and os.path.isfile(configFile):
|
||||
break
|
||||
if(os.name <> 'nt'):
|
||||
if os.name <> 'nt':
|
||||
configFile = os.path.join(os.getenv('HOME', '.'), name)
|
||||
else:
|
||||
configFile = os.path.join(os.getenv('APPDATA', '.'), name)
|
||||
if(configFile and not os.path.isfile(configFile)):
|
||||
if(os.name <> 'nt'):
|
||||
if configFile and not os.path.isfile(configFile):
|
||||
if os.name <> 'nt':
|
||||
configFile = os.path.join(os.getenv('HOME', '.'), constants.DEFAULT_CONFIG_NAME_LINUX)
|
||||
else:
|
||||
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):
|
||||
parser = SafeConfigParserUnicode()
|
||||
if(not os.path.isfile(iniPath)):
|
||||
if(createConfig):
|
||||
if not os.path.isfile(iniPath):
|
||||
if createConfig:
|
||||
open(iniPath, 'w').close()
|
||||
else:
|
||||
return
|
||||
parser.readfp(codecs.open(iniPath, "r", "utf_8_sig"))
|
||||
for section, options in self._iniStructure.items():
|
||||
if(parser.has_section(section)):
|
||||
if parser.has_section(section):
|
||||
for option in options:
|
||||
if(parser.has_option(section, option)):
|
||||
if parser.has_option(section, option):
|
||||
self._config[option] = parser.get(section, option)
|
||||
|
||||
def _checkConfig(self):
|
||||
@ -195,39 +195,39 @@ class ConfigurationGetter(object):
|
||||
sys.exit()
|
||||
|
||||
def _promptForMissingArguments(self, error=None):
|
||||
if(self._config['noGui'] or not GuiConfiguration):
|
||||
if self._config['noGui'] or not GuiConfiguration:
|
||||
if error:
|
||||
print "{}!".format(error)
|
||||
print getMessage("missing-arguments-error")
|
||||
sys.exit()
|
||||
elif(GuiConfiguration):
|
||||
elif GuiConfiguration:
|
||||
gc = GuiConfiguration(self._config, error=error)
|
||||
gc.setAvailablePaths(self._playerFactory.getAvailablePlayerPaths())
|
||||
gc.run()
|
||||
return gc.getProcessedConfiguration()
|
||||
|
||||
def __wasOptionChanged(self, parser, section, option):
|
||||
if (parser.has_option(section, option)):
|
||||
if (parser.get(section, option) != unicode(self._config[option])):
|
||||
if parser.has_option(section, option):
|
||||
if parser.get(section, option) != unicode(self._config[option]):
|
||||
return True
|
||||
else:
|
||||
return True
|
||||
|
||||
def _saveConfig(self, iniPath):
|
||||
changed = False
|
||||
if(self._config['noStore']):
|
||||
if self._config['noStore']:
|
||||
return
|
||||
parser = SafeConfigParserUnicode()
|
||||
parser.readfp(codecs.open(iniPath, "r", "utf_8_sig"))
|
||||
for section, options in self._iniStructure.items():
|
||||
if(not parser.has_section(section)):
|
||||
if not parser.has_section(section):
|
||||
parser.add_section(section)
|
||||
changed = True
|
||||
for option in options:
|
||||
if(self.__wasOptionChanged(parser, section, option)):
|
||||
if self.__wasOptionChanged(parser, section, option):
|
||||
changed = True
|
||||
parser.set(section, option, unicode(self._config[option]).replace('%', '%%'))
|
||||
if(changed):
|
||||
if changed:
|
||||
parser.write(codecs.open(iniPath, "wb", "utf_8_sig"))
|
||||
|
||||
|
||||
@ -239,7 +239,7 @@ class ConfigurationGetter(object):
|
||||
pass
|
||||
|
||||
try:
|
||||
if(self._config['noGui'] == False):
|
||||
if self._config['noGui'] == False:
|
||||
for key, value in self._promptForMissingArguments().items():
|
||||
self._config[key] = value
|
||||
except GuiConfiguration.WindowClosed:
|
||||
@ -267,7 +267,7 @@ class ConfigurationGetter(object):
|
||||
for location in locations:
|
||||
for name in constants.CONFIG_NAMES:
|
||||
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) + "'")
|
||||
self._parseConfigFile(path, createConfig=False)
|
||||
self._checkConfig()
|
||||
@ -298,23 +298,23 @@ class ConfigurationGetter(object):
|
||||
self._argparser.add_argument('_args', metavar='options', type=str, nargs='*', help=getMessage("args-argument"))
|
||||
args = self._argparser.parse_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['file'] = None
|
||||
# Arguments not validated yet - booleans are still text values
|
||||
if 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._checkConfig()
|
||||
self._saveConfig(iniPath)
|
||||
if(self._config['file']):
|
||||
if self._config['file']:
|
||||
self._config['loadedRelativePaths'] = self._loadRelativeConfiguration()
|
||||
if self._config['language']:
|
||||
setLanguage(self._config['language'])
|
||||
if not GuiConfiguration:
|
||||
self._config['noGui'] = True
|
||||
if(not self._config['noGui']):
|
||||
if not self._config['noGui']:
|
||||
from syncplay.vendor import qt4reactor
|
||||
if QCoreApplication.instance() is None:
|
||||
self.app = QtGui.QApplication(sys.argv)
|
||||
@ -336,5 +336,5 @@ class SafeConfigParserUnicode(SafeConfigParser):
|
||||
continue
|
||||
if (value is not None) or (self._optcre == self.OPTCRE):
|
||||
key = " = ".join((key, unicode(value).replace('\n', '\n\t')))
|
||||
fp.write("%s\n" % (key))
|
||||
fp.write("%s\n" % key)
|
||||
fp.write("\n")
|
||||
|
@ -56,7 +56,7 @@ class ConfigDialog(QtGui.QDialog):
|
||||
self.setFixedSize(self.sizeHint())
|
||||
|
||||
def runButtonTextUpdate(self):
|
||||
if (self.donotstoreCheckbox.isChecked()):
|
||||
if self.donotstoreCheckbox.isChecked():
|
||||
self.runButton.setText(getMessage("run-label"))
|
||||
else:
|
||||
self.runButton.setText(getMessage("storeandrun-label"))
|
||||
@ -68,7 +68,7 @@ class ConfigDialog(QtGui.QDialog):
|
||||
settings = QSettings("Syncplay", "PlayerList")
|
||||
settings.beginGroup("PlayerList")
|
||||
savedPlayers = settings.value("PlayerList", [])
|
||||
if(not isinstance(savedPlayers, list)):
|
||||
if not isinstance(savedPlayers, list):
|
||||
savedPlayers = []
|
||||
playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers)))
|
||||
settings.endGroup()
|
||||
@ -85,7 +85,7 @@ class ConfigDialog(QtGui.QDialog):
|
||||
self.executablepathCombobox.addItem(foundpath)
|
||||
|
||||
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)
|
||||
if foundpath == "":
|
||||
foundpath = path
|
||||
@ -95,7 +95,7 @@ class ConfigDialog(QtGui.QDialog):
|
||||
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.endGroup()
|
||||
return(foundpath)
|
||||
return foundpath
|
||||
|
||||
def updateExecutableIcon(self):
|
||||
currentplayerpath = unicode(self.executablepathCombobox.currentText())
|
||||
@ -148,9 +148,9 @@ class ConfigDialog(QtGui.QDialog):
|
||||
morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
|
||||
settings.endGroup()
|
||||
if morestate == "true":
|
||||
return(True)
|
||||
return True
|
||||
else:
|
||||
return(False)
|
||||
return False
|
||||
|
||||
def saveMoreState(self, morestate):
|
||||
settings = QSettings("Syncplay", "MoreSettings")
|
||||
@ -161,11 +161,11 @@ class ConfigDialog(QtGui.QDialog):
|
||||
def browseMediapath(self):
|
||||
self.loadMediaBrowseSettings()
|
||||
options = QtGui.QFileDialog.Options()
|
||||
if (os.path.isdir(self.mediadirectory)):
|
||||
if os.path.isdir(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)
|
||||
elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))):
|
||||
elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)):
|
||||
defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
|
||||
else:
|
||||
defaultdirectory = ""
|
||||
@ -240,13 +240,13 @@ class ConfigDialog(QtGui.QDialog):
|
||||
def dragEnterEvent(self, event):
|
||||
data = event.mimeData()
|
||||
urls = data.urls()
|
||||
if (urls and urls[0].scheme() == 'file'):
|
||||
if urls and urls[0].scheme() == 'file':
|
||||
event.acceptProposedAction()
|
||||
|
||||
def dropEvent(self, event):
|
||||
data = event.mimeData()
|
||||
urls = data.urls()
|
||||
if (urls and urls[0].scheme() == 'file'):
|
||||
if urls and urls[0].scheme() == 'file':
|
||||
if sys.platform.startswith('linux'):
|
||||
dropfilepath = unicode(urls[0].path())
|
||||
else:
|
||||
@ -285,9 +285,9 @@ class ConfigDialog(QtGui.QDialog):
|
||||
self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
|
||||
self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))
|
||||
|
||||
if(config['host'] == None):
|
||||
if config['host'] == None:
|
||||
host = ""
|
||||
elif(":" in config['host']):
|
||||
elif ":" in config['host']:
|
||||
host = config['host']
|
||||
else:
|
||||
host = config['host'] + ":" + str(config['port'])
|
||||
|
@ -5,7 +5,7 @@ except ImportError:
|
||||
from syncplay.ui.consoleUI import ConsoleUI
|
||||
|
||||
def getUi(graphical=True):
|
||||
if(graphical): #TODO: Add graphical ui
|
||||
if graphical: #TODO: Add graphical ui
|
||||
ui = GraphicalUI()
|
||||
else:
|
||||
ui = ConsoleUI()
|
||||
|
@ -28,10 +28,10 @@ class ConsoleUI(threading.Thread):
|
||||
while True:
|
||||
data = raw_input().decode(sys.stdin.encoding)
|
||||
data = data.rstrip('\n\r')
|
||||
if(not self.promptMode.isSet()):
|
||||
if not self.promptMode.isSet():
|
||||
self.PromptResult = data
|
||||
self.promptMode.set()
|
||||
elif(self._syncplayClient):
|
||||
elif self._syncplayClient:
|
||||
self._executeCommand(data)
|
||||
except EOFError:
|
||||
pass
|
||||
@ -50,12 +50,12 @@ class ConsoleUI(threading.Thread):
|
||||
self.showMessage(message, True)
|
||||
for user in rooms[room]:
|
||||
username = "*<{}>*".format(user.username) if user == currentUser else "<{}>".format(user.username)
|
||||
if(user.file):
|
||||
if user.file:
|
||||
message = u"{} is playing:".format(username)
|
||||
self.showMessage(message, True)
|
||||
message = u" File: '{}' ({})".format(user.file['name'], formatTime(user.file['duration']))
|
||||
if(currentUser.file):
|
||||
if(user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']):
|
||||
if currentUser.file:
|
||||
if user.file['name'] == currentUser.file['name'] and user.file['size'] != currentUser.file['size']:
|
||||
message += " (their file size is different from yours!)"
|
||||
self.showMessage(message, True)
|
||||
else:
|
||||
@ -67,7 +67,7 @@ class ConsoleUI(threading.Thread):
|
||||
|
||||
def showMessage(self, message, noTimestamp=False):
|
||||
message = message.encode(sys.stdout.encoding, 'replace')
|
||||
if(noTimestamp):
|
||||
if noTimestamp:
|
||||
print(message)
|
||||
else:
|
||||
print(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message)
|
||||
@ -79,8 +79,8 @@ class ConsoleUI(threading.Thread):
|
||||
print("ERROR:\t" + message)
|
||||
|
||||
def _extractSign(self, m):
|
||||
if(m):
|
||||
if(m == "-"):
|
||||
if m:
|
||||
if m == "-":
|
||||
return -1
|
||||
else:
|
||||
return 1
|
||||
@ -90,23 +90,23 @@ class ConsoleUI(threading.Thread):
|
||||
def _tryAdvancedCommands(self, data):
|
||||
o = re.match(constants.UI_OFFSET_REGEX, data)
|
||||
s = re.match(constants.UI_SEEK_REGEX, data)
|
||||
if(o):
|
||||
if o:
|
||||
sign = self._extractSign(o.group('sign'))
|
||||
t = utils.parseTime(o.group('time'))
|
||||
if(t is None):
|
||||
if t is None:
|
||||
return
|
||||
if (o.group('sign') == "/"):
|
||||
if o.group('sign') == "/":
|
||||
t = self._syncplayClient.getPlayerPosition() - t
|
||||
elif(sign):
|
||||
elif sign:
|
||||
t = self._syncplayClient.getUserOffset() + sign * t
|
||||
self._syncplayClient.setUserOffset(t)
|
||||
return True
|
||||
elif s:
|
||||
sign = self._extractSign(s.group('sign'))
|
||||
t = utils.parseTime(s.group('time'))
|
||||
if(t is None):
|
||||
if t is None:
|
||||
return
|
||||
if(sign):
|
||||
if sign:
|
||||
t = self._syncplayClient.getGlobalPosition() + sign * t
|
||||
self._syncplayClient.setPosition(t)
|
||||
return True
|
||||
@ -114,17 +114,17 @@ class ConsoleUI(threading.Thread):
|
||||
|
||||
def _executeCommand(self, data):
|
||||
command = re.match(constants.UI_COMMAND_REGEX, data)
|
||||
if(not command):
|
||||
if not command:
|
||||
return
|
||||
if(command.group('command') in constants.COMMANDS_UNDO):
|
||||
if command.group('command') in constants.COMMANDS_UNDO:
|
||||
tmp_pos = self._syncplayClient.getPlayerPosition()
|
||||
self._syncplayClient.setPosition(self._syncplayClient.playerPositionBeforeLastSeek)
|
||||
self._syncplayClient.playerPositionBeforeLastSeek = tmp_pos
|
||||
elif (command.group('command') in constants.COMMANDS_LIST):
|
||||
elif command.group('command') in constants.COMMANDS_LIST:
|
||||
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())
|
||||
elif (command.group('command') in constants.COMMANDS_ROOM):
|
||||
elif command.group('command') in constants.COMMANDS_ROOM:
|
||||
room = command.group('parameter')
|
||||
if room == None:
|
||||
if self._syncplayClient.userlist.currentUser.file:
|
||||
@ -135,9 +135,9 @@ class ConsoleUI(threading.Thread):
|
||||
self._syncplayClient.setRoom(room)
|
||||
self._syncplayClient.sendRoom()
|
||||
else:
|
||||
if(self._tryAdvancedCommands(data)):
|
||||
if self._tryAdvancedCommands(data):
|
||||
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("commandlist-notification"), True)
|
||||
self.showMessage(getMessage("commandlist-notification/room"), True)
|
||||
|
@ -23,7 +23,7 @@ class MainWindow(QtGui.QMainWindow):
|
||||
message = message.replace("<", "<span style=\"color:#367AA9;font-weight:bold;\"><")
|
||||
message = message.replace(">", "></span>")
|
||||
message = message.replace("\n", "<br />")
|
||||
if(noTimestamp):
|
||||
if noTimestamp:
|
||||
self.newMessage(message + "<br />")
|
||||
else:
|
||||
self.newMessage(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message + "<br />")
|
||||
@ -36,7 +36,7 @@ class MainWindow(QtGui.QMainWindow):
|
||||
|
||||
for room in rooms:
|
||||
roomitem = QtGui.QStandardItem(room)
|
||||
if (room == currentUser.room):
|
||||
if room == currentUser.room:
|
||||
font = QtGui.QFont()
|
||||
font.setWeight(QtGui.QFont.Bold)
|
||||
roomitem.setFont(font)
|
||||
@ -47,9 +47,9 @@ class MainWindow(QtGui.QMainWindow):
|
||||
for user in rooms[room]:
|
||||
useritem = QtGui.QStandardItem(user.username)
|
||||
fileitem = QtGui.QStandardItem("")
|
||||
if (user.file):
|
||||
if user.file:
|
||||
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'])
|
||||
sameSize = sameFilesize(user.file['size'], currentUser.file['size'])
|
||||
sameDuration = sameFileduration(user.file['duration'], currentUser.file['duration'])
|
||||
@ -57,20 +57,20 @@ class MainWindow(QtGui.QMainWindow):
|
||||
differentName = not sameName
|
||||
differentSize = not sameSize
|
||||
differentDuration = not sameDuration
|
||||
if (sameName or sameRoom):
|
||||
if (differentSize and sameDuration):
|
||||
if sameName or sameRoom:
|
||||
if differentSize and sameDuration:
|
||||
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")))
|
||||
elif (differentDuration):
|
||||
elif differentDuration:
|
||||
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')))
|
||||
else:
|
||||
fileitem = QtGui.QStandardItem(getMessage("nofile-note"))
|
||||
if (room == currentUser.room):
|
||||
if room == currentUser.room:
|
||||
fileitem.setForeground(QtGui.QBrush(QtGui.QColor('blue')))
|
||||
if(currentUser.username == user.username):
|
||||
if currentUser.username == user.username:
|
||||
font = QtGui.QFont()
|
||||
font.setWeight(QtGui.QFont.Bold)
|
||||
useritem.setFont(font)
|
||||
@ -86,7 +86,7 @@ class MainWindow(QtGui.QMainWindow):
|
||||
self.listTreeView.resizeColumnToContents(1)
|
||||
|
||||
def roomClicked(self, item):
|
||||
while(item.parent().row() != -1):
|
||||
while item.parent().row() != -1:
|
||||
item = item.parent()
|
||||
self.joinRoom(item.sibling(item.row(), 0).data())
|
||||
|
||||
@ -114,18 +114,18 @@ class MainWindow(QtGui.QMainWindow):
|
||||
else:
|
||||
room = self._syncplayClient.defaultRoom
|
||||
self.roomInput.setText(room)
|
||||
if(room != self._syncplayClient.getRoom()):
|
||||
if room != self._syncplayClient.getRoom():
|
||||
self._syncplayClient.setRoom(room)
|
||||
self._syncplayClient.sendRoom()
|
||||
|
||||
def seekPosition(self):
|
||||
s = re.match(constants.UI_SEEK_REGEX, self.seekInput.text())
|
||||
if(s):
|
||||
if s:
|
||||
sign = self._extractSign(s.group('sign'))
|
||||
t = utils.parseTime(s.group('time'))
|
||||
if(t is None):
|
||||
if t is None:
|
||||
return
|
||||
if(sign):
|
||||
if sign:
|
||||
t = self._syncplayClient.getGlobalPosition() + sign * t
|
||||
self._syncplayClient.setPosition(t)
|
||||
|
||||
@ -168,11 +168,11 @@ class MainWindow(QtGui.QMainWindow):
|
||||
def browseMediapath(self):
|
||||
self.loadMediaBrowseSettings()
|
||||
options = QtGui.QFileDialog.Options()
|
||||
if (os.path.isdir(self.mediadirectory)):
|
||||
if os.path.isdir(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)
|
||||
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)
|
||||
else:
|
||||
defaultdirectory = ""
|
||||
@ -187,8 +187,8 @@ class MainWindow(QtGui.QMainWindow):
|
||||
self._syncplayClient._player.openFile(fileName)
|
||||
|
||||
def _extractSign(self, m):
|
||||
if(m):
|
||||
if(m == "-"):
|
||||
if m:
|
||||
if m == "-":
|
||||
return -1
|
||||
else:
|
||||
return 1
|
||||
@ -201,14 +201,14 @@ class MainWindow(QtGui.QMainWindow):
|
||||
"")
|
||||
if ok and newoffset != '':
|
||||
o = re.match(constants.UI_OFFSET_REGEX, "o " + newoffset)
|
||||
if(o):
|
||||
if o:
|
||||
sign = self._extractSign(o.group('sign'))
|
||||
t = utils.parseTime(o.group('time'))
|
||||
if(t is None):
|
||||
if t is None:
|
||||
return
|
||||
if (o.group('sign') == "/"):
|
||||
if o.group('sign') == "/":
|
||||
t = self._syncplayClient.getPlayerPosition() - t
|
||||
elif(sign):
|
||||
elif sign:
|
||||
t = self._syncplayClient.getUserOffset() + sign * t
|
||||
self._syncplayClient.setUserOffset(t)
|
||||
else:
|
||||
@ -400,7 +400,7 @@ class MainWindow(QtGui.QMainWindow):
|
||||
def dragEnterEvent(self, event):
|
||||
data = event.mimeData()
|
||||
urls = data.urls()
|
||||
if (urls and urls[0].scheme() == 'file'):
|
||||
if urls and urls[0].scheme() == 'file':
|
||||
event.acceptProposedAction()
|
||||
|
||||
def dropEvent(self, event):
|
||||
@ -410,7 +410,7 @@ class MainWindow(QtGui.QMainWindow):
|
||||
rewindFile = True
|
||||
data = event.mimeData()
|
||||
urls = data.urls()
|
||||
if (urls and urls[0].scheme() == 'file'):
|
||||
if urls and urls[0].scheme() == 'file':
|
||||
if sys.platform.startswith('linux'):
|
||||
dropfilepath = unicode(urls[0].path())
|
||||
else:
|
||||
|
@ -58,14 +58,14 @@ def parseTime(timeStr):
|
||||
time_params = {}
|
||||
for (name, param) in parts.iteritems():
|
||||
if param:
|
||||
if(name == "miliseconds"):
|
||||
if name == "miliseconds":
|
||||
time_params["microseconds"] = int(param) * 1000
|
||||
else:
|
||||
time_params[name] = int(param)
|
||||
return datetime.timedelta(**time_params).total_seconds()
|
||||
|
||||
def formatTime(timeInSeconds, weeksAsTitles=True):
|
||||
if(timeInSeconds < 0):
|
||||
if timeInSeconds < 0:
|
||||
timeInSeconds = -timeInSeconds
|
||||
sign = '-'
|
||||
else:
|
||||
@ -81,11 +81,11 @@ def formatTime(timeInSeconds, weeksAsTitles=True):
|
||||
hours = (timeInSeconds % 86400) // 3600
|
||||
minutes = (timeInSeconds % 3600) // 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)
|
||||
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)
|
||||
elif(hours > 0):
|
||||
elif hours > 0:
|
||||
formattedTime = '{0:}{1:02.0f}:{2:02.0f}:{3:02.0f}'.format(sign, hours, minutes, seconds)
|
||||
else:
|
||||
formattedTime = '{0:}{1:02.0f}:{2:02.0f}'.format(sign, minutes, seconds)
|
||||
@ -114,7 +114,7 @@ def blackholeStdoutForFrozenWindow():
|
||||
_error = None
|
||||
def write(self, text, fname='.syncplay.log'):
|
||||
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)
|
||||
else:
|
||||
path = os.path.join(os.getenv('APPDATA', '.'), fname)
|
||||
|
@ -5,7 +5,7 @@ import site, sys
|
||||
# libpath
|
||||
|
||||
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!")
|
||||
except AttributeError:
|
||||
import warnings
|
||||
@ -14,7 +14,7 @@ except AttributeError:
|
||||
from syncplay.clientManager import SyncplayClientManager
|
||||
from syncplay.utils import blackholeStdoutForFrozenWindow
|
||||
|
||||
if(__name__ == '__main__'):
|
||||
if __name__ == '__main__':
|
||||
blackholeStdoutForFrozenWindow()
|
||||
SyncplayClientManager().run()
|
||||
|
||||
|
@ -6,7 +6,7 @@ import site, sys
|
||||
# libpath
|
||||
|
||||
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!")
|
||||
except AttributeError:
|
||||
import warnings
|
||||
|
Loading…
Reference in New Issue
Block a user