2007-08-20, 20:45
I need to learn how to script lol, i really want to port NZBPlayer to the XBOX.
import os,sys,traceback,string
from re import findall as reFindall, compile as reCompile,re.DOTALL as reDotAll, search as reSearch
import pickle,nntplib
############################################
## Change These to match your news Server ##
############################################
NEWZ_SERVER = <<CHANGE TO ADDRESS OF YOUR NEWS SERVER>>
NEWZ_USER =<<CHANGE TO YOUR USERNAME ON SERVER>>
NEWZ_PASS =<<CHANGE TO YOUR PASSWORD ON SERVER>>
NZB_FILE =<<NAME OF NZB FILE TO PROCESS THATS IN THIS DIRECTORY>>
############################################
HOME_DIR = os.getcwd().replace(";","")+"\\"
yenc42 = "".join([chr((i - 42) & 255) for i in range(256)])
yenc64 = "".join([chr((i - 64) & 255) for i in range(256)])
REALNAME = ''
def ParseNzb(data) :
try :
## Get start/end points ##
Exp = reCompile('(<file.*?</file>)',reDotAll)
Tar = reFindall(Exp,data)
FileData = {}
RARTYPE = None
for FTag in Tar :
Exp = reCompile('<file.*?subject=\"(.*?)\">')
Subject = reSearch('subject=\".*?\">',FTag).span()
Fields = str(FTag[Subject[0]+9:Subject[1]-2]).rsplit(' - ')
FileNm = reSub('"','',Fields[-1])
FileNm = reSub('"','',FileNm)
FileNm = reSub('"','',FileNm)
Chk1 = reSearch(' yEnc| \(',FileNm,reIgnoreCase)
if ( Chk1 ) :
FileNm = FileNm[:Chk1.start()]
Spaces = FileNm.rsplit(' ')
FileNm = Spaces[-1]
FileNm = FileNm.strip()
## Now see what type of file it is.
Record = -1
Type_1 = reSearch('part\d+\.rar$',FileNm)
Type_2 = reSearch('\.r\d+$',FileNm)
if ( Type_1 ) or ( Type_2 ) :
RecPos = reSearch('\d+$',FileNm).span()
Record = int(FileNm[RecPos[0]:RecPos[1]])
if (Type_2) : Record += 2
elif ( reSearch('.rar$',FileNm) ) :
Record = 1
if Record == -1 :
print 'Ignored -- '+ str(FileNm)
elif FileData.has_key(Record) :
print 'Duplicates -- Cannot Sort This File..'
raise Exception
else :
##print 'Processed --'+ str(FileNm) +' - In slot: '+ str(Record)
FileData[Record] = FTag
return FileData
except :
print '--ParseNzb Fail--'
traceback.print_exc()
return None
def WriteObj(Var,myFile):
try :
toFile = open(HOME_DIR + myFile,'wb')
pickle.dump( Var,toFile )
toFile.close()
return True
except :
print '--WriteObj Fail--'
traceback.print_exc()
return False
def ReadObj(myFile):
try :
toFile = open(HOME_DIR + myFile,'rb')
data = pickle.load(toFile)
toFile.close()
return data
except :
print '--ReadObj Fail--'
traceback.print_exc()
return None
def SortNzb(Fn) :
try :
if Fn.endswith('.nzb') :
f = open(HOME_DIR + Fn,'r')
data = f.read()
f.close
Result = ParseNzb(data)
if len(Result) == 0 or Result == None :
print 'Unable to Sort this file..'
else :
KeySort = Result.keys()
KeySort.sort()
## Now setup Regexp for GROUP and SEGMENT data.
GrpExp = reCompile('<group>(.*?)</group>')
SegExp = reCompile('<segment.*?number=[\"|\'](\d+)[\"|\']>(.*?)</segment>')
for Key,Segment in Result.items() :
Result[Key] = {}
Tar = reFindall(SegExp,Segment)
Grp = reFindall(GrpExp,Segment)
Result[Key]['Group'] = Grp
for Add in Tar :
Result[Key][int(Add[0])] = Add[1]
## Write the whole Object out to a file.close
if ( WriteObj(Result,'stream.obj') ) :
return True
return False
except :
traceback.print_exc()
return False
def YencDecode(FileIn):
try :
global REALNAME
Buffer = []
for line in FileIn :
if line == '' :
print '--Ignore : '+ str(line) +' --'
elif line.startswith('=y') :
HasName = reSearch('name=',line)
if ( HasName ) :
REALNAME = line[HasName.end():]
else :
print '--Ignore : '+ str(line) +' --'
else :
## This is real data
if line[-2:] == "\r\n":
line = line[:-2]
elif line[-1:] in "\r\n":
line = line[:-1]
splitData = line.split("=")
Buffer.append(splitData[0].translate(yenc42))
for data in splitData[1:]:
Buffer.append(data[0].translate(yenc64).translate(yenc42))
Buffer.append(data[1:].translate(yenc42))
return Buffer
except :
traceback.print_exc()
return None
def CheckPost(SortKeys,Type) :
try :
############################################################
## Types are 'CHECK' or 'DOWNLOAD' ##
## CHECK will stat all of the files to ensure they exist ##
## DOWNLOAD will download the file. ##
############################################################
DUMP = []
Newz=nntplib.NNTP(NEWZ_SERVER,119,NEWZ_USER,NEWZ_PASS)
for i in SortKeys :
print '---KEY--- :'+ str(i) +' --Group:'+ str(PostId[i]['Group'])
FILEARRAY = []
REALNAME = ''
## Goto Group
NullData = Newz.group(PostId[i]['Group'][0])
if len(NullData) == 0 :
print 'Group :'+ str(PostId[i]['Group'][0]) +' Doesnt exist'
## Now loop through the keys
SubKeys = PostId[i].keys()
SubKeys.sort()
TmpName = ''
FullChunk = []
for j in SubKeys :
if j != 'Group' :
## Perform an Action back on the Type passed.
if Type == 'CHECK' :
print '--Statting-- :'+ str(PostId[i][j])
Result = Newz.stat('<' + str(PostId[i][j]) +'>')
if len(Result) > 0 : return None,None
elif Type == 'DOWNLOAD' :
print '--Getting-- :'+ str(PostId[i][j])
Result = Newz.body('<' + str(PostId[i][j]) +'>')
TmpName = 'tmp-'+ str(i) +'-'+ str(j) +'.tmp'
FullChunk.append(Result)
if not ( DumpChunk(FullChunk) ) :
print '--Failed to Dump Chunk--'
raise Exception
raise Exception
except :
traceback.print_exc()
return None
def DumpChunk(Dump) :
try :
f = open(HOME_DIR + 'Dummy.rar','wb')
for Chunk in Dump :
Data = YencDecode(Chunk[3])
f.write(''.join(Data))
f.close()
os.rename(HOME_DIR + 'Dummy.rar',HOME_DIR + REALNAME)
return True
except :
traceback.print_exc()
return False
print '--Starting--'
if ( SortNzb(NZB_FILE) ) :
print '--NZB File sorted and saved as stream.obj--'
## File was sorted ok and written out to stream.obj ##
PostId = ReadObj('stream.obj')
if PostId != None :
print '--Read stream.obj from file into PostId dictionary has worked--'
SortKeys = PostId.keys()
SortKeys.sort()
if ( CheckPost(SortKeys,'CHECK') ) != None :
print '--All Files STAT OK **We can proceed** Yippee--'
Dump = CheckPost(SortKeys,'DOWNLOAD')
else :
print '--All files DID NOT STAT ok on the news server--'
else :
print '--Failed to read stream.obj into PostId--'