Refactor OS check to utils

This commit is contained in:
Etoh 2017-12-10 14:32:35 +00:00
parent 117a45b7cb
commit 8a082ed1cd
7 changed files with 64 additions and 41 deletions

View File

@ -224,4 +224,10 @@ SYNCPLAY_PUBLIC_SERVER_LIST_URL = u"http://syncplay.pl/listpublicservers?{}" # P
DEFAULT_TRUSTED_DOMAINS = [u"youtube.com",u"youtu.be"]
TRUSTABLE_WEB_PROTOCOLS = [u"http://www.",u"https://www.",u"http://",u"https://"]
PRIVATE_FILE_FIELDS = ["path"]
PRIVATE_FILE_FIELDS = ["path"]
OS_WINDOWS = "win"
OS_LINUX = "linux"
OS_OSX = "darwin"
OS_BSD = "freebsd"
OS_DRAGONFLY = "dragonfly"

View File

@ -6,6 +6,7 @@ from syncplay.players.basePlayer import BasePlayer
from syncplay import constants, utils
from syncplay.messages import getMessage
import os, sys
from syncplay.utils import isWindows
class MplayerPlayer(BasePlayer):
speedSupported = True
@ -282,7 +283,7 @@ class MplayerPlayer(BasePlayer):
call = [playerPath]
if filePath:
if sys.platform.startswith('win') and not utils.isASCII(filePath):
if isWindows() and not utils.isASCII(filePath):
self.__playerController.delayedFilePath = filePath
filePath = None
else:

View File

@ -11,6 +11,7 @@ import asynchat, asyncore
import urllib
import time
from syncplay.messages import getMessage
from syncplay.utils import isBSD, isLinux, isWindows, isOSX
class VlcPlayer(BasePlayer):
speedSupported = True
@ -20,7 +21,7 @@ class VlcPlayer(BasePlayer):
RE_ANSWER = re.compile(constants.VLC_ANSWER_REGEX)
SLAVE_ARGS = constants.VLC_SLAVE_ARGS
if sys.platform.startswith('darwin'):
if isOSX():
SLAVE_ARGS.extend(constants.VLC_SLAVE_OSX_ARGS)
else:
SLAVE_ARGS.extend(constants.VLC_SLAVE_NONOSX_ARGS)
@ -146,7 +147,7 @@ class VlcPlayer(BasePlayer):
fileURL = fileURL.replace(u'\\', u'/')
fileURL = fileURL.encode('utf8')
fileURL = urllib.quote_plus(fileURL)
if sys.platform.startswith('win'):
if isWindows():
fileURL = "file:///" + fileURL
else:
fileURL = "file://" + fileURL
@ -331,13 +332,13 @@ class VlcPlayer(BasePlayer):
return False
playerController._client.ui.showErrorMessage(getMessage("vlc-interface-not-installed"))
return False
if sys.platform.startswith('linux'):
if isLinux():
playerController.vlcIntfPath = "/usr/lib/vlc/lua/intf/"
playerController.vlcIntfUserPath = os.path.join(os.getenv('HOME', '.'), ".local/share/vlc/lua/intf/")
elif sys.platform.startswith('darwin'):
elif isOSX():
playerController.vlcIntfPath = "/Applications/VLC.app/Contents/MacOS/share/lua/intf/"
playerController.vlcIntfUserPath = os.path.join(os.getenv('HOME', '.'), "Library/Application Support/org.videolan.vlc/lua/intf/")
elif 'bsd' in sys.platform or sys.platform.startswith('dragonfly'):
elif isBSD():
# *BSD ports/pkgs install to /usr/local by default.
# This should also work for all the other BSDs, such as OpenBSD or DragonFly.
playerController.vlcIntfPath = "/usr/local/lib/vlc/lua/intf/"
@ -349,7 +350,7 @@ class VlcPlayer(BasePlayer):
if _usevlcintf(playerController.vlcIntfPath, playerController.vlcIntfUserPath):
playerController.SLAVE_ARGS.append('--lua-config=syncplay={{port=\"{}\"}}'.format(str(playerController.vlcport)))
else:
if sys.platform.startswith('linux'):
if isLinux():
playerController.vlcDataPath = "/usr/lib/syncplay/resources"
else:
playerController.vlcDataPath = utils.findWorkingDir() + "\\resources"
@ -387,7 +388,7 @@ class VlcPlayer(BasePlayer):
playerController._client.ui.showErrorMessage(
getMessage("media-player-error").format(line), True)
break
if not sys.platform.startswith('darwin'):
if not isOSX():
self.__process.stderr = None
else:
vlcoutputthread = threading.Thread(target = self.handle_vlcoutput, args=())
@ -401,7 +402,7 @@ class VlcPlayer(BasePlayer):
self._sendingData = threading.Lock()
def _shouldListenForSTDOUT(self):
if sys.platform.startswith('win'):
if isWindows():
return False # Due to VLC3 not using STDOUT/STDERR
else:
return True

View File

@ -6,6 +6,7 @@ import ast
from syncplay import constants, utils, version, milestone
from syncplay.messages import getMessage, setLanguage, isValidLanguage
from syncplay.players.playerFactory import PlayerFactory
from syncplay.utils import isOSX
import codecs
class InvalidConfigValue(Exception):
@ -411,7 +412,7 @@ class ConfigurationGetter(object):
if QCoreApplication.instance() is None:
self.app = QtWidgets.QApplication(sys.argv)
qt5reactor.install()
if sys.platform.startswith('darwin'):
if isOSX():
import appnope
appnope.nope()
except ImportError:

View File

@ -12,6 +12,7 @@ import sys
import threading
from syncplay.messages import getMessage, getLanguages, setLanguage, getInitialLanguage
from syncplay import constants
from syncplay.utils import isBSD, isLinux, isWindows, isOSX
class GuiConfiguration:
def __init__(self, config, error=None, defaultConfig=None):
@ -238,11 +239,11 @@ class ConfigDialog(QtWidgets.QDialog):
defaultdirectory = os.environ["ProgramFiles"]
elif "PROGRAMW6432" in os.environ:
defaultdirectory = os.environ["ProgramW6432"]
elif sys.platform.startswith('linux'):
elif isLinux():
defaultdirectory = "/usr/bin"
elif sys.platform.startswith('darwin'):
elif isOSX():
defaultdirectory = "/Applications/"
elif "bsd" in sys.platform or sys.platform.startswith('dragonfly'):
elif isBSD():
defaultdirectory = "/usr/local/bin"
fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(self,
@ -250,7 +251,7 @@ class ConfigDialog(QtWidgets.QDialog):
defaultdirectory,
browserfilter, "", options)
if fileName:
if sys.platform.startswith('darwin') and fileName.endswith('.app'): # see GitHub issue #91
if isOSX() and fileName.endswith('.app'): # see GitHub issue #91
# Mac OS X application bundles contain a Info.plist in the Contents subdirectory of the .app.
# This plist file includes the 'CFBundleExecutable' key, which specifies the name of the
# executable. I would have used plistlib here, but since the version of this library in
@ -1109,7 +1110,7 @@ class ConfigDialog(QtWidgets.QDialog):
self.QtWidgets = QtWidgets
self.QtGui = QtGui
self.error = error
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + "\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"

View File

@ -9,12 +9,13 @@ import sys
import time
import urllib
from datetime import datetime
from syncplay.utils import isLinux, isWindows, isOSX
import re
import os
from syncplay.utils import formatTime, sameFilename, sameFilesize, sameFileduration, RoomPasswordProvider, formatSize, isURL
from functools import wraps
from twisted.internet import task
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
from Foundation import NSURL
lastCheckedForUpdates = None
@ -34,7 +35,7 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
if column == constants.USERLIST_GUI_USERNAME_COLUMN:
currentQAbstractItemModel = indexQModelIndex.model()
itemQModelIndex = currentQAbstractItemModel.index(indexQModelIndex.row(), constants.USERLIST_GUI_USERNAME_COLUMN, indexQModelIndex.parent())
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
@ -65,7 +66,7 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
if isUserRow:
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+constants.USERLIST_GUI_USERNAME_OFFSET)
if column == constants.USERLIST_GUI_FILENAME_COLUMN:
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
@ -90,18 +91,18 @@ class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
QtWidgets.QStyledItemDelegate.paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex)
class AboutDialog(QtWidgets.QDialog):
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
if sys.platform.startswith('darwin'):
if isOSX():
self.setWindowTitle("")
else:
self.setWindowTitle(getMessage("about-dialog-title"))
if sys.platform.startswith('win'):
if isWindows():
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
nameLabel = QtWidgets.QLabel("<center><strong>Syncplay</strong></center>")
nameLabel.setFont(QtGui.QFont("Helvetica", 20))
@ -131,13 +132,13 @@ class AboutDialog(QtWidgets.QDialog):
self.setLayout(aboutLayout)
def openLicense(self):
if sys.platform.startswith('win'):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + self.resourcespath + u"license.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + self.resourcespath + u"license.rtf"))
def openDependencies(self):
if sys.platform.startswith('win'):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + self.resourcespath + u"third-party-notices.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + self.resourcespath + u"third-party-notices.rtf"))
@ -160,7 +161,7 @@ class MainWindow(QtWidgets.QMainWindow):
itemQPainter.save()
currentQAbstractItemModel = indexQModelIndex.model()
currentlyPlayingFile = currentQAbstractItemModel.data(indexQModelIndex, Qt.UserRole + constants.PLAYLISTITEM_CURRENTLYPLAYING_ROLE)
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
@ -219,7 +220,7 @@ class MainWindow(QtWidgets.QMainWindow):
indexRow = window.playlist.count() if window.clearedPlaylistNote else 0
for url in urls[::-1]:
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
dropfilepath = os.path.abspath(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
else:
dropfilepath = os.path.abspath(unicode(url.toLocalFile()))
@ -324,7 +325,7 @@ class MainWindow(QtWidgets.QMainWindow):
if indexRow == -1:
indexRow = window.playlist.count()
for url in urls[::-1]:
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
dropfilepath = os.path.abspath(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
else:
dropfilepath = os.path.abspath(unicode(url.toLocalFile()))
@ -567,7 +568,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient
def openPlaylistMenu(self, position):
indexes = self.playlist.selectedIndexes()
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
@ -609,7 +610,7 @@ class MainWindow(QtWidgets.QMainWindow):
def openRoomMenu(self, position):
# TODO: Deselect items after right click
indexes = self.listTreeView.selectedIndexes()
if sys.platform.startswith('win'):
if isWindows():
resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
resourcespath = utils.findWorkingDir() + u"/resources/"
@ -872,7 +873,7 @@ class MainWindow(QtWidgets.QMainWindow):
return
self.loadMediaBrowseSettings()
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.DontUseNativeDialog)
else:
options = QtWidgets.QFileDialog.Options()
@ -886,7 +887,7 @@ class MainWindow(QtWidgets.QMainWindow):
fileName, filtr = QtWidgets.QFileDialog.getOpenFileName(self, getMessage("browseformedia-label"), defaultdirectory,
browserfilter, "", options)
if fileName:
if sys.platform.startswith('win'):
if isWindows():
fileName = fileName.replace("/", "\\")
self.mediadirectory = os.path.dirname(fileName)
self._syncplayClient.fileSwitch.setCurrentDirectory(self.mediadirectory)
@ -900,7 +901,7 @@ class MainWindow(QtWidgets.QMainWindow):
return
self.loadMediaBrowseSettings()
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.DontUseNativeDialog)
else:
options = QtWidgets.QFileDialog.Options()
@ -916,7 +917,7 @@ class MainWindow(QtWidgets.QMainWindow):
self.updatingPlaylist = True
if fileNames:
for fileName in fileNames:
if sys.platform.startswith('win'):
if isWindows():
fileName = fileName.replace("/", "\\")
self.mediadirectory = os.path.dirname(fileName)
self._syncplayClient.fileSwitch.setCurrentDirectory(self.mediadirectory)
@ -1051,7 +1052,7 @@ class MainWindow(QtWidgets.QMainWindow):
@needsClient
def openAddMediaDirectoryDialog(self, MediaDirectoriesTextbox, MediaDirectoriesDialog):
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontUseNativeDialog)
else:
options = QtWidgets.QFileDialog.Options(QtWidgets.QFileDialog.ShowDirsOnly)
@ -1121,9 +1122,9 @@ class MainWindow(QtWidgets.QMainWindow):
self.showErrorMessage(getMessage("invalid-offset-value"))
def openUserGuide(self):
if sys.platform.startswith('linux'):
if isLinux():
self.QtGui.QDesktopServices.openUrl(QUrl("http://syncplay.pl/guide/linux/"))
elif sys.platform.startswith('win'):
elif isWindows():
self.QtGui.QDesktopServices.openUrl(QUrl("http://syncplay.pl/guide/windows/"))
else:
self.QtGui.QDesktopServices.openUrl(QUrl("http://syncplay.pl/guide/"))
@ -1452,7 +1453,7 @@ class MainWindow(QtWidgets.QMainWindow):
getMessage("update-menu-label"))
window.updateAction.triggered.connect(self.userCheckForUpdates)
if not sys.platform.startswith('darwin'):
if not isOSX():
window.helpMenu.addSeparator()
window.about = window.helpMenu.addAction(QtGui.QPixmap(self.resourcespath + 'syncplay.png'),
getMessage("about-menu-label"))
@ -1461,7 +1462,7 @@ class MainWindow(QtWidgets.QMainWindow):
window.about.triggered.connect(self.openAbout)
window.menuBar.addMenu(window.helpMenu)
if not sys.platform.startswith('darwin'):
if not isOSX():
window.mainLayout.setMenuBar(window.menuBar)
def openAbout(self):
@ -1597,7 +1598,7 @@ class MainWindow(QtWidgets.QMainWindow):
data = event.mimeData()
urls = data.urls()
if urls and urls[0].scheme() == 'file':
if sys.platform.startswith('darwin') and IsPySide:
if isOSX() and IsPySide:
dropfilepath = os.path.abspath(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
else:
dropfilepath = os.path.abspath(unicode(url.toLocalFile()))
@ -1732,11 +1733,11 @@ class MainWindow(QtWidgets.QMainWindow):
self._syncplayClient = None
self.folderSearchEnabled = True
self.QtGui = QtGui
if sys.platform.startswith('win'):
if isWindows():
self.resourcespath = utils.findWorkingDir() + u"\\resources\\"
else:
self.resourcespath = utils.findWorkingDir() + u"/resources/"
if sys.platform.startswith('darwin'):
if isOSX():
self.setWindowFlags(self.windowFlags())
else:
self.setWindowFlags(self.windowFlags() & Qt.AA_DontUseNativeMenuBar)

View File

@ -17,6 +17,18 @@ import subprocess
folderSearchEnabled = True
def isWindows():
return sys.platform.startswith(constants.OS_WINDOWS)
def isLinux():
return sys.platform.startswith(constants.OS_LINUX)
def isOSX():
return sys.platform.startswith(constants.OS_OSX)
def isBSD():
return constants.OS_BSD in sys.platform or sys.platform.startswith(constants.OS_DRAGONFLY)
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.