/*	get final download link
965739
function getDownloadlink(map,title){
	var url = decodeURIComponent(map.url),
		sig = (map.s || map.sig)? '&signature='+(map.s || map.sig) : '',
		tit = '&title='+title;
	return url+sig+tit;
}
279764
function getQueuedLink(callback, seconds) {
  var dateField = 'queued.lastAttempt';
  seconds = seconds || DELAY_SECONDS;
  // function to process the link
  var process = function(err, res) {
    var queuedLink = null;
    if (res && res.hits && res.hits.hits.length) {
      var hit = res.hits.hits[0]._source;
      var queued = hit.queued;
      queuedLink = { uri: hit.uri, queued: queued, total: res.hits.total };
      queued.lastAttempt = new Date().toISOString();
      queued.attempts = queued.attempts + 1;
      hit.queued = queued;

      // update accesses
      contentLib.indexContentItem(hit, {state: 'queued', member: queued.member}, function(err, res) {
        // process the link
        if (!err) {
          callback(null, queuedLink);
        } else {
          utils.passingError(err);
        }
      });
    } else {
      callback(err, null);
    }
  };

 // call query with the function
  GLOBAL.svc.indexer.formQuery({query: {
    terms: dateField + ':<now-' + seconds + 's AND state:queued AND queued.attempts:<' + MAX_ATTEMPTS
  }, sort: dateField, sourceFields : ['uri', 'title', 'queued.*'], size : 1 }, process);
}
1120103
static function FileGet($url, $data = "", $verify_cert = false, $timeout = 30)
	{
		$qs = HttpRequest::ArrayToQueryString($data);
		$full_url = $url . ($qs ? "?" . $qs : "");
		return file_get_contents( $full_url );
	}
709703
function download(downloadUrl, filename, callback, ondata) {
    var url = require("url").parse(downloadUrl);
    var out = require("fs").createWriteStream(filename, { flags: 'w', encoding: null, mode: 0666 });
    var bytes = 0, total = -1;
    var options = {
        "hostname" : url["host"],
        "method" : "GET",
        "path" : url["path"],
        "agent" : false
    }

    // Reconfigure request options if an HTTP proxy setting exists
    if (process.env.http_proxy) {
        var http_proxy = require("url").parse(process.env.http_proxy);
        options["hostname"] = http_proxy["hostname"];
        options["port"] = http_proxy["port"];
        options["path"] = url["href"];
        options["headers"] = {
            "Host" : url["host"]
        };
    }

    var req = require(path.join(__dirname, "..", "lib", "follow-redirects.js")).http.request(options,
                                                                                             function(res) {
        if (res.headers["content-length"]) {
            total = parseInt(res.headers["content-length"], 10);
        }
        if (res.statusCode != 200) {
            res.setEncoding(null);
            callback(new Error("Download failed: HTTP status code "+res.statusCode), -1);
            return;
        }
        res.on("data", function(chunk) {
            bytes += chunk.length;
            if (ondata) ondata(chunk.length, total);
            out.write(chunk);
        });

        res.on("end", function() {
            callback(null, bytes);
        });
    });
    req.on("error", function(e) {
        callback(e, -1);
    });
    req.end();
}
934169
function download(url) {
  return request('GET', url).then(function (res) {
    var out = {
      url: url,
      body: res.body,
      statusCode: res.statusCode,
      headers: res.headers,
      dependencies: []
    };

    try {
      if (out.statusCode === 302) {
        out.dependencies = [out.headers.location];
      } else if (!out.headers['content-type']) {
        out.dependencies = [];
      } else if (out.headers['content-type'].indexOf('text/html') !== -1) {
        out.dependencies = htmldeps(out.body.toString());
      } else if (out.headers['content-type'].indexOf('text/css') !== -1) {
        out.dependencies = cssdeps(out.body.toString());
      } else {
        out.dependencies = [];
      }
    } catch (ex) {
      ex.message = 'Error parsing deps for "' + url + '": ' + ex.message;
      throw ex;
    }
    return out;
  });
}
188510
def get_download_link(cookie, tokens, path):
    '''
    '''
    metas = get_metas(cookie, tokens, path)
    if (not metas or metas.get('errno', -1) != 0 or
            'info' not in metas or len(metas['info']) != 1):
        logger.error('pcs.get_download_link(): %s' % metas)
        return None
    dlink = metas['info'][0]['dlink']
    url = '{0}&cflg={1}'.format(dlink, cookie.get('cflag').value)
    req = net.urlopen_without_redirect(url, headers={
        'Cookie': cookie.sub_output('BAIDUID', 'BDUSS', 'cflag'),
        'Accept': const.ACCEPT_HTML,
    })
    if not req:
        return url
    else:
        return req.getheader('Location', url)
36486
function downloadRepo(config, tmpFolder, callback) {

  console.log('Downloading repo...'.magenta);

  // Keep track if the request fails to prevent the continuation of the install
  var requestFailed = false;

  var repoUrl = 'http://server.webhook.com/';

  if(config.server) {
    if(config.server.indexOf('http://') !== 0) {
      config.server = config.server += 'http://';
    }

    if(config.server.indexOf(config.server.length - 1) !== '/') {
      config.server += '/';
    }

    repoUrl = config.server;
  }

  var repoRequest = request(repoUrl + 'download/?site=' + config.siteName + '&token=' + config.siteToken);

  repoRequest
    .on('response', function (response) {
      // If we fail, set it as failing and remove zip file
      if (response.statusCode !== 200) {
        requestFailed = true;
        fs.unlinkSync('repo.zip');
        callback(true);
      }
    })
    .pipe(fs.createWriteStream('repo.zip'))
    .on('close', function () {
      if (requestFailed) return;

      console.log('Extracting Files...'.magenta);
      // Unzip into temporary file
      var zip = new Zip('repo.zip');
      zip.extractAllTo(tmpFolder);
      fs.unlinkSync('repo.zip');
      callback(null, tmpFolder + '/' + fs.readdirSync(tmpFolder)[0]);
    });
}
647470
String prevLink() {
    if (currentOffset == 0 || currentLimit == 0) {
      return null;
    }

    return urlWithUpdatedPagination(Math.max(0, currentOffset - currentLimit), currentLimit);
  }
149585
public com.google.api.ads.adwords.axis.v201809.cm.UrlList getFinalUrls() {
        return finalUrls;
    }
890790
protected function get_api_url( $endpoint, $download_link = false ) {
		$type     = $this->return_repo_type();
		$segments = [
			'owner'  => $this->type->owner,
			'repo'   => $this->type->slug,
			'branch' => empty( $this->type->branch ) ? 'master' : $this->type->branch,
		];

		foreach ( $segments as $segment => $value ) {
			$endpoint = str_replace( ':' . $segment, sanitize_text_field( $value ), $endpoint );
		}

		$repo_api = $this->get_repo_api( $type['git'], $this->type );
		switch ( $type['git'] ) {
			case 'github':
				if ( ! $this->type->enterprise && $download_link ) {
					$type['base_download'] = $type['base_uri'];
					break;
				}
				if ( $this->type->enterprise_api ) {
					$type['base_download'] = $this->type->enterprise_api;
					$type['base_uri']      = null;
					if ( $download_link ) {
						break;
					}
				}
				$endpoint = $repo_api->add_endpoints( $this, $endpoint );
				break;
			case 'gitlab':
				if ( ! $this->type->enterprise && $download_link ) {
					break;
				}
				if ( $this->type->enterprise ) {
					$type['base_download'] = $this->type->enterprise;
					$type['base_uri']      = null;
					if ( $download_link ) {
						break;
					}
				}
				$endpoint = $repo_api->add_endpoints( $this, $endpoint );
				break;
			case 'bitbucket':
				$this->load_authentication_hooks();
				if ( $this->type->enterprise_api ) {
					if ( $download_link ) {
						$type['base_download'] = $type['base_uri'];
						break;
					}
					$endpoint = $repo_api->add_endpoints( $this, $endpoint );

					return $this->type->enterprise_api . $endpoint;
				}
				if ( $download_link && 'release_asset' === self::$method ) {
					$type['base_download'] = $type['base_uri'];
				}
				$endpoint = $repo_api->add_endpoints( $this, $endpoint );
				break;
			case 'gitea':
				if ( $download_link ) {
					$type['base_download'] = $type['base_uri'];
					break;
				}
				$endpoint = $repo_api->add_endpoints( $this, $endpoint );
				break;
			default:
				break;
		}

		$base = $download_link ? $type['base_download'] : $type['base_uri'];

		return $base . $endpoint;
	}
943780
def get(self):
        """"""
        method_name = "_download_" + self.name
        method = getattr(self, method_name)
        return method()
995888
function generateDownloadsDir() {
    // Create temporary directory for file uploads
    let dloads = path.join(path.dirname(require.main.filename), 'download');

    if (!fs.existsSync(dloads)) {
        fs.mkdirSync(dloads);
    }

    let files = fs.readdirSync(dloads);

    for (let ix = 0; ix < files.length; ++ix) {
        fs.unlinkSync(path.join(dloads, files[ix]));
    }

    return dloads;
}
475081
function downloadFromClick(page, ph, selector, callback) {
    const HREF_KEY = 'href';
    async.waterfall([
        function (callback) {
            getSelectorAttribute(page, ph, [selector, HREF_KEY], callback);
        },
        function (page, ph, relativeHref, callback) {
            getCurrentUrl(page, ph, function (error, page, ph, currentUrl) {
                if (error) {
                    callback(error, page, ph);
                    return;
                }
                callback(null, page, ph, currentUrl + relativeHref);
            });
        },
        function (page, ph, url, callback) {
            downloadFromUrl(page, ph, url, callback);
        }
    ], callback);
}
917319
private static function getFopen()
    {
        if (\count($args = func_get_args()) === 1) {
            $args = $args[0];
        }

        $uri      = $args[0];
        $options  = $args[1] ?? [];
        $callback = $args[2] ?? null;

        if ($callback) {
            $options['fopen']['notification'] = ['self', 'progress'];
        }

        if (isset($options['fopen']['ssl'])) {
            $ssl = $options['fopen']['ssl'];
            unset($options['fopen']['ssl']);

            $stream  = stream_context_create([
                'http' => $options['fopen'],
                'ssl' => $ssl
            ], $options['fopen']);
        } else {
            $stream  = stream_context_create(['http' => $options['fopen']], $options['fopen']);
        }


        $content = @file_get_contents($uri, false, $stream);

        if ($content === false) {
            $code = null;
            // Function file_get_contents() creates local variable $http_response_header, check it
            if (isset($http_response_header)) {
                $code = explode(' ', $http_response_header[0] ?? '')[1] ?? null;
            }

            switch ($code) {
                case '404':
                    throw new \RuntimeException('Page not found');
                case '401':
                    throw new \RuntimeException('Invalid LICENSE');
                default:
                    throw new \RuntimeException("Error while trying to download (code: {$code}): {$uri}\n");
            }
        }

        return $content;
    }
539117
function updateDownloadLink( anchor, objectUrl, fileName ) {
    if ( window.updateDownloadLinkIe11 ) {
        return window.updateDownloadLinkIe11( ...arguments );
    }
    anchor.setAttribute( 'href', objectUrl || '' );
    anchor.setAttribute( 'download', fileName || '' );
}
511613
def finalize_download(url, download_to_file, content_type, request):
    
    # If format is given, a format check is performed.
    if content_type and content_type not in request.headers['content-type']:
        msg = 'The downloaded file is not of the desired format'
        raise InvenioFileDownloadError(msg)

    # Save the downloaded file to desired or generated location.
    to_file = open(download_to_file, 'w')
    try:
        try:
            while True:
                block = request.read(CFG_FILEUTILS_BLOCK_SIZE)
                if not block:
                    break
                to_file.write(block)
        except Exception as e:
            msg = "Error when downloading %s into %s: %s" % \
                  (url, download_to_file, e)
            raise InvenioFileDownloadError(msg)
    finally:
        to_file.close()

    # Check Size
    filesize = os.path.getsize(download_to_file)
    if filesize == 0:
        raise InvenioFileDownloadError("%s seems to be empty" % (url,))

    # download successful, return the new path
    return download_to_file
200789
public function construct_download_link( $branch_switch = false ) {
		self::$method       = 'download_link';
		$download_link_base = $this->get_api_url( "/projects/{$this->get_gitlab_id()}/repository/archive.zip" );
		$download_link_base = remove_query_arg( 'private_token', $download_link_base );

		$endpoint = '';
		$endpoint = add_query_arg( 'sha', $this->type->branch, $endpoint );

		// Release asset.
		if ( $this->type->ci_job && '0.0.0' !== $this->type->newest_tag ) {
			$release_asset = $this->get_release_asset();
			return $release_asset;
		}

		// If branch is master (default) and tags are used, use newest tag.
		if ( 'master' === $this->type->branch && ! empty( $this->type->tags ) ) {
			$endpoint = add_query_arg( 'sha', $this->type->newest_tag, $endpoint );
		}

		// Create endpoint for branch switching.
		if ( $branch_switch ) {
			$endpoint = add_query_arg( 'sha', $branch_switch, $endpoint );
		}

		$endpoint      = $this->add_access_token_endpoint( $this, $endpoint );
		$download_link = $download_link_base . $endpoint;

		/**
		 * Filter download link so developers can point to specific ZipFile
		 * to use as a download link during a branch switch.
		 *
		 * @since 8.8.0
		 *
		 * @param string    $download_link Download URL.
		 * @param /stdClass $this->type    Repository object.
		 * @param string    $branch_switch Branch or tag for rollback or branch switching.
		 */
		return apply_filters( 'github_updater_post_construct_download_link', $download_link, $this->type, $branch_switch );
	}