This method uses the `download_file` task to retrieve binary files
        such as attachments, images and videos.

        Notice that this method does not wait for the tasks it creates to return
        a result synchronously.
338695
def download_files(self, files):
        
        utils.pending_message(
            "Downloading {nfiles} file{plural}...".format(
                nfiles=len(files),
                plural='s' if len(files) > 1 else ''
            ))

        for file in files:
            if 'file_id' not in file:
                continue

            def build_callback(file):
                """Callback to save a download file result to a file on disk."""
                def file_callback(task):
                    device_name = self.devices[self.device_id]['device_name']
                    path_chunks = file['file_path'].split('/')

                    directory = os.path.join('files', device_name, *path_chunks[:-1])

                    filepath = utils.get_or_create_filepath(file['filename'], directory)

                    with open(filepath, 'wb') as out:
                        out.write(task.result)

                    if settings.getboolean('logging', 'time_profile'):
                        filepath = utils.append_profile_info(filepath, task.timer)

                    with indent(4):
                        utils.print_message(filepath)

                return file_callback

            self.client.download_file(
                account=self.account,
                device=self.device_id,
                file=file['file_id'],
                callback=build_callback(file)
            )
168037
def download_attachments(self):
        
        if not self._parent.has_attachments:
            log.debug(
                'Parent {} has no attachments, skipping out early.'.format(
                    self._parent.__class__.__name__))
            return False

        if not self._parent.object_id:
            raise RuntimeError(
                'Attempted to download attachments of an unsaved {}'.format(
                    self._parent.__class__.__name__))

        url = self.build_url(self._endpoints.get('attachments').format(
            id=self._parent.object_id))

        response = self._parent.con.get(url)
        if not response:
            return False

        attachments = response.json().get('value', [])

        # Everything received from cloud must be passed as self._cloud_data_key
        self.untrack = True
        self.add({self._cloud_data_key: attachments})
        self.untrack = False

        # TODO: when it's a item attachment the attachment itself
        # is not downloaded. We must download it...
        # TODO: idea: retrieve the attachments ids' only with
        # select and then download one by one.
        return True
125610
def download_file(self, file_id, dest):
        
        f = self.getFile(file_id)
        try:
            d = dest if _isfile(dest) else open(dest, 'wb')

            r = api.download((self._token, f['file_path']), preload_content=False)

            while 1:
                data = r.read(self._file_chunk_size)
                if not data:
                    break
                d.write(data)
        finally:
            if not _isfile(dest) and 'd' in locals():
                d.close()

            if 'r' in locals():
                r.release_conn()
868705
def download_file(self, src_uri, target):
        
        resource = self.get_resource_by_uri(src_uri)
        if not isinstance(resource, File):
            raise MediaFireError("Only files can be downloaded")

        quick_key = resource['quickkey']
        result = self.api.file_get_links(quick_key=quick_key,
                                         link_type='direct_download')
        direct_download = result['links'][0]['direct_download']

        # Force download over HTTPS
        direct_download = direct_download.replace('http:', 'https:')

        name = resource['filename']

        target_is_filehandle = True if hasattr(target, 'write') else False

        if not target_is_filehandle:
            if (os.path.exists(target) and os.path.isdir(target)) or \
                    target.endswith("/"):
                target = os.path.join(target, name)

            if not os.path.isdir(os.path.dirname(target)):
                os.makedirs(os.path.dirname(target))

            logger.info("Downloading %s to %s", src_uri, target)

        response = requests.get(direct_download, stream=True)
        try:
            if target_is_filehandle:
                out_fd = target
            else:
                out_fd = open(target, 'wb')

            checksum = hashlib.sha256()
            for chunk in response.iter_content(chunk_size=4096):
                if chunk:
                    out_fd.write(chunk)
                    checksum.update(chunk)

            checksum_hex = checksum.hexdigest().lower()
            if checksum_hex != resource['hash']:
                raise DownloadError("Hash mismatch ({} != {})".format(
                    resource['hash'], checksum_hex))

            logger.info("Download completed successfully")
        finally:
            if not target_is_filehandle:
                out_fd.close()
376747
def download_file(request):
    ''''''
    if request.method == "GET":
        if path.exists(settings.MEDIA_ROOT):
            zipfile_name = 'media_%s.zip' % settings.SITE_NAME
            in_memory_file = BytesIO()

            media_zipfile = zipfile.ZipFile(in_memory_file, 'w',
                                            zipfile.ZIP_DEFLATED)

            directory_name = path.split(settings.MEDIA_ROOT)[-1]
            for root, dirs, files in walk(directory_name):
                for file in files:
                    media_zipfile.write(path.join(root, file))

            media_zipfile.close()

            resp = HttpResponse(in_memory_file.getvalue(),
                                content_type="application/x-zip-compressed")
            resp['Content-Disposition'] = (
                'attachment; filename=%s' % zipfile_name)

        else:
            resp = render(request,
                          'django_admin/transfer_media_message.html',
                          {'error_message':
                           'media file does not exist'})
    else:
        resp = HttpResponseNotAllowed(permitted_methods=['GET'])

    return resp
1053707
def get_file_download(self, resources):
        
        api_name = 'virustotal-file-download'
        api_endpoint = 'file/download'
        return self._extract_all_responses(resources, api_endpoint, api_name)
363158
def download_file(url, file_name):
    

    logger.info("Downloading URL: %s", url)
    file_size = 0

    if not os.path.isfile(file_name):
        response = requests.get(url, stream=True)

        with open(file_name, "wb") as fp:
            if not response.ok:
                raise Exception("Download exception. Will fail.")

            for block in response.iter_content(1024):
                if not block:
                    break

                fp.write(block)
                file_size += len(block)

        logger.info("Download finished, size is %d bytes.", file_size)

    return file_size
1006053
def get_file(self, job_binary_id):
        """"""
        resp = self.api.get('/job-binaries/%s/data' % job_binary_id)

        if resp.status_code != 200:
            self._raise_api_exception(resp)
        return resp.content
146682
def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE):
  
  logging.info(u"Downloading: %s to: %s", file_obj.urn, target_path)

  target_file = open(target_path, "wb")
  file_obj.Seek(0)
  count = 0

  data_buffer = file_obj.Read(buffer_size)
  while data_buffer:
    target_file.write(data_buffer)
    data_buffer = file_obj.Read(buffer_size)
    count += 1
    if not count % 3:
      logging.debug(u"Downloading: %s: %s done", file_obj.urn,
                    utils.FormatNumberAsString(count * buffer_size))
  target_file.close()
590103
def download_photo_async(photo):
    
    photo_id = photo['id']
    photo_title = photo['title']
    download_url = get_photo_url(photo_id)
    photo_format = download_url.split('.')[-1]
    photo_title = photo_title + '.' + photo_format
    file_path = directory + os.sep + photo_title
    logger.info('Download %s...', photo_title.encode('utf-8'))
    req = [grequests.get(download_url)]
    counter_lock = multiprocessing.Lock()
    for resp in grequests.map(req):
        with open(file_path, 'w') as f:
            f.write(resp.content)
            with counter_lock:
                global counter
                counter -= 1
        logger.info(
            'The number of pictures remaining: %s', counter
        )
995306
async def _download_photo(self, photo, file, date, thumb, progress_callback):
        """"""
        # Determine the photo and its largest size
        if isinstance(photo, types.MessageMediaPhoto):
            photo = photo.photo
        if not isinstance(photo, types.Photo):
            return

        size = self._get_thumb(photo.sizes, thumb)
        if not size or isinstance(size, types.PhotoSizeEmpty):
            return

        file = self._get_proper_filename(file, 'photo', '.jpg', date=date)
        if isinstance(size, (types.PhotoCachedSize, types.PhotoStrippedSize)):
            return self._download_cached_photo_size(size, file)

        result = await self.download_file(
            types.InputPhotoFileLocation(
                id=photo.id,
                access_hash=photo.access_hash,
                file_reference=photo.file_reference,
                thumb_size=size.type
            ),
            file,
            file_size=size.size,
            progress_callback=progress_callback
        )
        return result if file is bytes else file
897609
public FileDownloadQueueSet downloadTogether(List<BaseDownloadTask> tasks) {
        this.isSerial = false;
        this.tasks = new BaseDownloadTask[tasks.size()];
        tasks.toArray(this.tasks);

        return this;

    }
858654
def reconstruct_binary(self, attachments):
        
        self.data = self._reconstruct_binary_internal(self.data,
                                                      self.attachments)
1274604
def download_blob_to(file) #:doc:
        file.binmode
        blob.download { |chunk| file.write(chunk) }
        file.flush
        file.rewind
      end
599628
def process_files(self):
        
        from .files import VideoFile, ExtractedVideoThumbnailFile, WebVideoFile

        downloaded = super(VideoNode, self).process_files()

        try:
            # Extract thumbnail if one hasn't been provided and derive_thumbnail is set
            if self.generate_thumbnail and not self.has_thumbnail():
                videos = [f for f in self.files if isinstance(f, VideoFile) or isinstance(f, WebVideoFile)]
                assert len(videos) > 0 and videos[0].filename, "Cannot extract thumbnail (No videos found on node {0})".format(self.source_id)

                self.set_thumbnail(ExtractedVideoThumbnailFile(config.get_storage_path(videos[0].filename)))
                downloaded.append(self.thumbnail.get_filename())

        except AssertionError as ae:
            config.LOGGER.warning(ae)

        return downloaded
193840
def download(self, request, **kwargs):
        

        # method check to avoid bad requests
        self.method_check(request, allowed=['get'])

        # create a basic bundle object for self.get_cached_obj_get.
        basic_bundle = self.build_bundle(request=request)

        # using the primary key defined in the url, obtain the tileset
        tileset = self.cached_obj_get(
            bundle=basic_bundle,
            **self.remove_api_resource_names(kwargs))

        filename = helpers.get_tileset_filename(tileset)
        filename = os.path.abspath(filename)
        if os.path.isfile(filename):
            response = serve(request, os.path.basename(filename), os.path.dirname(filename))
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(filename))
        else:
            response = self.create_response(request, {'status': 'not generated'})
        return response
255053
def downloadFiles(self):
        
        for each_file in self.filesToSync:
            self.downloadFile(each_file["name"], each_file["ispickle"], each_file["at_home"])