import requests
from qiniu import Auth
from qiniu import BucketManager

access_key = "qpnoR6IOay_5u_3THVqBkyKMjCNdmF_evwGOq_qG"
secret_key = "QqLeawyN92Tuxc9484PbBq2GrVCxIKOegqUvIKhY"
bucket_name = "jsjds"
prefix = None
limit = 2
delimiter = None
marker = None


def getDomainByBucket(auth,bucketName):
    connector = "/v6/domain/list?tbl={0}".format(bucketName)
    url = "http://api.qiniu.com" + connector
    try:
        accessToken = auth.token_of_request(connector)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "QBox " + accessToken
        }
        resp = requests.get(url, headers=headers)
        resp.raise_for_status()
        if(resp.status_code == requests.codes.ok):
            return list(resp.json())

    except Exception as e:
        print "Exception"+e

def main():
    q = Auth(access_key,secret_key)
    bucket = BucketManager(q)

    domain_list = getDomainByBucket(q,bucket_name)
    oneDomain = domain_list[0]

    marker = None
    eof = False
    while eof is False:
        print "##################"
        ret,eof,info = bucket.list(bucket_name,prefix,marker,limit)
        marker = ret.get('marker',None)
        for item in ret.get('items'):
            key = item.get("key")
            base_url = "http://%s/%s"%(oneDomain,key)
            private_url = q.private_download_url(base_url,expires=3600)
            print private_url
            r =requests.get(private_url)
            if r.status_code == 200:
                open(key,"wb").write(r.content)


if __name__=="__main__":
    main()
