Skip to content

Instantly share code, notes, and snippets.

@fastcodecoq
Last active December 22, 2015 16:49
Show Gist options
  • Save fastcodecoq/6502165 to your computer and use it in GitHub Desktop.
Save fastcodecoq/6502165 to your computer and use it in GitHub Desktop.
Clase para crear streaming con Mongo y GridFS
/*
Copyrights @gomosoft 2013
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
<?php
define("FATAL_ERROR", "Error critico, el sistema se ha colgado");
class Stream{
private $errors;
private $id;
private $db_con;
private $db;
private $col;
private $grid;
private $requester;
public function __construct( $uid = NULL, $id = NULL){
$this->uid = ($uid === NULL) ? substr(md5(time()), 0, 5) : $uid;
$this->id = ($id === NULL) ? md5(time() . "|" . $this->uid . "|" . $_SERVER["HTTP_USER_AGENT"]) : md5($id . "|" . $this->uid . "|" . $_SERVER["USER_AGENT"]);
$this->db_con = new MongoClient();
$this->db = $this->db_con->selectDB("basededatos"); //remplazalo por tu base de datos
$this->col = $this->db->streams;
$this->grid = $this->db->getGridFS();
$this->requester = $_SERVER["HTTP_USER_AGENT"];
$rs = $this->db->secure->findOne();
$this->requester_validate = (count($rs) === 0) ? "developer mode" : $rs["rqter"];
}
public function emit($file_id){
try{
if(!preg_match('/^[0-9a-f]/i', $file_id))
throw new Exception("El parametro para stream no es valido", 43);
$file = $this->grid->findOne(array("md5" => $file_id));
$stream = $file->getResource();
header('Content-type: audio/mp3;');
header('Content-Disposition: inline; filename="meuxic.mp3"');
header('Content-length: '. $file->file["length"]);
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: chunked");
header("ETag: \"{$file->file["md5"]}\"");
header("Accept-Ranges: bytes");
$this->register_stream();
while (!feof($stream)) {
echo fread($stream, 26);
}
}catch (Exception $e){
$this->errors[] = var_dump($e);
return false;
}
}
private function register_stream(){
try{
$ip = $_SERVER["REMOTE_ADDR"];
$date = new MongoDate(strtotime(date("Y-m-d G:i:s")));
if(!filter_var($ip, FILTER_VALIDATE_IP))
throw new Exception("IP inválida", 79);
if($this->requester_validate != "developer mode")
if($this->requester != $this->requester_validate)
throw new Exception("No se puede procesar tu petición, no tienes los privilegios necesarios", 91);
$stream_info = array(
"uid" => $this->uid,
"id" => $this->id,
"user_agent" => get_browser(),
"ip" => $ip,
"start" => $date,
"end" => $date, // esta la actualizaremos cuando acabe la transmisión
"closed_by_error" => "No"
);
$this->col->insert($stream_info);
setcookie("stream", $stream_info["id"], time() + (3600 * 24), "/"); //mantenemos el id del stream lado cliente
}catch(Exception $e){
$this->errors[] = $e;
$this->many_errors();
return false;
}
}
public function errors(){
return $this->errors;
}
public function error(){
return end($this->errors);
}
public function first_error(){
return $this->errors[0];
}
public function close_con( $closed_by = NULL){
$ended = new MongoDate(strtotime(date("Y-m-d G:i:s")));
if($closed_by != FATAL_ERROR)
$this->col->update( array("id" => $this->id), array('$set' => array("end" => $ended)) );
else
$this->col->update( array("id" => $this->id), array('$set' => array("end" => $ended, "closed_by_error" => array( "Yes" , "erros" => $this->errors) )) );
$this->con->close(); // cerramos conexión a la BD
}
private function many_errors(){
if(count($this->errors()) > 1)
$this->fatal_error();
}
private function fatal_error(){
$this->close_con(FATAL_ERROR);
}
}
if($_GET && isset($_GET["id"]))
{
$stream = new Stream;
$id = addslashes( strip_tags($_GET["id"]));
if(!$stream->emit($id))
echo json_encode(array("HTTP_CODE" => "202" , "error" => $stream->error()));
}
/* Happy Coding */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment