# -*- coding: utf-8 -*-
import sys, os
import urllib, urllib2
from ftplib import FTP
temp_dir = "d:\\"


def ru(x):return unicode(x,'utf8', 'ignore')

def getURL(url,Referer = 'http://emulations.ru/'):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Opera/10.60 (X11; openSUSE 11.3/Linux i686; U; ru) Presto/2.6.30 Version/10.60')
	req.add_header('Accept', 'text/html, application/xml, application/xhtml+xml, */*')
	req.add_header('Accept-Language', 'ru,en;q=0.9')
	req.add_header('Referer', Referer)
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link

def mfindal(http, ss, es):
	L=[]
	while http.find(es)>0:
		s=http.find(ss)
		#sn=http[s:]
		e=http.find(es)
		i=http[s:e]
		L.append(i)
		http=http[e+2:]
	return L

def mfind(t,s,e):
	r=t[t.find(s)+len(s):]
	r2=r[:r.find(e)]
	return r2

def CRC32(buf):
		import binascii
		buf = (binascii.crc32(buf) & 0xFFFFFFFF)
		return str("%08X" % buf)

def save_inf(s):
	p = os.path.join(ru(temp_dir),"temp.txt")
	f = open(p, "w")
	f.write(s)
	f.close()
	return p

def upload(ftp, path, ftp_path):
	with open(path, 'rb') as fobj:
		ftp.storbinary('STOR ' + ftp_path, fobj, 1024)


def get_path(id):
	pref='0'*(6-len(id))
	id=pref+id
	#print len(id[:-4])
	if len(id[:-4])==3:s1=chr(int(id[:-5])+87)+id[-5:-4]
	else:s1=id[:-4]
	s=[s1,id[-4:-2],id[-2:]]
	#print s
	return s

def make_id(ftp, id):
	s='/kinodb'
	i=get_path(id)
	for c in [i[0], i[1]]:
		s+='/'+c
		try:ftp.mkd(s)
		except: pass
	ret=s+'/'+i[2]
	print ret
	return ret

def verifid_id(ftp, id):
	s='/kinodb'
	for c in get_path(id):
		s+='/'+c
	try:size=ftp.size(s+'.nfo')
	except: size=0
	#print size
	return size

def get_request(q):
	id=CRC32(q)
	HUP=get_host('request')
	HOST=HUP['HOST']
	url='http://'+HOST+'/request/'+id[:1]+'/'+id[1:]+'.txt'
	try:request=eval(getURL(url))
	except: request={}
	return request

def save_request(q, r):
	print 'ADD request: '+q
	HUP=get_host('request')
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	ftp = FTP(HOST)
	ftp.login(USER, PASS)

	id=CRC32(q)
	try:ftp.mkd('/request/'+id[:1])
	except: pass
	path = save_inf(repr(r))
	upload(ftp, path, '/request/'+id[:1]+'/'+id[1:]+'.txt')
	ftp.quit()


def add(info):
	return add_compression_info(info)
	'''
	id=info['id']
	HUP=get_host(id)
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	ftp = FTP(HOST)
	ftp.login(USER, PASS)
	print 'ADD KinoDB: '+id
	if verifid_id(ftp, id) == 0:
		dir=make_id(ftp, id)
		path = save_inf(repr(info))
		upload(ftp, path, dir+'.nfo')
	ftp.quit()
	'''


def add2(info):
	id=info['id']
	HUP=get_host(id)
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	ftp = FTP(HOST)
	ftp.login(USER, PASS)
	print 'ADD KinoDB: '+id
	if verifid_id(ftp, id) == 0:
		dir=make_id(ftp, id)
		path = save_inf(repr(info))
		upload(ftp, path, dir+'.info')
	ftp.quit()

def update(info):
	return add_compression_info(info)
	id=info['id']
	HUP=get_host(id)
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	ftp = FTP(HOST)
	ftp.login(USER, PASS)
	print 'UPD KinoDB: '+id
	if verifid_id(ftp, id) != 0:
		dir=make_id(ftp, id)
		path = save_inf(repr(info))
		upload(ftp, path, dir+'.nfo')
	ftp.quit()

def get_info(id):
	return get_compression_info(id)
	c=get_path(id)
	HOST=get_host(id)['HOST']
	url='http://'+HOST+'/kinodb/'+c[0]+'/'+c[1]+'/'+c[2]+'.nfo'
	#print url
	info=eval(getURL(url))
	return info

def get_host(id):
	if id=='request': return {'HOST':'kinodb.my1.ru',    'USER':'5kinodb',   'PASS':'19111980'}
	else:             return {'HOST':'td-soft.narod.ru', 'USER':'otd-soft',  'PASS':'19111980'}
	#if          int(id)>= 900000: return {'HOST':'1kinodb2.my1.ru',  'USER':'15kinodb2',  'PASS':'19980'}
	#elif 900000>int(id)>= 500000: return {'HOST':'1gbaroms.my1.ru',  'USER':'15gbaroms',  'PASS':'19980'}
	#elif 500000>int(id)>= 300000: return {'HOST':'1roms.my1.ru',     'USER':'15roms',     'PASS':'19980'}
	#elif 300000>int(id)>= 100000: return {'HOST':'1segaroms.my1.ru', 'USER':'15segaroms', 'PASS':'19980'}
	#else:						  return {'HOST':'1kinodb.my1.ru',   'USER':'15kinodb',   'PASS':'19980'}


#add({"id":"123"})
'''
for i1 in range(0, 100):
	for i2 in range(0, 100):
		name=str(i1*100+i2)+'xx'
		inf={}
		for i3 in range(0, 100):
			id=i1*10000+i2*100+i3
			print id
			try:
				info=get_info(str(id))
				inf[str(id)] = info
			except: pass
		print inf
		inf['id']=name
		add2(inf)
'''

def make_compression_info(id):
	#print 'make_compression_info'
	c=get_path(id)
	HUP=get_host(id)
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	cinfo={}
	for i in range(0, 100):
		if i<10: sid='0'+str(i)
		else:    sid=str(i)
		curl='http://'+HOST+'/kinodb/'+c[0]+'/'+c[1]+'/'+sid+'.nfo'
		#print curl
		try:    i_id=int(c[0]+c[1]+sid)
		except: i_id=c[0]+c[1]+sid
		try:cinfo[str(i_id)] = eval(getURL(curl))
		except: pass
	ftp = FTP(HOST)
	ftp.login(USER, PASS)
	print 'ADDcomp KinoDB: '+id
	
	try:ftp.mkd('/kinodb/'+c[0])
	except: pass
	
	path = save_inf(repr(cinfo))
	url='/kinodb/'+c[0]+'/'+c[1]+'.info'#'http://'+HOST+
	upload(ftp, path, url)
	ftp.quit()
	return cinfo

def get_compression_info(id):
	#print get_compression_info
	c=get_path(id)
	HOST=get_host(id)['HOST']
	url='http://'+HOST+'/kinodb/'+c[0]+'/'+c[1]+'.info'
	#print url
	try: 
		cinfo=eval(getURL(url))
		#print 'cinfo найден'
	except: 
		cinfo=make_compression_info(id)
		#print 'cinfo создан'
	info=cinfo[id]
	return info

def add_compression_info(nfo):
	id=nfo['id']
	c=get_path(id)
	HUP=get_host(id)
	HOST=HUP['HOST']
	USER=HUP['USER']
	PASS=HUP['PASS']
	url='http://'+HOST+'/kinodb/'+c[0]+'/'+c[1]+'.info'
	try: cinfo=eval(getURL(url))
	except: cinfo=make_compression_info(id)
	cinfo[id]=nfo
	
	ftp = FTP(HOST)
	ftp.login(USER, PASS)
	#print 'SAVEcomp KinoDB: '+id
	#dir=make_id(ftp, id)
	path = save_inf(repr(cinfo))
	ftp_url='/kinodb/'+c[0]+'/'+c[1]+'.info'
	upload(ftp, path, ftp_url)
	ftp.quit()

#print get_compression_info('445')
#print get_path('1111911')
#add_compression_info({'id':'1211911'})