def download(link, outdir='<STR_LIT:.>', chunk_size=<NUM_LIT>):
url = None<EOL>fh = None<EOL>eta = '<STR_LIT>'<EOL>bytes_so_far = <NUM_LIT:0><EOL>filename = filename_from_url(link) or "<STR_LIT:.>"<EOL>cj = cjar.CookieJar()<EOL>(fd_tmp, tmpfile) = tempfile.mkstemp(<EOL>"<STR_LIT>", prefix=filename + "<STR_LIT:.>", dir=outdir)<EOL>os.close(fd_tmp)<EOL>os.unlink(tmpfile)<EOL>try:<EOL><INDENT>opener = ulib.build_opener(ulib.HTTPCookieProcessor(cj))<EOL>url = opener.open(link)<EOL>fh = open(tmpfile, mode='<STR_LIT:wb>')<EOL>headers = url.info()<EOL>try:<EOL><INDENT>total_size = int(headers['<STR_LIT>'])<EOL><DEDENT>except (ValueError, KeyError, TypeError):<EOL><INDENT>total_size = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>md5_header = headers['<STR_LIT>']<EOL><DEDENT>except (ValueError, KeyError, TypeError):<EOL><INDENT>md5_header = None<EOL><DEDENT>if total_size != '<STR_LIT>':<EOL><INDENT>if CONSOLE_WIDTH > <NUM_LIT>:<EOL><INDENT>reporthook = report_bar<EOL><DEDENT>else:<EOL><INDENT>reporthook = report_onlysize<EOL><DEDENT><DEDENT>else:<EOL><INDENT>reporthook = report_unknown<EOL><DEDENT>time_register = time()<EOL>speed = <NUM_LIT:0.0><EOL>speed_list = []<EOL>bytes_register = <NUM_LIT:0.0><EOL>eta = '<STR_LIT>'<EOL>while True:<EOL><INDENT>chunk = url.read(chunk_size)<EOL>if time() - time_register > <NUM_LIT:0.5>:<EOL><INDENT>speed = (bytes_so_far - bytes_register) /(time() - time_register)<EOL>speed_list.append(speed)<EOL>time_register = time()<EOL>bytes_register = bytes_so_far<EOL>if total_size != '<STR_LIT>' and len(speed_list) == <NUM_LIT:3>:<EOL><INDENT>speed_mean = sum(speed_list) / <NUM_LIT:3><EOL>eta_sec = int((total_size - bytes_so_far) / speed_mean)<EOL>eta = str(datetime.timedelta(seconds=eta_sec))<EOL>speed_list = []<EOL><DEDENT><DEDENT>bytes_so_far += len(chunk)<EOL>if not chunk:<EOL><INDENT>sys.stdout.write('<STR_LIT:\n>')<EOL>break<EOL><DEDENT>fh.write(chunk)<EOL>reporthook(bytes_so_far, total_size, speed, eta)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>'.format(os.path.abspath(tmpfile)))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>finally:<EOL><INDENT>if url:<EOL><INDENT>url.close()<EOL><DEDENT>if fh:<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT>filenamealt = filename_from_headers(headers)<EOL>if filenamealt:<EOL><INDENT>filename = filenamealt<EOL><DEDENT>if os.path.exists(os.path.join(outdir, filename)):<EOL><INDENT>filename = filename_fix_existing(filename, outdir)<EOL><DEDENT>filename = os.path.join(outdir, filename)<EOL>shutil.move(tmpfile, filename)<EOL>if total_size != '<STR_LIT>' and total_size != bytes_so_far:<EOL><INDENT>print(<EOL>'<STR_LIT>')<EOL><DEDENT>if md5_header:<EOL><INDENT>print('<STR_LIT>')<EOL>if md5_header == md5sum(filename):<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT><DEDENT>return filename<EOL>
This is the Main function, which downloads a given link
and saves on outdir (default = current directory)