<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends CI_Controller {

	public function __construct()
	{ 
		parent:: __construct();
		$this->load->model('common_model');
	}

	public function uploadtoserver()
    {
		// 5 minutes execution time
		@set_time_limit(5 * 60);
		// Uncomment this one to fake upload time
		// usleep(5000);

		// Settings

		$targetDir = FCPATH . "assets/videos/uploads";
		//$targetDir = 'uploads';
		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds


		// Create target dir
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);
		}

		// Get a file name
		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}

		$filePath = $targetDir . DIRECTORY_SEPARATOR . str_replace(' ', '_', $fileName);

		// Chunking might be enabled
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


		// Remove old temp files	
		if ($cleanupTargetDir) {
			if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
			}

			while (($file = readdir($dir)) !== false) {
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

				// If temp file is current file proceed to the next
				if ($tmpfilePath == "{$filePath}.part") {
					continue;
				}

				// Remove temp file if it is older than the max age and is not the current file
				if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
					@unlink($tmpfilePath);
				}
			}
			closedir($dir);
		}	


		// Open temp file
		if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
		}

		if (!empty($_FILES)) {
			if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			}

			// Read binary input stream and append it to temp file
			if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		} else {	
			if (!$in = @fopen("php://input", "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		}

		while ($buff = fread($in, 4096)) {
			fwrite($out, $buff);
		}

		@fclose($out);
		@fclose($in);
		//echo $main_filename = pathinfo($filePath, PATHINFO_FILENAME);die;

		// Check if file has been uploaded
		if (!$chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off 
			rename("{$filePath}.part", $filePath);

			$main_filename = pathinfo($filePath, PATHINFO_FILENAME).'-'.rand(1000,1);
			//$main_filename = pathinfo($filePath, PATHINFO_FILENAME);
			/**********insert in db****************/
			/*$postdata = array(
		            'user_id' 	=> $this->session->userdata('user_id'),
		            'status'=> 1,
		            'created_at'	=>time()
		        );
		    $postId = $this->common_model->insertData('usr_post',$postdata);*/
			$file['user_id'] 	= $this->session->userdata('user_id');
			$file['post_id'] 	= 0;
		    
		    //$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>15,'created'=>time(),'video_id'=>$fileId));
		    /**********insert in db****************/
		    $file_ext = explode('.', $filePath);
		    $extsn = '';
		    if(count($file_ext)>0){
		    	$extsn = $file_ext[1];
		    }
		    //echo "ffmpeg -i $filePath ".$targetDir.DIRECTORY_SEPARATOR.$main_filename.".mp4";
		    if(strtolower($extsn) != 'mp4'){
		    	$file['filename'] = $main_filename.'.mp4';
		    	//exec("ffmpeg -i $filePath -c:v libx264 ".$targetDir.DIRECTORY_SEPARATOR.$main_filename.".mp4");
		    	exec("ffmpeg -i $filePath -vf scale=1080:566,setsar=1:1 ".$targetDir.DIRECTORY_SEPARATOR.$main_filename.".mp4 -y 2> /home/castleevents/public_html/assets/videos/uploads/out.txt");
		    	//exec("ffmpeg -i $filePath -vf scale=1080:566,setsar=1:1 ".$targetDir.DIRECTORY_SEPARATOR.$main_filename.".webm -y 2> /home/castleevents/public_html/assets/videos/uploads/out.txt");
			} else {
				$file['filename'] = $fileName;
				//exec("ffmpeg -i $filePath -vf scale=1080:566,setsar=1:1 ".$targetDir.DIRECTORY_SEPARATOR.$extsn[0].".webm -y 2> /home/castleevents/public_html/assets/videos/uploads/out.txt");
			}
			//exec('ffmpeg -y -i '.$filePath.' -c:v libx264 -c:a aac -pix_fmt yuv420p -movflags faststart -hide_banner '.$targetDir.DIRECTORY_SEPARATOR.$main_filename.'.mp4 2>&1', $out, $res);

			//exec('ffmpeg -i '.$filePath.'  '.$targetDir.DIRECTORY_SEPARATOR.$main_filename.'.webm 2>&1', $out, $res);
			//exec("ffmpeg -i $filePath -acodec libvorbis -b:a 96k -ac 2 -vcodec libvpx -b:v 400k -f webm -s 384x216 ".$targetDir.DIRECTORY_SEPARATOR.$main_filename.".webm");
			//exec("ffmpeg -i ".$filePath." ".$targetDir."/".$main_filename.".mp4"); 
			if(strtolower($extsn) != 'mp4'){
				$thumbnail = FCPATH . "assets/videos/uploads/thumb/".$main_filename.".jpg";
			} else {
				$thumbnail = FCPATH . "assets/videos/uploads/thumb/".str_replace('mp4', 'jpg', $fileName);
			}

			// shell command [highly simplified, please don't run it plain on your script!]
			exec("ffmpeg -i $filePath -deinterlace -an -ss 1 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg $thumbnail 2>&1");

			$this->load->library('s3_upload');
  			//echo $filePath;
			// Upload file
			//print_r($this->s3_upload);die;
			if(strtolower($extsn) != 'mp4'){
				$sample_file = $targetDir.DIRECTORY_SEPARATOR.$main_filename.'.mp4';
				//$sample_file_webm = $targetDir.DIRECTORY_SEPARATOR.$main_filename.'.webm';
			} else {
				$sample_file = $filePath;
				//$sample_file_webm = $targetDir.DIRECTORY_SEPARATOR.$extsn[0].'.webm';
			}
			$file_url = $this->s3_upload->upload_file($sample_file, $file['user_id']);			
			//$file_url = $this->s3_upload->upload_file($sample_file_webm, $file['user_id']);
			$fileId = $this->common_model->insertData('sys_videos',$file);
			die('{"jsonrpc" : "2.0", "result" : "completed", "id" : "id"}');

		} else {
			die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
		}

		// Return Success JSON-RPC response
		

    }

    public function deleteVideo($enc_userID='')
	{
		if($enc_userID!='')
		{
			$ugalId=base64_decode($enc_userID);
			$imageDetails = $this->common_model->getAllRow('sys_videos',array('id'=>$ugalId));
			$this->load->library('s3_upload');
  			$file_url = $this->s3_upload->remove_file($imageDetails['filename'], $imageDetails['user_id']);
			$video_name = explode('.', $imageDetails['filename']);
            if(count($video_name)>1){
				@unlink(FCPATH.'assets/videos/uploads/thumb/'.$video_name[0].'.jpg');
				@unlink(FCPATH.'assets/videos/uploads/'.$video_name[0].'.mp4');
				@unlink(FCPATH.'assets/videos/uploads/'.$video_name[0].'.webm');
			}
			@unlink(FCPATH.'assets/videos/uploads/'.$imageDetails['filename']);
			$this->common_model->deleteData('sys_videos',array('id'=>$ugalId));
			//$this->utility->setMsg('Video rejected','SUCCESS');	
			redirect(base_url().'pictures');
		}
		else
		{
			//$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'pictures');
		}
	}
}

/* End of file upload.php */
/* Location: ./application/controllers/upload.php */