#!usr/bin/env python
#-*- coding: utf-8 -*-
 
import os
import urllib2
import urllib
import cookielib
import xml.etree.elementtree as et
 
#--------------------------------
# login in www.***.com.cn
def chinabiddinglogin(url, username, password):
    # enable cookie support for urllib2
    cookiejar=cookielib.cookiejar()
    urlopener=urllib2.build_opener(urllib2.httpcookieprocessor(cookiejar))
    urllib2.install_opener(urlopener)
     
    urlopener.addheaders.append(('referer', 'http://www.chinabidding.com.cn/zbw/login/login.jsp'))
    urlopener.addheaders.append(('accept-language', 'zh-cn'))
    urlopener.addheaders.append(('host', 'www.chinabidding.com.cn'))
    urlopener.addheaders.append(('user-agent', 'mozilla/5.0 (compatible; mise 9.0; windows nt 6.1); trident/5.0'))
    urlopener.addheaders.append(('connection', 'keep-alive'))
 
    print 'xxx login......'
 
    imgurl=r'http://www.*****.com.cn/zbw/login/image.jsp'
    downloadfile(imgurl, urlopener)
    authcode=raw_input('please enter the authcode:')
    #authcode=verifyingcoderecognization(r"http://192.168.0.106/images/code.jpg")
 
 
    # send login/password to the site and get the session cookie
    values={'login_id':username, 'opl':'op_login', 'login_passwd':password, 'login_check':authcode}
    urlcontent=urlopener.open(urllib2.request(url, urllib.urlencode(values)))
    page=urlcontent.read(500000)
 
 
    # make sure we are logged in, check the returned page content
    if page.find('login.jsp')!=-1:
        print 'login failed with username=%s, password=%s and authcode=%s' 
                % (username, password, authcode)
        return false
    else:
        print 'login succeeded!'
        return true
 
#------------------
# download from fileurl then save to filetosave
# note: the fileurl must be a valid file
def downloadfile(fileurl, urlopener):
    isdownok=false
 
 
    try:
        if fileurl:
            outfile=open(r'/var/www/images/code.jpg', 'w')
            outfile.write(urlopener.open(urllib2.request(fileurl)).read())
            outfile.close()
 
 
            isdownok=true
        else:
            print 'error: fileurl is null!'
    except:
        isdownok=false
 
 
    return isdownok
 
#----------------
# verifying code recoginization
def verifyingcoderecognization(imgurl):
    url=r'http://192.168.0.119:800/api?'
    user='admin'
    pwd='admin'
    model='ocr'
    ocrfile='cbi'
 
    values={'user':user, 'pwd':pwd, 'model':model, 'ocrfile':ocrfile, 'imgurl':imgurl}
    data=urllib.urlencode(values)
 
    try:
        url+=data
        urlcontent=urllib2.urlopen(url)
    except ioerror:
        print '***error: invalid url (%s)' % url
 
    page=urlcontent.read(500000)
 
    # parse the xml data and get the verifying code
    root=et.fromstring(page)
    node_find=root.find('addfield')
    authcode=node_find.attrib['data']
 
    return authcode
 
#----------------
# read users from configure file
def readusersfromfile(filename):
    users={}
    for eachline in open(filename, 'r'):
        info=[w for w in eachline.strip().split()]
        if len(info)==2:
            users[info[0]]=info[1]
    return users
 
#----------------
def main():
    login_page=r'http://www.***.com.cnlogin/login.jsp'
    download_page=r'http://www.***.com.cn***/***?record_id='
 
    start_id=8593330
    end_id=8595000
 
    now_id=start_id
    users=readusersfromfile('users.conf')
    while true:
        for key in users:
            if chinabiddinglogin(login_page, key, users[key]):
                for i in range(3):
                    pageurl=download_page+'%d' % now_id
                    urlcontent=urllib2.urlopen(pageurl)
 
 
                    filepath='./download/%s.html' % now_id
                    f=open(filepath, 'w')
                    f.write(urlcontent.read(500000))
                    f.close()
 
                    now_id+=1
            else:
                
continue
#------------------------------
if __name__=='__main__':
    main()