Function used to send media files from the media folder to the browser.
188417
def send_media_file(self, filename):
        
        cache_timeout = self.get_send_file_max_age(filename)
        return send_from_directory(self.config['MEDIA_FOLDER'], filename,
                                   cache_timeout=cache_timeout)
180225
function FileListController($scope, mediator, $stateParams, $window, userClient, fileMediatorService, $timeout, mobileCamera, desktopCamera, FILE_CONFIG) {
  var self = this;
  self.files = null;
  var _files;
  self.uploadEnabled = FILE_CONFIG.uploadEnabled;
  userClient.getProfile().then(function(profileData){
    var userFilter;
    if(FILE_CONFIG.userMode){
      userFilter = profileData.id;
    }
    
    function refreshFiles(){
      fileMediatorService.listFiles(userFilter).then(function(files){
        $timeout(function(){
          _files = files;
          self.files = files;
        });
      });
    }
  
    refreshFiles();
  
    fileMediatorService.subscribeToFileCRUDDoneTopics($scope, refreshFiles);
  
    self.selectFile = function(event, file){
      self.selectedFileId = file.id;
      mediator.publish(fileMediatorService.fileUITopics.getTopic(CONSTANTS.TOPICS.SELECTED), file);
    };
  
    //TODO: Move to service
    self.applyFilter = function(term){
      term = term.toLowerCase();
      self.files = _files.filter(function(file){
        return String(file.name).toLowerCase().indexOf(term) !== -1
          || String(file.id).indexOf(term) !== -1;
      });
    };
  
    $scope.$parent.selected = {id: null};
    var captureThenUpload = function(){
      if($window.cordova){
        return mobileCamera.capture()
          .then(function(capture){
            var fileData = {
              userId: profileData.id,
              fileURI: capture.fileURI,
              options: {fileName: capture.fileName}
            };
            fileMediatorService.createFile(fileData);
          });
      }else{
        return desktopCamera.capture()
          .then(function(dataUrl){
            return fileMediatorService.createFile({userId: profileData.id, dataUrl: dataUrl});
          });
      }
    };
    self.capturePhoto = function(){
      captureThenUpload().then(function(){
      }, function(error){
        console.error(error);
      });
    };
  });
}
999561
public function sendToBrowser($strFilename = '', $strDest = 'I')
    {
        $strFilename = $strFilename ?: $this->buildFilename();

        $this->objPdf->Output($strFilename, $strDest);
    }
1186000
def upload_gallery_file(self, folder_name, file_name, data=None, input_file_path=None,
                            prevent_share=False, content_type="image/png", scope='content/write'):
        
        if input_file_path:
            with open(input_file_path, 'rb') as f:
                data = f.read()

        if not data:
            raise ValueError('Either the data of a file or the path to a file must be provided')

        params = {
            'fileName': file_name,
            'preventShare': 'true' if prevent_share else 'false',
        }

        return _post(
            token=self.oauth.get_user_token(scope),
            uri='/user/media/file/' + urllib.quote(folder_name) + '?' + urllib.urlencode(params),
            data=data,
            content_type=content_type,
        )
511049
async def download_media(self, *args, **kwargs):
        
        return await self._client.download_media(self, *args, **kwargs)
685282
def media(self, uri):
        """"""
        try:
            local_path, _ = urllib.request.urlretrieve(uri)
            metadata = mutagen.File(local_path, easy=True)
            if metadata.tags:
                self._tags = metadata.tags
            title = self._tags.get(TAG_TITLE, [])
            self._manager[ATTR_TITLE] = title[0] if len(title) else ''
            artist = self._tags.get(TAG_ARTIST, [])
            self._manager[ATTR_ARTIST] = artist[0] if len(artist) else ''
            album = self._tags.get(TAG_ALBUM, [])
            self._manager[ATTR_ALBUM] = album[0] if len(album) else ''
            local_uri = 'file://{}'.format(local_path)

        # urllib.error.HTTPError
        except Exception:  # pylint: disable=broad-except
            local_uri = uri
        self._player.set_state(Gst.State.NULL)
        self._player.set_property(PROP_URI, local_uri)
        self._player.set_state(Gst.State.PLAYING)
        self.state = STATE_PLAYING
        self._manager[ATTR_URI] = uri
        self._manager[ATTR_DURATION] = self._duration()
        self._manager[ATTR_VOLUME] = self._player.get_property(PROP_VOLUME)
        _LOGGER.info('playing %s (as %s)', uri, local_uri)
100245
def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None,
                                        content_type='application/octet-stream', auto_open=False,
                                        prevent_share=False, scope='content/send'):
        
        if input_file_path:
            with open(input_file_path, 'rb') as f:
                data = f.read()

        if not data:
            raise ValueError('Either the data of a file or the path to a file must be provided')

        params = {
            'fileName': file_name,
            'userId': user_id,
            'autoOpen': 'true' if auto_open else 'false',
            'preventShare': 'true' if prevent_share else 'false',
        }

        return _post(
            token=self.oauth.get_app_token(scope),
            uri='/user/media/file/send?' + urllib.urlencode(params),
            data=data,
            content_type=content_type
        )
1044504
function (client) {
	/**
	 * Upload a media file
	 * @param {String} name The name of uploaded file.
	 * @param {String|Buffer|Readable} data Data to upload. If data is string it should be path to file to upload.
	 * @param {String} contentType Optional MIME type of uploaded data (default: application/octet-stream).
	 * @param {Function} [callback] Callback for the operation
	 * @return {Promise} A promise for the operation
	 */
	this.upload = function (name, data, contentType, callback) {
		if (!callback && typeof contentType === "function") {
			callback = contentType;
			contentType = null;
		}
		return getReadStreamData(data)
			.then(function (streamData) {
				return new Promise(function (resolve, reject) {
					var req = request(
						client.createRequestOptions({
							path   : encodeURI("media/" + name),
							method :  "PUT"
						})
					);
					req.headers["Content-Type"] =
						contentType || "application/octet-stream";
					req.headers["Content-Length"] = streamData.size;
					req.on("error", reject);
					req.on("response", resolve);
					streamData.stream.pipe(req);
				});
			})
			.then(client.handleResponse)
			.asCallback(callback);
	};

	/**
	 * Download a media file
	 * @param {String} name The name of downloaded file.
	 * @param {Function} [callback] Callback for the operation
	 * @return {DownloadMediaFileResponse} A promise for the operation
	 */
	this.download = function (name, callback) {
		return client
			.makeRequest ({
				path     : encodeURI("media/" + name),
				method   : "GET",
				encoding : "binary"
			})
			.then(function (response) {
				return {
					contentType : response.headers["content-type"],
					content     : response.body
				};
			})
			.asCallback(callback);
	};

	/**
	 * Gets a list of your media files.
	 * @param {Function} [callback] Callback for the operation
	 * @return {Array<MediaFileResponse>} A promise for the operation
	 */
	this.list = function (callback) {
		return client
			.makeRequest({
				path   : "media",
				method : "GET"
			})
			.then(function (response) {
				return response.body;
			})
			.asCallback(callback);
	};

	/**
	 * Remove a media file
	 * @param {String} name The name of file to remove.
	 * @param {Function} [callback] Callback for the operation
	 * @return {Promise} A promise for the operation
	 */
	this.delete = function (name, callback) {
		return client
			.makeRequest({
				path   : encodeURI("media/" + name),
				method : "DELETE"
			})
			.asCallback(callback);
	};
}
472085
function toBuffer (media) {
  return new Promise((resolve, reject) => {
    if (isURL(media)) {
      toBase64(media)
      .then(data => {
        toBuffer(data)
        .then(data => resolve(data))
        .catch(error => reject(error))
      })
      .catch(error => reject(error))
    } else if (isBase64(media)) {
      try {
        resolve(Buffer.from(media))
      } catch (ex) {
        reject(ex)
      }
    } else if (isFile(media)) {
      fs.readFile(media, (err, data) => {
        err && reject(err)
        resolve(data)
      })
    } else {
      reject('Error: toBuffer(): argument must be file, url or file')
    }
  })
}
562728
def media_upload(self, filename, *args, **kwargs):
        
        f = kwargs.pop('file', None)
        headers, post_data = API._pack_image(filename, 4883, form_field='media', f=f)
        kwargs.update({'headers': headers, 'post_data': post_data})

        return bind_api(
            api=self,
            path='/media/upload.json',
            method='POST',
            payload_type='media',
            allowed_param=[],
            require_auth=True,
            upload_api=True
        )(*args, **kwargs)
311160
def send(self):
        """"""
        self._file.write(self.as_bytes())
        self._file.write(b'\r\n')
741185
def sendImage(
        self,
        image_id,
        message=None,
        thread_id=None,
        thread_type=ThreadType.USER,
        is_gif=False,
    ):
        
        if is_gif:
            mimetype = "image/gif"
        else:
            mimetype = "image/png"
        return self._sendFiles(
            files=[(image_id, mimetype)],
            message=message,
            thread_id=thread_id,
            thread_type=thread_type,
        )
9222
def send_single_file(self, sender, receiver, media_id):
        
        return self.send_file(sender, 'single', receiver, media_id)
832886
async function writeCustomMediaToMjsFile(to, customMedia) {
	const mjsContents = Object.keys(customMedia).reduce((mjsLines, name) => {
		mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customMedia[name])}'`);

		return mjsLines;
	}, []).join(',\n');
	const mjs = `export const customMedia = {\n${mjsContents}\n};\n`;

	await writeFile(to, mjs);
}
73920
def send_audio(self, number, path):
        
        return self._send_media_path(number, path, RequestUploadIqProtocolEntity.MEDIA_TYPE_AUDIO)
664057
def _sendFiles(
        self, files, message=None, thread_id=None, thread_type=ThreadType.USER
    ):
        
        thread_id, thread_type = self._getThread(thread_id, thread_type)
        data = self._getSendData(
            message=self._oldMessage(message),
            thread_id=thread_id,
            thread_type=thread_type,
        )

        data["action_type"] = "ma-type:user-generated-message"
        data["has_attachment"] = True

        for i, (file_id, mimetype) in enumerate(files):
            data["{}s[{}]".format(mimetype_to_key(mimetype), i)] = file_id

        return self._doSendRequest(data)
1286196
function(folder, dest) {
		try {
			fs.mkdirSync(dest, '0755');
		} catch (e) {}
		var files = fs.readdirSync(folder);
		var indexFile = templatesManager.getFolderIndex(files);
		logger.debug('Index file for "%s": "%s"', folder, indexFile);
		files.forEach(function(file) {
			if (config.exclude.indexOf(file) === -1) {
				var curPath = path.join(folder, file);
				if (fs.statSync(curPath).isDirectory()) {
					walk(curPath, path.join(dest, file));
				} else {
					if (['.md', '.markdown'].indexOf(path.extname(file).toLowerCase()) !== -1) {
						var isIndex = (file === indexFile);
						filesToRender[curPath] = {
							filename: file,
							path: curPath,
							versions: templatesManager.getVersions(curPath, 'template', isIndex),
							isIndex: isIndex
						};
					} else if (config.media.indexOf(path.extname(file).toLowerCase().substr(1)) !== -1) {
						logger.log('Copy "%s" to "%s"', curPath, path.join(dest, path.basename(curPath)));
						fs.copy(curPath, path.join(dest, path.basename(curPath)), {replace: true}, function(err) {
							if (err) {
								logger.error('Problem while copying media file "%s" to "%s": "%s"', curPath, path.join(dest, path.basename(curPath)), err);
							}
						});
					}
				}
			} else {
				logger.debug('Excluded:', file);
			}
		});
	}