Browse Source

Clean up the messy platform checks.

Refer now to the global sabnzbd flags:
WIN32, POSIX, DARWIN, DARWIN_INTEL and FOUNDATION
tags/0.6.0
shypike 16 years ago
parent
commit
c3f7a0769e
  1. 27
      main/SABnzbd.py
  2. 49
      main/sabnzbd/__init__.py
  3. 3
      main/sabnzbd/assembler.py
  4. 5
      main/sabnzbd/cfg.py
  5. 10
      main/sabnzbd/codecs.py
  6. 6
      main/sabnzbd/interface.py
  7. 24
      main/sabnzbd/misc.py
  8. 26
      main/sabnzbd/newsunpack.py
  9. 7
      main/sabnzbd/newswrapper.py
  10. 5
      main/sabnzbd/postproc.py
  11. 3
      main/sabnzbd/tvsort.py
  12. 8
      main/sabnzbd/utils/rarfile.py

27
main/SABnzbd.py

@ -28,8 +28,7 @@ import signal
import re
import glob
import socket
if os.name=='nt':
import platform
import platform
try:
import Cheetah
@ -82,7 +81,7 @@ try:
import win32api
win32api.SetConsoleCtrlHandler(sabnzbd.sig_handler, True)
except ImportError:
if os.name == 'nt':
if sabnzbd.WIN32:
print "Sorry, requires Python module PyWin32."
exit(1)
@ -162,10 +161,10 @@ def print_help():
print " -w --weblogging <0..2> Set cherrypy logging (0= off, 1= on, 2= file-only) [*]"
print
print " -b --browser <0..1> Auto browser launch (0= off, 1= on) [*]"
if os.name != 'nt':
print " -d --daemon Fork daemon process"
else:
if sabnzbd.WIN32:
print " -d --daemon Use when run as a service"
else:
print " -d --daemon Fork daemon process"
print
print " --force Discard web-port timeout (see Wiki!)"
print " -h --help Print this message"
@ -278,14 +277,14 @@ def GetProfileInfo(vista):
sabnzbd.DIR_APPDATA = sabnzbd.DIR_PROG
sabnzbd.DIR_LCLDATA = sabnzbd.DIR_PROG
sabnzbd.DIR_HOME = sabnzbd.DIR_PROG
if os.name == 'nt':
if sabnzbd.WIN32:
# Ignore Win32 "logoff" signal
# This should work, but it doesn't
# Instead the signal_handler will ignore the "logoff" signal
#signal.signal(5, signal.SIG_IGN)
pass
ok = True
elif os.name == 'nt':
elif sabnzbd.WIN32:
specials = Get_User_ShellFolders()
try:
sabnzbd.DIR_APPDATA = '%s\\%s' % (specials['AppData'], DEF_WORKDIR)
@ -370,7 +369,7 @@ def print_modules():
else:
logging.warning("unzip binary... NOT found!")
if os.name != 'nt':
if not sabnzbd.WIN32:
if sabnzbd.newsunpack.NICE_COMMAND:
logging.info("nice binary... found (%s)", sabnzbd.newsunpack.NICE_COMMAND)
else:
@ -456,7 +455,7 @@ def get_webhost(cherryhost, cherryport, https_port):
sabnzbd.AMBI_LOCALHOST = True
logging.info("IPV6 has priority on this system, potential Firefox issue")
if ipv6 and ipv4 and cherryhost == '' and os.name == 'nt':
if ipv6 and ipv4 and cherryhost == '' and sabnzbd.WIN32:
logging.warning("Please be aware the 0.0.0.0 hostname will need an IPv6 address for external access")
if cherryport == None:
@ -628,7 +627,7 @@ def main():
for opt, arg in opts:
if (opt in ('-d', '--daemon')):
if os.name != 'nt':
if not sabnzbd.WIN32:
fork = True
AUTOBROWSER = False
sabnzbd.DAEMON = True
@ -688,7 +687,7 @@ def main():
testlog = True
# Detect Vista or higher
if os.name == 'nt':
if sabnzbd.WIN32:
if platform.platform().find('Windows-32bit') >= 0:
vista = True
vista64 = 'ProgramFiles(x86)' in os.environ
@ -844,7 +843,7 @@ def main():
logging.info('--------------------------------')
logging.info('%s-%s (rev=%s)', sabnzbd.MY_NAME, sabnzbd.__version__, sabnzbd.__baseline__)
if os.name == 'nt':
if sabnzbd.WIN32:
suffix = ''
if vista: suffix = ' (=Vista)'
if vista64: suffix = ' (=Vista64)'
@ -889,7 +888,7 @@ def main():
sabnzbd.WEB_COLOR2 = CheckColor(sabnzbd.cfg.WEB_COLOR2.get(), web_dir2)
sabnzbd.cfg.WEB_COLOR2.set(sabnzbd.WEB_COLOR2)
if fork and os.name != 'nt':
if fork and not sabnzbd.WIN32:
daemonize()
# Save the INI file

49
main/sabnzbd/__init__.py

@ -30,22 +30,35 @@ import gzip
import subprocess
import time
import cherrypy
from threading import RLock, Lock, Condition, Thread
try:
import ctypes
KERNEL32 = ctypes.windll.LoadLibrary("Kernel32.dll")
except:
KERNEL32 = None
#------------------------------------------------------------------------
# Determine platform flags
try:
# Try to import OSX library
import Foundation
import subprocess
DARWIN = True
except:
DARWIN = False
WIN32 = DARWIN = DARWIN_INTEL = POSIX = FOUNDATION = False
KERNEL32 = None
from threading import RLock, Lock, Condition, Thread
if os.name == 'nt':
WIN32 = True
try:
import ctypes
KERNEL32 = ctypes.windll.LoadLibrary("Kernel32.dll")
except:
pass
elif os.name == 'posix':
POSIX = True
import platform
if platform.system().lower() == 'darwin':
DARWIN = True
try:
import Foundation
FOUNDATION = True
except:
pass
if platform.machine() == 'i386':
DARWIN_INTEL = True
#------------------------------------------------------------------------
import sabnzbd.nzbqueue as nzbqueue
import sabnzbd.postproc as postproc
@ -111,7 +124,7 @@ __INITIALIZED__ = False
################################################################################
def sig_handler(signum = None, frame = None):
global SABSTOP
if os.name == 'nt' and type(signum) != type(None) and DAEMON and signum==5:
if sabnzbd.WIN32 and type(signum) != type(None) and DAEMON and signum==5:
# Ignore the "logoff" event when running as a Win32 daemon
return True
if type(signum) != type(None):
@ -389,7 +402,7 @@ def add_nzbfile(nzbfile, pp=None, script=None, cat=None, priority=NORMAL_PRIORIT
filename = codecs.name_fixer(nzbfile.filename)
if os.name != 'nt':
if not sabnzbd.WIN32:
# If windows client sends file to Unix server backslashed may
# be included, so convert these
filename = filename.replace('\\', '/')
@ -443,7 +456,7 @@ def system_shutdown():
while __INITIALIZED__:
time.sleep(1.0)
if os.name == 'nt':
if sabnzbd.WIN32:
try:
import win32security
import win32api
@ -471,7 +484,7 @@ def system_shutdown():
def system_hibernate():
logging.info("Performing system hybernation")
try:
if os.name == 'nt':
if sabnzbd.WIN32:
subprocess.Popen("rundll32 powrprof.dll,SetSuspendState Hibernate")
time.sleep(10)
except:
@ -481,7 +494,7 @@ def system_hibernate():
def system_standby():
logging.info("Performing system standby")
try:
if os.name == 'nt':
if sabnzbd.WIN32:
subprocess.Popen("rundll32 powrprof.dll,SetSuspendState Standby")
elif DARWIN:
subprocess.call(['osascript', '-e','tell app "System Events" to sleep'])

3
main/sabnzbd/assembler.py

@ -27,8 +27,7 @@ import logging
import struct
from threading import Thread
from time import sleep
if os.name == 'nt':
import subprocess
import subprocess
try:
import hashlib
new_md5 = hashlib.md5

5
main/sabnzbd/cfg.py

@ -20,6 +20,7 @@ sabnzbd.cfg - Configuration Parameters
"""
import os
import sabnzbd
from sabnzbd.constants import *
from sabnzbd.config import OptionBool, OptionNumber, OptionPassword, \
OptionDir, OptionStr, OptionList, no_nonsense, \
@ -133,11 +134,11 @@ DIRSCAN_DIR = OptionDir('misc', 'dirscan_dir', create=False)
DIRSCAN_SPEED = OptionNumber('misc', 'dirscan_speed', DEF_SCANRATE, 1, 3600)
CHERRYHOST = OptionStr('misc','host', DEF_HOST)
if os.name == 'nt':
if sabnzbd.WIN32:
CHERRYPORT = OptionStr('misc','port', DEF_PORT_WIN)
else:
CHERRYPORT = OptionStr('misc','port', DEF_PORT_UNIX)
if os.name == 'nt':
if sabnzbd.WIN32:
HTTPS_PORT = OptionStr('misc','https_port', DEF_PORT_WIN_SSL)
else:
HTTPS_PORT = OptionStr('misc','https_port', DEF_PORT_UNIX_SSL)

10
main/sabnzbd/codecs.py

@ -25,9 +25,7 @@ from xml.sax.saxutils import escape
import sabnzbd
gNT = os.name == 'nt'
gUTF = sys.getfilesystemencoding().lower() == 'utf-8'
#gUTF = sys.getfilesystemencoding().lower() == 'utf-8'
def name_fixer(p):
@ -42,7 +40,7 @@ def name_fixer(p):
def unicode2local(p):
""" Convert Unicode filename to appropriate local encoding
"""
if gNT:
if sabnzbd.WIN32:
return p.encode('Latin-1', 'replace').replace('?', '_')
else:
return p.encode('utf-8', 'replace').replace('?', '_')
@ -105,8 +103,8 @@ gTABLE850 = string.maketrans(
def TRANS(p):
""" For Windows: Translate CP850 to Python's Latin-1
"""
global gTABLE850, gNT
if gNT:
global gTABLE850
if sabnzbd.WIN32:
return p.translate(gTABLE850)
else:
return p

6
main/sabnzbd/interface.py

@ -1468,7 +1468,7 @@ class ConfigSwitches:
conf, pnfo_list, bytespersec = build_header(self.__prim)
conf['nt'] = os.name == 'nt'
conf['nt'] = sabnzbd.WIN32
conf['have_nice'] = bool(sabnzbd.newsunpack.NICE_COMMAND)
conf['have_ionice'] = bool(sabnzbd.newsunpack.IONICE_COMMAND)
@ -1613,7 +1613,7 @@ class ConfigGeneral:
cfg.BANDWIDTH_LIMIT.set(bandwith_limit)
cfg.RSS_RATE.set(rss_rate)
cfg.REFRESH_RATE.set(refresh_rate)
if cleanup_list and os.name == 'nt':
if cleanup_list and sabnzbd.WIN32:
cleanup_list = cleanup_list.lower()
cfg.CLEANUP_LIST.set_string(cleanup_list)
cfg.CACHE_LIMIT.set(cache_limitstr)
@ -2493,7 +2493,7 @@ def build_header(prim):
header['webdir'] = sabnzbd.WEB_DIR2
header['finishaction'] = sabnzbd.QUEUECOMPLETE
header['nt'] = os.name == 'nt'
header['nt'] = sabnzbd.WIN32
header['darwin'] = sabnzbd.DARWIN
bytespersec = bpsmeter.method.get_bps()

24
main/sabnzbd/misc.py

@ -29,20 +29,14 @@ import tempfile
import shutil
import threading
try:
# Try to import OSX library
import Foundation
HAVE_FOUNDATION = True
except:
HAVE_FOUNDATION = False
import sabnzbd
from sabnzbd.decorators import synchronized
from sabnzbd.constants import *
import nzbqueue
import sabnzbd.config as config
import sabnzbd.cfg as cfg
if sabnzbd.FOUNDATION:
import Foundation
RE_VERSION = re.compile('(\d+)\.(\d+)\.(\d+)([a-zA-Z]*)(\d*)')
RE_UNITS = re.compile('(\d+\.*\d*)\s*([KMGTP]*)', re.I)
@ -133,7 +127,7 @@ def Cat2OptsDef(fname, cat=None):
################################################################################
# sanitize_filename #
################################################################################
if os.name == 'nt':
if sabnzbd.WIN32:
CH_ILLEGAL = r'\/<>?*:|"'
CH_LEGAL = r'++{}!@-#`'
else:
@ -196,7 +190,7 @@ def CreateAllDirs(path, umask=False):
""" Create all required path elements and set umask on all
Return True if last elelent could be made or exists """
result = True
if os.name == 'nt':
if sabnzbd.WIN32:
try:
os.makedirs(path)
except:
@ -227,7 +221,7 @@ def CreateAllDirs(path, umask=False):
# Real_Path #
################################################################################
def real_path(loc, path):
if not ((os.name == 'nt' and len(path)>1 and path[0].isalpha() and path[1] == ':') or \
if not ((sabnzbd.WIN32 and len(path)>1 and path[0].isalpha() and path[1] == ':') or \
(path and (path[0] == '/' or path[0] == '\\'))
):
path = loc + '/' + path
@ -390,7 +384,7 @@ def panic_message(panic, a=None, b=None):
if (not cfg.AUTOBROWSER.get()) or sabnzbd.DAEMON:
return
if os.name == 'nt':
if sabnzbd.WIN32:
os_str = 'Press Startkey+R and type the line (example):'
prog_path = '"%s"' % sabnzbd.MY_FULLNAME
else:
@ -647,7 +641,7 @@ def ExitSab(value):
#------------------------------------------------------------------------------
def Notify(notificationName, message):
""" Send a notification to the OS (OSX-only) """
if HAVE_FOUNDATION:
if sabnzbd.FOUNDATION:
pool = Foundation.NSAutoreleasePool.alloc().init()
nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
nc.postNotificationName_object_(notificationName, message)
@ -845,7 +839,7 @@ def OnCleanUpList(filename, skip_nzb=False):
if cfg.CLEANUP_LIST.get():
ext = os.path.splitext(filename)[1].strip().strip('.')
if os.name == 'nt': ext = ext.lower()
if sabnzbd.WIN32: ext = ext.lower()
for k in cfg.CLEANUP_LIST.get():
item = k.strip().strip('.')
@ -868,7 +862,7 @@ def get_filename(path):
def loadavg():
""" Return 1, 5 and 15 minute load average of host or "" if not supported
"""
if os.name == 'nt' or sabnzbd.DARWIN:
if sabnzbd.WIN32 or sabnzbd.DARWIN:
return ""
try:
loadavgstr = open('/proc/loadavg', 'r').readline().strip()

26
main/sabnzbd/newsunpack.py

@ -25,11 +25,6 @@ import re
import subprocess
import logging
from time import time
try:
import Foundation #OSX
import platform
except:
pass
import sabnzbd
from sabnzbd.codecs import TRANS, unicode2local
@ -37,16 +32,15 @@ from sabnzbd.utils.rarfile import is_rarfile, RarFile
from sabnzbd.misc import format_time_string
import sabnzbd.cfg as cfg
try:
from win32con import SW_HIDE
from win32process import STARTF_USESHOWWINDOW, IDLE_PRIORITY_CLASS
except ImportError:
pass
# Define option handlers
if sabnzbd.WIN32:
try:
from win32con import SW_HIDE
from win32process import STARTF_USESHOWWINDOW, IDLE_PRIORITY_CLASS
except ImportError:
pass
# Regex globals
RAR_RE = re.compile(r'\.(?P<ext>part\d*\.rar|rar|s\d\d|r\d\d|\d\d\d)$', re.I)
RAR_RE_V3 = re.compile(r'\.(?P<ext>part\d*)$', re.I)
@ -69,7 +63,7 @@ def find_programs(curdir):
"""Find external programs
"""
if sabnzbd.DARWIN:
if platform.machine() == 'i386':
if sabnzbd.DARWIN_INTEL:
p = os.path.abspath(curdir + '/osx/par2/par2')
if os.access(p, os.X_OK):
sabnzbd.newsunpack.PAR2_COMMAND = p
@ -83,7 +77,7 @@ def find_programs(curdir):
if os.access(p, os.X_OK):
sabnzbd.newsunpack.RAR_COMMAND = p
if os.name == 'nt':
if sabnzbd.WIN32:
p = os.path.abspath(curdir + '/win/par2/par2.exe')
if os.access(p, os.X_OK):
sabnzbd.newsunpack.PAR2_COMMAND = p
@ -1004,7 +998,7 @@ def PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables):
#-------------------------------------------------------------------------------
def build_command(command):
if os.name != "nt":
if not sabnzbd.WIN32:
if IONICE_COMMAND and cfg.ionice.get().strip():
lst = cfg.ionice.get().split()
lst.reverse()

7
main/sabnzbd/newswrapper.py

@ -22,12 +22,13 @@ sabnzbd.newswrapper
import errno
import socket
from threading import Thread
from nntplib import NNTPPermanentError
from time import time
from sabnzbd.constants import *
import logging
import sabnzbd
from sabnzbd.constants import *
try:
from OpenSSL import SSL
_ssl = SSL
@ -109,7 +110,7 @@ class NNTP:
try:
# Windows must do the connection in a seperate thread due to non-blocking issues
# If the server wants to be blocked (for testing) then use the linux route
if os.name == 'nt' and not block:
if sabnzbd.WIN32 and not block:
Thread(target=con, args=(self.sock, self.host, self.port, sslenabled, self)).start()
else:
self.sock.connect((self.host, self.port))

5
main/sabnzbd/postproc.py

@ -28,8 +28,7 @@ import urllib
import time
import re
from xml.sax.saxutils import escape
if os.name == 'nt':
import subprocess
import subprocess
from sabnzbd.decorators import synchronized
from sabnzbd.newsunpack import unpack_magic, par2_repair, external_processing
@ -366,7 +365,7 @@ class PostProcessor(Thread):
workdir_complete = file_sorter.move(workdir_complete)
## Set permissions right
if cfg.UMASK.get() and (os.name != 'nt'):
if cfg.UMASK.get() and not sabnzbd.WIN32:
perm_script(workdir_complete, cfg.UMASK.get())
## Run the user script

3
main/sabnzbd/tvsort.py

@ -24,6 +24,7 @@ import logging
import re
import sabnzbd
from sabnzbd.misc import move_to_path, cleanup_empty_directories, get_unique_filename
from sabnzbd.constants import series_match, date_match, year_match
import sabnzbd.cfg as cfg
@ -844,7 +845,7 @@ def stripFolders(folders):
def strip_all(x):
x = x.strip().strip('_')
if os.name == 'nt':
if sabnzbd.WIN32:
# Don't want to strip . from folders such as /.sabnzbd/
x = x.strip('.')
x = x.strip()

8
main/sabnzbd/utils/rarfile.py

@ -232,7 +232,7 @@ class RarFile:
id = fd.read(len(RAR_ID))
if id != RAR_ID:
raise Exception("Not a Rar")
volume = 0 # first vol (.rar) is 0
more_vols = 0
while 1:
@ -428,7 +428,7 @@ class RarFile:
volume += 1
return buf
return buf
# put file compressed data into temporary .rar archive, and run
# unrar on that, thus avoiding unrar going over whole archive
@ -460,7 +460,7 @@ class RarFile:
# extract using unrar
def _extract_unrar(self, rarfile, inf):
fn = inf.filename
if os.name == 'nt':
if sabnzbd.WIN32:
# Windows unrar wants '\', not '/'
fn = fn.replace("/", "\\")
else:
@ -468,7 +468,7 @@ class RarFile:
fn = fn.replace("`", "\\`")
fn = fn.replace('"', '\\"')
fn = fn.replace("$", "\\$")
err, buf = sabnzbd.SimpleRarExtract(rarfile, fn)
if err > 0:
raise Exception("Error reading file")

Loading…
Cancel
Save