forked from sabnzbd/sabnzbd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SABnzbd.py
executable file
·1691 lines (1464 loc) · 58.8 KB
/
SABnzbd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python -OO
# Copyright 2008-2011 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
if sys.version_info < (2,5):
print "Sorry, requires Python 2.5 or higher."
sys.exit(1)
import logging
import logging.handlers
import os
import getopt
import signal
import socket
import platform
import time
try:
import Cheetah
if Cheetah.Version[0] != '2':
raise ValueError
except ValueError:
print "Sorry, requires Python module Cheetah 2.0rc7 or higher."
sys.exit(1)
except:
print "The Python module Cheetah is required"
sys.exit(1)
import cherrypy
if not cherrypy.__version__.startswith("3.2"):
print "Sorry, requires Python module Cherrypy 3.2 (use the included version)"
sys.exit(1)
from cherrypy import _cpserver
from cherrypy import _cpwsgi_server
SQLITE_DLL = True
try:
from sqlite3 import version as sqlite3_version
except:
try:
from pysqlite2.dbapi2 import version as sqlite3_version
except:
if os.name != 'nt':
print "Sorry, requires Python module sqlite3"
print "Try: apt-get install python-pysqlite2"
sys.exit(1)
else:
SQLITE_DLL = False
import sabnzbd
import sabnzbd.lang
import sabnzbd.interface
from sabnzbd.constants import *
import sabnzbd.newsunpack
from sabnzbd.misc import get_user_shellfolders, real_path, \
check_latest_version, exit_sab, \
split_host, get_ext, create_https_certificates, \
windows_variant, ip_extract, set_serv_parms, get_serv_parms, globber
from sabnzbd.panic import panic_tmpl, panic_port, panic_host, panic_fwall, \
panic_sqlite, panic, launch_a_browser, panic_xport
import sabnzbd.scheduler as scheduler
import sabnzbd.config as config
import sabnzbd.cfg
import sabnzbd.downloader
from sabnzbd.encoding import unicoder, latin1
from sabnzbd.utils import osx
from threading import Thread
LOG_FLAG = False # Global for this module, signalling loglevel change
_first_log = True
def FORCELOG(txt):
global _first_log
if _first_log:
os.remove('d:/temp/debug.txt')
_first_log = False
ff = open('d:/temp/debug.txt', 'a+')
ff.write(txt)
ff.write('\n')
ff.close()
#------------------------------------------------------------------------------
try:
import win32api
import win32serviceutil, win32evtlogutil, win32event, win32service, pywintypes
win32api.SetConsoleCtrlHandler(sabnzbd.sig_handler, True)
from util.mailslot import MailSlot
from util.apireg import get_connection_info, set_connection_info, del_connection_info
except ImportError:
class MailSlot:
pass
if sabnzbd.WIN32:
print "Sorry, requires Python module PyWin32."
sys.exit(1)
def guard_loglevel():
""" Callback function for guarding loglevel """
global LOG_FLAG
LOG_FLAG = True
#------------------------------------------------------------------------------
# Improved RotatingFileHandler
# See: http://www.mail-archive.com/python-bugs-list@python.org/msg53913.html
# http://bugs.python.org/file14420/NTSafeLogging.py
# Thanks Erik Antelman
#
if sabnzbd.WIN32:
import msvcrt
import _subprocess
import codecs
def duplicate(handle, inheritable=False):
target_process = _subprocess.GetCurrentProcess()
return _subprocess.DuplicateHandle(
_subprocess.GetCurrentProcess(), handle, target_process,
0, inheritable, _subprocess.DUPLICATE_SAME_ACCESS).Detach()
class NewRotatingFileHandler(logging.handlers.RotatingFileHandler):
def _open(self):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
"""
if self.encoding is None:
stream = open(self.baseFilename, self.mode)
newosf = duplicate(msvcrt.get_osfhandle(stream.fileno()), inheritable=False)
newFD = msvcrt.open_osfhandle(newosf,os.O_APPEND)
newstream = os.fdopen(newFD,self.mode)
stream.close()
return newstream
else:
stream = codecs.open(self.baseFilename, self.mode, self.encoding)
return stream
else:
NewRotatingFileHandler = logging.handlers.RotatingFileHandler
#------------------------------------------------------------------------------
class FilterCP3:
### Filter out all CherryPy3-Access logging that we receive,
### because we have the root logger
def __init__(self):
pass
def filter(self, record):
_cplogging = record.module == '_cplogging'
# Python2.4 fix
# record has no attribute called funcName under python 2.4
if hasattr(record, 'funcName'):
access = record.funcName == 'access'
else:
access = True
return not (_cplogging and access)
class guiHandler(logging.Handler):
"""
Logging handler collects the last warnings/errors/exceptions
to be displayed in the web-gui
"""
def __init__(self, size):
"""
Initializes the handler
"""
logging.Handler.__init__(self)
self.size = size
self.store = []
def emit(self, record):
"""
Emit a record by adding it to our private queue
"""
if len(self.store) >= self.size:
# Loose the oldest record
self.store.pop(0)
try:
self.store.append(self.format(record))
except UnicodeDecodeError:
# Catch elusive Unicode conversion problems
pass
def clear(self):
self.store = []
def count(self):
return len(self.store)
def last(self):
if self.store:
return self.store[len(self.store)-1]
else:
return ""
def content(self):
"""
Return an array with last records
"""
return self.store
#------------------------------------------------------------------------------
def print_help():
print
print "Usage: %s [-f <configfile>] <other options>" % sabnzbd.MY_NAME
print
print "Options marked [*] are stored in the config file"
print
print "Options:"
print " -f --config-file <ini> Location of config file"
print " -s --server <srv:port> Listen on server:port [*]"
print " -t --templates <templ> Template directory [*]"
print " -2 --template2 <templ> Secondary template dir [*]"
print
print " -l --logging <0..2> Set logging level (0= least, 2= most) [*]"
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 sabnzbd.WIN32:
print " -d --daemon Use when run as a service"
else:
print " -d --daemon Fork daemon process"
print " --pid <path> Create a PID file in the listed folder (full path)"
print
print " --force Discard web-port timeout (see Wiki!)"
print " -h --help Print this message"
print " -v --version Print version information"
print " -c --clean Remove queue, cache and logs"
print " -p --pause Start in paused mode"
print " --repair Add orphaned jobs from the incomplete folder to the queue"
print " --repair-all Try to reconstruct the queue from the incomplete folder"
print " with full data reconstruction"
print " --https <port> Port to use for HTTPS server"
print " --log-all Log all article handling (for developers)"
print " --new Run a new instance of SABnzbd"
def print_version():
print """
%s-%s
Copyright (C) 2008-2011, The SABnzbd-Team <team@sabnzbd.org>
SABnzbd comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. It is licensed under the
GNU GENERAL PUBLIC LICENSE Version 2 or (at your option) any later version.
""" % (sabnzbd.MY_NAME, sabnzbd.__version__)
#------------------------------------------------------------------------------
def daemonize():
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError:
print "fork() failed"
sys.exit(1)
os.chdir(sabnzbd.DIR_PROG)
os.setsid()
# Make sure I can read my own files and shut out others
prev= os.umask(0)
os.umask(prev and int('077',8))
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError:
print "fork() failed"
sys.exit(1)
dev_null = file('/dev/null', 'r')
os.dup2(dev_null.fileno(), sys.stdin.fileno())
#------------------------------------------------------------------------------
def Bail_Out(browserhost, cherryport, err=''):
"""Abort program because of CherryPy troubles
"""
logging.error(Ta('Failed to start web-interface') + ' : ' + str(err))
if not sabnzbd.DAEMON:
if '13' in err:
panic_xport(browserhost, cherryport)
elif '49' in err:
panic_host(browserhost, cherryport)
else:
panic_port(browserhost, cherryport)
sabnzbd.halt()
exit_sab(2)
#------------------------------------------------------------------------------
def Web_Template(key, defweb, wdir):
""" Determine a correct web template set,
return full template path
"""
if wdir is None:
try:
wdir = fix_webname(key())
except:
wdir = ''
if not wdir:
wdir = defweb
key.set(wdir)
if not wdir:
# No default value defined, accept empty path
return ''
full_dir = real_path(sabnzbd.DIR_INTERFACES, wdir)
full_main = real_path(full_dir, DEF_MAIN_TMPL)
logging.info("Web dir is %s", full_dir)
if not os.path.exists(full_main):
logging.warning(Ta('Cannot find web template: %s, trying standard template'), full_main)
full_dir = real_path(sabnzbd.DIR_INTERFACES, DEF_STDINTF)
full_main = real_path(full_dir, DEF_MAIN_TMPL)
if not os.path.exists(full_main):
logging.exception('Cannot find standard template: %s', full_dir)
panic_tmpl(full_dir)
exit_sab(1)
#sabnzbd.lang.install_language(real_path(full_dir, DEF_INT_LANGUAGE), sabnzbd.cfg.language(), wdir)
return real_path(full_dir, "templates")
#------------------------------------------------------------------------------
def CheckColor(color, web_dir):
""" Check existence of color-scheme """
if color and os.path.exists(os.path.join(web_dir,'static/stylesheets/colorschemes/'+color+'.css')):
return color
elif color and os.path.exists(os.path.join(web_dir,'static/stylesheets/colorschemes/'+color)):
return color
else:
return ''
#------------------------------------------------------------------------------
def fix_webname(name):
if name:
xname = name.title()
else:
xname = ''
if xname in ('Default',):
return 'Classic'
elif xname in ('Classic', 'Plush', 'Mobile'):
return xname
elif xname in ('Smpl', 'Wizard'):
return name.lower()
else:
return name
#------------------------------------------------------------------------------
def GetProfileInfo(vista_plus):
""" Get the default data locations
"""
ok = False
if sabnzbd.DAEMON:
# In daemon mode, do not try to access the user profile
# just assume that everything defaults to the program dir
sabnzbd.DIR_APPDATA = sabnzbd.DIR_PROG
sabnzbd.DIR_LCLDATA = sabnzbd.DIR_PROG
sabnzbd.DIR_HOME = sabnzbd.DIR_PROG
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 sabnzbd.WIN32:
specials = get_user_shellfolders()
try:
sabnzbd.DIR_APPDATA = '%s\\%s' % (specials['AppData'], DEF_WORKDIR)
sabnzbd.DIR_LCLDATA = '%s\\%s' % (specials['Local AppData'], DEF_WORKDIR)
sabnzbd.DIR_HOME = specials['Personal']
ok = True
except:
try:
if vista_plus:
root = os.environ['AppData']
user = os.environ['USERPROFILE']
sabnzbd.DIR_APPDATA = '%s\\%s' % (root.replace('\\Roaming', '\\Local'), DEF_WORKDIR)
sabnzbd.DIR_HOME = '%s\\Documents' % user
else:
root = os.environ['USERPROFILE']
sabnzbd.DIR_APPDATA = '%s\\%s' % (root, DEF_WORKDIR)
sabnzbd.DIR_HOME = root
try:
# Conversion to 8bit ASCII required for CherryPy
sabnzbd.DIR_APPDATA = sabnzbd.DIR_APPDATA.encode('latin-1')
sabnzbd.DIR_HOME = sabnzbd.DIR_HOME.encode('latin-1')
ok = True
except:
# If unconvertible characters exist, use MSDOS name
try:
sabnzbd.DIR_APPDATA = win32api.GetShortPathName(sabnzbd.DIR_APPDATA)
sabnzbd.DIR_HOME = win32api.GetShortPathName(sabnzbd.DIR_HOME)
ok = True
except:
pass
sabnzbd.DIR_LCLDATA = sabnzbd.DIR_APPDATA
except:
pass
elif sabnzbd.DARWIN:
home = os.environ.get('HOME')
if home:
sabnzbd.DIR_APPDATA = '%s/Library/Application Support/SABnzbd' % home
sabnzbd.DIR_LCLDATA = sabnzbd.DIR_APPDATA
sabnzbd.DIR_HOME = home
ok = True
else:
# Unix/Linux
home = os.environ.get('HOME')
if home:
sabnzbd.DIR_APPDATA = '%s/.%s' % (home, DEF_WORKDIR)
sabnzbd.DIR_LCLDATA = sabnzbd.DIR_APPDATA
sabnzbd.DIR_HOME = home
ok = True
if not ok:
panic("Cannot access the user profile.",
"Please start with sabnzbd.ini file in another location")
exit_sab(2)
#------------------------------------------------------------------------------
def print_modules():
""" Log all detected optional or external modules
"""
if sabnzbd.decoder.HAVE_YENC:
logging.info("_yenc module... found!")
else:
if hasattr(sys, "frozen"):
logging.error(Ta('_yenc module... NOT found!'))
else:
logging.info("_yenc module... NOT found!")
if sabnzbd.newsunpack.PAR2_COMMAND:
logging.info("par2 binary... found (%s)", sabnzbd.newsunpack.PAR2_COMMAND)
else:
logging.error(Ta('par2 binary... NOT found!'))
if sabnzbd.newsunpack.PAR2C_COMMAND:
logging.info("par2-classic binary... found (%s)", sabnzbd.newsunpack.PAR2C_COMMAND)
if sabnzbd.newsunpack.RAR_COMMAND:
logging.info("unrar binary... found (%s)", sabnzbd.newsunpack.RAR_COMMAND)
else:
logging.warning(Ta('unrar binary... NOT found'))
if sabnzbd.newsunpack.ZIP_COMMAND:
logging.info("unzip binary... found (%s)", sabnzbd.newsunpack.ZIP_COMMAND)
else:
logging.warning(Ta('unzip binary... NOT found!'))
if not sabnzbd.WIN32:
if sabnzbd.newsunpack.NICE_COMMAND:
logging.info("nice binary... found (%s)", sabnzbd.newsunpack.NICE_COMMAND)
else:
logging.info("nice binary... NOT found!")
if sabnzbd.newsunpack.IONICE_COMMAND:
logging.info("ionice binary... found (%s)", sabnzbd.newsunpack.IONICE_COMMAND)
else:
logging.info("ionice binary... NOT found!")
if sabnzbd.newswrapper.HAVE_SSL:
logging.info("pyOpenSSL... found (%s)", sabnzbd.newswrapper.HAVE_SSL)
else:
logging.info("pyOpenSSL... NOT found - try apt-get install python-pyopenssl (SSL is optional)")
#------------------------------------------------------------------------------
def get_webhost(cherryhost, cherryport, https_port):
""" Determine the webhost address and port,
return (host, port, browserhost)
"""
if cherryhost is None:
cherryhost = sabnzbd.cfg.cherryhost()
else:
sabnzbd.cfg.cherryhost.set(cherryhost)
# Get IP address, but discard APIPA/IPV6
# If only APIPA's or IPV6 are found, fall back to localhost
ipv4 = ipv6 = False
localhost = hostip = 'localhost'
try:
info = socket.getaddrinfo(socket.gethostname(), None)
except:
# Hostname does not resolve, use 0.0.0.0
cherryhost = '0.0.0.0'
info = socket.getaddrinfo(localhost, None)
for item in info:
ip = str(item[4][0])
if ip.startswith('169.254.'):
pass # Is an APIPA
elif ':' in ip:
ipv6 = True
elif '.' in ip and not ipv4:
ipv4 = True
hostip = ip
# A blank host will use the local ip address
if cherryhost == '':
if ipv6 and ipv4:
# To protect Firefox users, use numeric IP
cherryhost = hostip
browserhost = hostip
else:
cherryhost = socket.gethostname()
browserhost = cherryhost
# 0.0.0.0 will listen on all ipv4 interfaces (no ipv6 addresses)
elif cherryhost == '0.0.0.0':
# Just take the gamble for this
cherryhost = '0.0.0.0'
browserhost = localhost
# :: will listen on all ipv6 interfaces (no ipv4 addresses)
elif cherryhost in ('::','[::]'):
cherryhost = cherryhost.strip('[').strip(']')
# Assume '::1' == 'localhost'
browserhost = localhost
# IPV6 address
elif '[' in cherryhost or ':' in cherryhost:
browserhost = cherryhost
# IPV6 numeric address
elif cherryhost.replace('.', '').isdigit():
# IPV4 numerical
browserhost = cherryhost
elif cherryhost == localhost:
cherryhost = localhost
browserhost = localhost
else:
# If on Vista and/or APIPA, use numerical IP, to help FireFoxers
if ipv6 and ipv4:
cherryhost = hostip
browserhost = cherryhost
# Some systems don't like brackets in numerical ipv6
if sabnzbd.DARWIN:
cherryhost = cherryhost.strip('[]')
else:
try:
info = socket.getaddrinfo(cherryhost, None)
except:
cherryhost = cherryhost.strip('[]')
if ipv6 and ipv4 and \
(browserhost not in ('localhost', '127.0.0.1', '[::1]', '::1')):
sabnzbd.AMBI_LOCALHOST = True
logging.info("IPV6 has priority on this system, potential Firefox issue")
if ipv6 and ipv4 and cherryhost == '' and sabnzbd.WIN32:
logging.warning(Ta('Please be aware the 0.0.0.0 hostname will need an IPv6 address for external access'))
if cherryhost == 'localhost' and not sabnzbd.WIN32 and not sabnzbd.DARWIN:
# On the Ubuntu family, localhost leads to problems for CherryPy
ips = ip_extract()
if '127.0.0.1' in ips and '::1' in ips:
cherryhost = '127.0.0.1'
if ips[0] != '127.0.0.1':
browserhost = '127.0.0.1'
# This is to please Chrome on OSX
if cherryhost == 'localhost' and sabnzbd.DARWIN:
cherryhost = '127.0.0.1'
browserhost = 'localhost'
if cherryport is None:
cherryport = sabnzbd.cfg.cherryport.get_int()
else:
sabnzbd.cfg.cherryport.set(str(cherryport))
if https_port is None:
https_port = sabnzbd.cfg.https_port.get_int()
else:
sabnzbd.cfg.https_port.set(str(https_port))
# if the https port was specified, assume they want HTTPS enabling also
sabnzbd.cfg.enable_https.set(True)
if cherryport == https_port:
sabnzbd.cfg.enable_https.set(False)
# Should have a translated message, but that's not available yet
#logging.error(Ta('HTTP and HTTPS ports cannot be the same'))
logging.error('HTTP and HTTPS ports cannot be the same')
return cherryhost, cherryport, browserhost, https_port
def is_sabnzbd_running(url):
""" Return True when there's already a SABnzbd instance running.
"""
try:
url = '%s&mode=version' % (url)
ver = sabnzbd.newsunpack.get_from_url(url)
if ver and ver.strip(' \n\r\t') == sabnzbd.__version__:
return True
else:
return False
except:
return False
def find_free_port(host, currentport):
""" Return a free port, 0 when nothing is free
"""
n = 0
while n < 10 and currentport <= 49151:
try:
cherrypy.process.servers.check_port(host, currentport)
return currentport
except:
currentport += 5
n += 1
return 0
def check_for_sabnzbd(url, upload_nzbs, allow_browser=True):
""" Check for a running instance of sabnzbd(same version) on this port
allow_browser==True|None will launch the browser, False will not.
"""
if allow_browser is None:
allow_browser = True
if is_sabnzbd_running(url):
# Upload any specified nzb files to the running instance
if upload_nzbs:
from sabnzbd.utils.upload import upload_file
for f in upload_nzbs:
upload_file(url, f)
else:
# Launch the web browser and quit since sabnzbd is already running
# Trim away everything after the final slash in the URL
url = url[:url.rfind('/')+1]
launch_a_browser(url, force=allow_browser)
exit_sab(0)
return True
return False
def copy_old_files(newpath):
""" OSX only:
If no INI file found but old one exists, copy it
When copying the INI, also copy rss, bookmarks and watched-data
"""
if not os.path.exists(os.path.join(newpath, DEF_INI_FILE)):
if not os.path.exists(newpath):
os.mkdir(newpath)
oldpath = os.environ['HOME'] + "/.sabnzbd"
oldini = os.path.join(oldpath, DEF_INI_FILE)
if os.path.exists(oldini):
import shutil
try:
shutil.copy(oldini, newpath)
except:
pass
oldpath = os.path.join(oldpath, DEF_CACHE_DIR)
newpath = os.path.join(newpath, DEF_CACHE_DIR)
if not os.path.exists(newpath):
os.mkdir(newpath)
try:
shutil.copy(os.path.join(oldpath, RSS_FILE_NAME), newpath)
except:
pass
try:
shutil.copy(os.path.join(oldpath, BOOKMARK_FILE_NAME), newpath)
except:
pass
try:
shutil.copy(os.path.join(oldpath, SCAN_FILE_NAME), newpath)
except:
pass
def evaluate_inipath(path):
""" Derive INI file path from a partial path.
Full file path: if file does not exist the name must contain a dot
but not a leading dot.
foldername is enough, the standard name will be appended.
"""
path = os.path.normpath(os.path.abspath(path))
inipath = os.path.join(path, DEF_INI_FILE)
if os.path.isdir(path):
return inipath
elif os.path.isfile(path):
return path
else:
dirpart, name = os.path.split(path)
if name.find('.') < 1:
return inipath
else:
return path
def cherrypy_logging(log_path, log_handler):
""" Setup CherryPy logging
"""
log = cherrypy.log
log.access_file = ''
log.error_file = ''
# Max size of 512KB
maxBytes = getattr(log, "rot_maxBytes", 524288)
# cherrypy.log cherrypy.log.1 cherrypy.log.2
backupCount = getattr(log, "rot_backupCount", 3)
# Make a new RotatingFileHandler for the error log.
fname = getattr(log, "rot_error_file", log_path)
h = log_handler(fname, 'a', maxBytes, backupCount)
h.setLevel(logging.DEBUG)
h.setFormatter(cherrypy._cplogging.logfmt)
log.error_log.addHandler(h)
#------------------------------------------------------------------------------
def commandline_handler(frozen=True):
""" Split win32-service commands are true parameters
Returns:
service, sab_opts, serv_opts, upload_nzbs
"""
service = ''
sab_opts = []
serv_inst = False
serv_opts = [os.path.normpath(os.path.abspath(sys.argv[0]))]
upload_nzbs = []
# OSX binary: get rid of the weird -psn_0_123456 parameter
for arg in sys.argv:
if arg.startswith('-psn_'):
sys.argv.remove(arg)
break
# Ugly hack to remove the extra "SABnzbd*" parameter the Windows binary
# gets when it's restarted
if len(sys.argv) > 1 and \
'sabnzbd' in sys.argv[1].lower() and \
not sys.argv[1].startswith('-'):
slice = 2
else:
slice = 1
# Prepend options from env-variable to options
info = os.environ.get('SABnzbd', '').split()
info.extend(sys.argv[slice:])
try:
opts, args = getopt.getopt(info, "phdvncw:l:s:f:t:b:2:",
['pause', 'help', 'daemon', 'nobrowser', 'clean', 'logging=',
'weblogging=', 'server=', 'templates',
'template2', 'browser=', 'config-file=', 'force',
'version', 'https=', 'autorestarted', 'repair', 'repair-all',
'log-all', 'no-login', 'pid=', 'new', 'sessions',
# Below Win32 Service options
'password=', 'username=', 'startup=', 'perfmonini=', 'perfmondll=',
'interactive', 'wait=',
])
except getopt.GetoptError:
print_help()
exit_sab(2)
# Check for Win32 service commands
if args and args[0] in ('install', 'update', 'remove', 'start', 'stop', 'restart', 'debug'):
service = args[0]
serv_opts.extend(args)
if not service:
# Get and remove any NZB file names
for entry in args:
if get_ext(entry) in ('.nzb', '.zip','.rar', '.gz'):
upload_nzbs.append(os.path.abspath(entry))
for opt, arg in opts:
if opt in ('password','username','startup','perfmonini', 'perfmondll', 'interactive', 'wait'):
# Service option, just collect
if service:
serv_opts.append(opt)
if arg:
serv_opts.append(arg)
else:
if opt == '-f':
arg = os.path.normpath(os.path.abspath(arg))
sab_opts.append((opt, arg))
return service, sab_opts, serv_opts, upload_nzbs
def get_f_option(opts):
""" Return value of the -f option """
for opt, arg in opts:
if opt == '-f':
return arg
else:
return None
#------------------------------------------------------------------------------
def main():
global LOG_FLAG
import sabnzbd # Due to ApplePython bug
autobrowser = None
autorestarted = False
sabnzbd.MY_FULLNAME = sys.argv[0]
sabnzbd.MY_NAME = os.path.basename(sabnzbd.MY_FULLNAME)
fork = False
pause = False
inifile = None
cherryhost = None
cherryport = None
https_port = None
cherrypylogging = None
clean_up = False
logging_level = None
web_dir = None
web_dir2 = None
vista_plus = False
vista64 = False
force_web = False
repair = 0
api_url = None
no_login = False
re_argv = [sys.argv[0]]
pid_path = None
new_instance = False
force_sessions = False
service, sab_opts, serv_opts, upload_nzbs = commandline_handler()
for opt, arg in sab_opts:
if opt == '--servicecall':
sabnzbd.MY_FULLNAME = arg
elif opt in ('-d', '--daemon'):
if not sabnzbd.WIN32:
fork = True
autobrowser = False
sabnzbd.DAEMON = True
re_argv.append(opt)
elif opt in ('-f', '--config-file'):
inifile = arg
re_argv.append(opt)
re_argv.append(arg)
elif opt in ('-h', '--help'):
print_help()
exit_sab(0)
elif opt in ('-t', '--templates'):
web_dir = arg
elif opt in ('-2', '--template2'):
web_dir2 = arg
elif opt in ('-s', '--server'):
(cherryhost, cherryport) = split_host(arg)
elif opt in ('-n', '--nobrowser'):
autobrowser = False
elif opt in ('-b', '--browser'):
try:
autobrowser = bool(int(arg))
except:
autobrowser = True
elif opt in ('--autorestarted'):
autorestarted = True
elif opt in ('-c', '--clean'):
clean_up = True
elif opt in ('-w', '--weblogging'):
try:
cherrypylogging = int(arg)
except:
cherrypylogging = -1
if cherrypylogging < 0 or cherrypylogging > 2:
print_help()
exit_sab(1)
elif opt in ('-l', '--logging'):
try:
logging_level = int(arg)
except:
logging_level = -1
if logging_level < 0 or logging_level > 2:
print_help()
exit_sab(1)
elif opt in ('-v', '--version'):
print_version()
exit_sab(0)
elif opt in ('-p', '--pause'):
pause = True
elif opt in ('--force',):
force_web = True
re_argv.append(opt)
elif opt in ('--https',):
https_port = int(arg)
re_argv.append(opt)
re_argv.append(arg)
elif opt in ('--repair',):
repair = 1
pause = True
elif opt in ('--repair-all',):
repair = 2
pause = True
elif opt in ('--log-all',):
sabnzbd.LOG_ALL = True
elif opt in ('--no-login',):
no_login = True
elif opt in ('--pid',):
pid_path = arg
re_argv.append(opt)
re_argv.append(arg)
elif opt in ('--new',):
new_instance = True
elif opt in ('--sessions',):
force_sessions = True
sabnzbd.MY_FULLNAME = os.path.normpath(os.path.abspath(sabnzbd.MY_FULLNAME))
sabnzbd.MY_NAME = os.path.basename(sabnzbd.MY_FULLNAME)
sabnzbd.DIR_PROG = os.path.dirname(sabnzbd.MY_FULLNAME)
sabnzbd.DIR_INTERFACES = real_path(sabnzbd.DIR_PROG, DEF_INTERFACES)
sabnzbd.DIR_LANGUAGE = real_path(sabnzbd.DIR_PROG, DEF_LANGUAGE)
org_dir = os.getcwd()
if getattr(sys, 'frozen', None) == 'macosx_app':
# Correct path if frozen with py2app (OSX)
sabnzbd.MY_FULLNAME = sabnzbd.MY_FULLNAME.replace("/Resources/SABnzbd.py","/MacOS/SABnzbd")
# Need console logging for SABnzbd.py and SABnzbd-console.exe
consoleLogging = (not hasattr(sys, "frozen")) or (sabnzbd.MY_NAME.lower().find('-console') > 0)
consoleLogging = consoleLogging and not sabnzbd.DAEMON
# No console logging needed for OSX app
noConsoleLoggingOSX = (sabnzbd.DIR_PROG.find('.app/Contents/Resources') > 0)
if noConsoleLoggingOSX:
consoleLogging = 1
LOGLEVELS = (logging.WARNING, logging.INFO, logging.DEBUG)
# Setup primary logging to prevent default console logging
gui_log = guiHandler(MAX_WARNINGS)
gui_log.setLevel(logging.WARNING)
format_gui = '%(asctime)s\n%(levelname)s\n%(message)s'
gui_log.setFormatter(logging.Formatter(format_gui))
sabnzbd.GUIHANDLER = gui_log
# Create logger
logger = logging.getLogger('')
logger.setLevel(logging.WARNING)
logger.addHandler(gui_log)
# Detect Windows variant
if sabnzbd.WIN32:
vista_plus, vista64 = windows_variant()
sabnzbd.WIN64 = vista64
if not SQLITE_DLL:
panic_sqlite(sabnzbd.MY_FULLNAME)
exit_sab(2)
if inifile:
# INI file given, simplest case
inifile = evaluate_inipath(inifile)
else:
# No ini file given, need profile data
GetProfileInfo(vista_plus)
# Find out where INI file is
inifile = os.path.abspath(sabnzbd.DIR_PROG + '/' + DEF_INI_FILE)
if not os.path.exists(inifile):
inifile = os.path.abspath(sabnzbd.DIR_LCLDATA + '/' + DEF_INI_FILE)
if sabnzbd.DARWIN:
copy_old_files(sabnzbd.DIR_LCLDATA)
# If INI file at non-std location, then use program dir as $HOME
if sabnzbd.DIR_LCLDATA != os.path.dirname(inifile):
sabnzbd.DIR_HOME = os.path.dirname(inifile)
# All system data dirs are relative to the place we found the INI file
sabnzbd.DIR_LCLDATA = os.path.dirname(inifile)
if not os.path.exists(inifile) and not os.path.exists(sabnzbd.DIR_LCLDATA):
try:
os.makedirs(sabnzbd.DIR_LCLDATA)
except IOError: