Advertisement
Guest User

Untitled

a guest
Sep 12th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 28.69 KB | None | 0 0
  1. <?php defined('BASEPATH') || exit('No direct script access allowed');
  2.  
  3. /**
  4.  * videos controller
  5.  */
  6. class Videos extends Front_Controller
  7. {
  8.  
  9.     protected $permissionCreate = 'Videos.Create';
  10.     protected $permissionDelete = 'Videos.Delete';
  11.     protected $permissionEdit = 'Videos.Edit';
  12.     protected $permissionView = 'Videos.View';
  13.     protected $permissionManage = 'Videos.Manage';
  14.     public $fields = array();
  15.  
  16.     protected $mbConverterHost = '192.168.200.190';
  17.     protected $mbConverterUsername = 'mediabox-converter';
  18.     protected $mbConverterPassword = 'dawd!@#$';
  19.  
  20.     protected $mbHost = '192.168.200.171';
  21.     protected $mbUsername = 'mediabox';
  22.     protected $mbPassword = 'dawd!@#$';
  23.  
  24.     protected $mbTrackerHost = '192.168.200.178';
  25.     protected $mbTrackerUsername = 'mediabox-tracker';
  26.     protected $mbTrackerPassword = 'dawd!@#$';
  27.  
  28.  
  29.     protected $trackerFilePath = "/home/mediabox-tracker/encodes";
  30.     protected $trackerTorrentPath = "/home/mediabox-tracker/torrents";
  31.  
  32.     /**
  33.      * Constructor
  34.      *
  35.      * @return void
  36.      */
  37.  
  38.     public function __construct()
  39.     {
  40.         parent::__construct();
  41.         $this->auth->restrict($this->permissionView);
  42.  
  43.         $this->load->model('videos/videos_model');
  44.  
  45.         $this->lang->load('videos/main', '', false, true, '', '', false);
  46.  
  47.         $this->lang->load('datatable');
  48.         $this->load->helper('color_helper');
  49.         $this->load->library('functions');
  50.         load_color('videos/main');
  51.  
  52.         ini_set('max_execution_time', 600);
  53.         //Load sshseclib for SSH commands.
  54.         include(realpath(APPPATH) . '/libraries/phpseclib/Net/SSH2.php');
  55.  
  56.     }
  57.  
  58.     /**
  59.      * Display a list of Videos data.
  60.      *
  61.      * @return void
  62.      */
  63.     public function index()
  64.     {
  65.  
  66.         $this->auth->restrict($this->permissionView);
  67.  
  68.         $breadcrumb = array('nomenclator' => lang('nomenclator'), 'videos' => lang('videos'));
  69.         breadcrumb($breadcrumb, true, false);
  70.  
  71.  
  72.         $this->load->model('datatable/datatable_model');
  73.         $dataTable['id'] = 'videos_table';
  74.         $dataTable['url'] = 'videos';
  75.         $dataTable['module'] = 'videos';
  76.         $dataTable['fields'] = $this->videos_model->get_fields();
  77.         $this->datatable_model->add_js($dataTable);
  78.  
  79.         $videos = $this->videos_model->getAllVideos();
  80.  
  81.         foreach ($videos as $k => $video) {
  82.             $videos[$k]['duration_readable'] = $this->timable($video['duration_seconds']);
  83.         }
  84.  
  85.         Template::set('clientId', $this->parent());
  86.         Template::set('videos', $videos);
  87.         Assets::clear_cache();
  88.         Assets::add_module_js('grupuri', 'bootbox.min.js');
  89.         Assets::add_js('resumable.js');
  90.         Template::set_view('videos/front/index');
  91.         Template::render();
  92.     }
  93.  
  94.     private function timable($seconds)
  95.     {
  96.         $t = round($seconds);
  97.         return sprintf('%02d:%02d:%02d', ($t / 3600), ($t / 60 % 60), $t % 60);
  98.     }
  99.  
  100.     /**
  101.      * Form for videos module
  102.      *
  103.      * @param int $id -> id_record
  104.      *
  105.      * @return void
  106.      */
  107.     public function form($id = NULL)
  108.     {
  109.         if (empty($id)) {
  110.             $this->auth->restrict($this->permissionCreate);
  111.             $mode = 'create';
  112.             $breadcrumb = array('nomenclator' => lang('nomenclator'), 'videos' => lang('videos'), 'form' => lang('add_label'));
  113.         } elseif (is_numeric($id)) {
  114.             $this->auth->restrict($this->permissionEdit);
  115.             $mode = 'edit';
  116.             $breadcrumb = array('nomenclator' => lang('nomenclator'), 'videos' => lang('videos'), 'form' => lang('edit_label'));
  117.         }
  118.  
  119.         breadcrumb($breadcrumb, true, false);
  120.  
  121.         if (isset($_POST['save'])) {
  122.             if ($id_i = $this->form_videos($mode, $id)) {
  123.                 if ($mode == 'create') {
  124.                     if (is_numeric($id_i)) {
  125.                         Template::set_message(lang('videos_create_success'), 'success');
  126.                     } else {
  127.                         Template::set_message(lang('videos_create_failure'), 'success');
  128.                     }
  129.                 } else {
  130.  
  131.                     Template::set_message(lang('videos_edit_success'), 'success');
  132.                 }
  133.                 redirect('nomenclator/videos');
  134.             }
  135.             // Not validation error
  136.             if (!empty($this->videos_model->error)) {
  137.                 Template::set_message(lang('videos_edit_failure') . $this->videos_model->error, 'error');
  138.             }
  139.         } elseif (isset($_POST['delete'])) {
  140.             $this->auth->restrict($this->permissionDelete);
  141.  
  142.             $result = true;
  143.             $deleted = $this->videos_model->delete($id);
  144.             if ($deleted == false) {
  145.                 $result = false;
  146.             }
  147.             if ($result) {
  148.                 Template::set_message(lang('videos_delete_success'), 'success');
  149.                 redirect('nomenclator/videos');
  150.             } else {
  151.                 Template::set_message(lang('videos_delete_failure') . $this->videos_model->error, 'error');
  152.             }
  153.         }
  154.  
  155.         $data = array();
  156.         if ($mode == 'edit') {
  157.             $data = $this->videos_model->find($id);
  158.         }
  159.  
  160.         Template::set('data', $data);
  161.  
  162.         Template::set_view('videos/front/form');
  163.         Template::render();
  164.     }
  165.  
  166.     /**
  167.      * Process form for videos module
  168.      * Check for validation if validations are ok go to insert/update
  169.      *
  170.      * @param string $mode -> create|edit
  171.      * @param int $id -> record id for update
  172.      *
  173.      * @return int|bool
  174.      */
  175.     private function form_videos($mode, $id = NULL)
  176.     {
  177.  
  178.         // Validate the data
  179.         $this->load->model('validari/get_validari_model');
  180.  
  181.  
  182.         $banned = $this->videos_model->get_banned_labels();
  183.  
  184.         $this->form_validation->set_rules($this->get_validari_model->get_validation_rules(9, $banned));
  185.         if ($this->form_validation->run() === false) {
  186.             return false;
  187.         }
  188.  
  189.         // Make sure we only pass in the fields we want
  190.         $data = $this->videos_model->prep_data($this->input->post());
  191.  
  192.  
  193.         $return = false;
  194.         if ($mode == 'create') {
  195.             $id = $this->videos_model->update($data);
  196.  
  197.             if (is_numeric($id)) {
  198.                 $return = $id;
  199.             }
  200.         } elseif ($mode == 'edit') {
  201.             $return = $this->videos_model->update($data, $id);
  202.         }
  203.  
  204.         return $return;
  205.     }
  206.  
  207.     /**
  208.      * Autovehicule datatable
  209.      *
  210.      *
  211.      * @return void
  212.      */
  213.     public function datatable()
  214.     {
  215.         $this->load->model('datatable/datatable_model');
  216.         $fields = array(
  217.             'id' => '',
  218.             'videos_name' => '',
  219.         );
  220.  
  221.  
  222.         $this->datatable_model->generate_output($fields, 'videos');
  223.     }
  224.  
  225.     //Uploading Spaghetti
  226.     public function run()
  227.     {
  228.  
  229.         $this->output->enable_profiler(FALSE); /* Disable Profiler */
  230.  
  231.         //Set paths
  232.         $realPath = realpath('./uploads') . '/client_' . $this->parent();
  233.         $tempPath = $realPath . '/temp/';
  234.         $originalPath = $realPath . '/original/';
  235.         $encodesPath = $realPath . '/encodes/';
  236.         $torrentsPath = $realPath . '/torrents/';
  237.         $logsPath = $realPath . '/logs/';
  238.  
  239.  
  240.         //Create Folders if missing
  241.         $this->createFolders($tempPath, $originalPath, $encodesPath, $torrentsPath, $logsPath);
  242.  
  243.  
  244.         if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  245.  
  246.             if (!(isset($_GET['resumableIdentifier']) && trim($_GET['resumableIdentifier']) != '')) {
  247.                 $_GET['resumableIdentifier'] = '';
  248.             }
  249.  
  250.             $temp_dir = $tempPath . $_GET['resumableIdentifier'];
  251.             if (!(isset($_GET['resumableFilename']) && trim($_GET['resumableFilename']) != '')) {
  252.                 $_GET['resumableFilename'] = '';
  253.             }
  254.             if (!(isset($_GET['resumableChunkNumber']) && trim($_GET['resumableChunkNumber']) != '')) {
  255.                 $_GET['resumableChunkNumber'] = '';
  256.             }
  257.             $chunk_file = $temp_dir . $_GET['resumableFilename'] . '.part' . $_GET['resumableChunkNumber'];
  258.             if (file_exists($chunk_file)) {
  259.                 header("HTTP/1.0 200 Ok");
  260.                 die;
  261.             } else {
  262.                 header("HTTP/1.0 404 Not Found");
  263.                 die;
  264.             }
  265.         }
  266.  
  267.  
  268. // loop through files and move the chunks to a temporarily created directory
  269.         if (!empty($_FILES)) foreach ($_FILES as $file) {
  270.  
  271.             // check the error status
  272.             if ($file['error'] != 0) {
  273.                 //@TODO RARES LOG THIS
  274.                 log_message('error', 'V05:' . $file['error'] . ' in file ' . $_POST['resumableFilename']);
  275. //                $this->_log('error ' . $file['error'] . ' in file ' . $_POST['resumableFilename']);
  276.                 continue;
  277.             }
  278.  
  279.             // init the destination file (format <filename.ext>.part<#chunk>
  280.             // the file is stored in a temporary directory
  281.             if (isset($_POST['resumableIdentifier']) && trim($_POST['resumableIdentifier']) != '') {
  282.                 $temp_dir = $tempPath . $_POST['resumableIdentifier'];
  283.             }
  284.             $dest_file = $temp_dir . '/' . $_POST['resumableFilename'] . '.part' . $_POST['resumableChunkNumber'];
  285. //            print_r($dest_file); die;
  286.             // create the temporary directory
  287.             if (!is_dir($temp_dir)) {
  288.                 umask(0002);
  289.                 if (!mkdir($temp_dir, 0777, true)) {
  290.                     log_message('error', 'V06: Nu s-a putut crea directorul ' . $temp_dir);
  291.                 }
  292.             }
  293.             // move the temporary file
  294.             if (!move_uploaded_file($file['tmp_name'], $dest_file)) {
  295.                 log_message('error', "V06: Nu s-a putut muta fisierul sursa: {$file['tmp_name']} in locatia $dest_file");
  296. //                $this->_log('Error saving (move_uploaded_file) chunk ' . $_POST['resumableChunkNumber'] . ' for file ' . $_POST['resumableFilename']);
  297.             } else {
  298.                 // check if all the parts present, and create the final destination file
  299.                 $this->createFileFromChunks($temp_dir, $_POST['resumableFilename'], $_POST['resumableChunkSize'], $_POST['resumableTotalSize'], $_POST['resumableTotalChunks'], $originalPath, $encodesPath, $torrentsPath);
  300.             }
  301.         }
  302.  
  303.     }
  304.  
  305. //
  306. //    private function _log($str)
  307. //    {
  308. //
  309. //        // log to the output
  310. //        $log_str = date('d.m.Y') . ": {$str}\r\n";
  311. //        echo $log_str;
  312. //
  313. //        // log to file
  314. //        if (($fp = fopen('upload_log.txt', 'a+')) !== false) {
  315. //            fputs($fp, $log_str);
  316. //            fclose($fp);
  317. //        }
  318. //    }
  319.  
  320.     /**
  321.      *
  322.      * Delete a directory RECURSIVELY
  323.      * @param string $dir - directory path
  324.      * @link http://php.net/manual/en/function.rmdir.php
  325.      */
  326.     private function rrmdir($dir)
  327.     {
  328.         if (is_dir($dir)) {
  329.             $objects = scandir($dir);
  330.             foreach ($objects as $object) {
  331.                 if ($object != "." && $object != "..") {
  332.                     if (filetype($dir . "/" . $object) == "dir") {
  333.                         $this->rrmdir($dir . "/" . $object);
  334.                     } else {
  335.                         unlink($dir . "/" . $object);
  336.                     }
  337.                 }
  338.             }
  339.             reset($objects);
  340.             rmdir($dir);
  341.         }
  342.     }
  343.  
  344.     /**
  345.      *
  346.      * Check if all the parts exist, and
  347.      * gather all the parts of the file together
  348.      * @param string $temp_dir - the temporary directory holding all the parts of the file
  349.      * @param string $fileName - the original file name
  350.      * @param string $chunkSize - each chunk size (in bytes)
  351.      * @param string $totalSize - original file size (in bytes)
  352.      */
  353.     private function createFileFromChunks($temp_dir, $fileName, $chunkSize, $totalSize, $total_files, $originalPath, $encodesPath, $torrentsPath)
  354.     {
  355.  
  356.         // count all the parts of this file
  357.         $total_files_on_server_size = 0;
  358.         $temp_total = 0;
  359. //        var_dump($this->rrmdir($temp_dir)); die;
  360.         foreach (scandir($temp_dir) as $file) {
  361.             $temp_total = $total_files_on_server_size;
  362.             $tempfilesize = filesize($temp_dir . '/' . $file);
  363.             $total_files_on_server_size = $temp_total + $tempfilesize;
  364.         }
  365.  
  366. //        print_r($total_files_on_server_size); die;
  367.         // check that all the parts are present
  368.         // If the Size of all the chunks on the server is equal to the size of the file uploaded.
  369.         if ($total_files_on_server_size >= $totalSize) {
  370.             // create the final destination file
  371.             if (($fp = fopen($originalPath . $fileName, 'w')) !== false) {
  372.  
  373.                 for ($i = 1; $i <= $total_files; $i++) {
  374.                     fwrite($fp, file_get_contents($temp_dir . '/' . $fileName . '.part' . $i));
  375. //                    $this->_log('writing chunk ' . $i);
  376.                 }
  377.                 fclose($fp);
  378. //                get new filename, insert in db;
  379. //                $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  380.                 $data = $this->setFilename($fileName, $originalPath);
  381.                 $this->encodeVideo($data, $originalPath, $encodesPath, $torrentsPath);
  382.             } else {
  383.                 return false;
  384.             }
  385.  
  386.             // rename the temporary directory (to avoid access from other
  387.             // concurrent chunks uploads) and than delete it
  388.             if (rename($temp_dir, $temp_dir . '_UNUSED')) {
  389.                 $this->rrmdir($temp_dir . '_UNUSED');
  390.             } else {
  391.                 $this->rrmdir($temp_dir);
  392.             }
  393.         }
  394.  
  395.     }
  396.  
  397.     //Set Filename for uploaded file.
  398.     public function setFilename($fileName = NULL, $originalPath = NULL)
  399.     {
  400.         if (!isset($fileName) || !isset($originalPath)) {
  401.             log_message('error', "V07: $fileName sau $originalPath nu este setat ");
  402.             return FALSE;
  403.         }
  404.         $userId = $this->parent();
  405.  
  406.         if (!$userId) {
  407.             log_message('error', "V08:\$this->parent() returned invalid user id");
  408.             return FALSE;
  409.         }
  410.         $lastId = $this->videos_model->getNextIdVideos();
  411.  
  412.         $stripName = preg_replace('/\s+/', '_', $fileName);
  413.  
  414.         //Generate new name
  415.         $data['newFileName'] = "{$userId}_{$lastId}_$stripName";
  416.  
  417.         //Rename the file
  418.         if (!rename($originalPath . '/' . $fileName, $originalPath . '/' . $data['newFileName'])) {
  419.             log_message('error', "V09: Error renaming file $originalPath/$fileName in  {$originalPath}/{$data['newFileName']}");
  420.         }
  421.  
  422.         //Get mediainfo for file
  423.         $data['details'] = $this->getMediainfo($data['newFileName'], $originalPath);
  424.  
  425.         if (empty($data['details'])) {
  426.             log_message('error', "V12: Empty media info for video");
  427.             return FALSE;
  428.  
  429.         }
  430.        
  431.         //Insert mediainfo in DB
  432.         $this->client_db->insert('videos', array(
  433.             'client_id' => $userId,
  434.             'filename' => $data['newFileName'],
  435.             'duration_seconds' => $data['details']['duration_seconds'],
  436.             'duration_milliseconds' => $data['details']['duration_milliseconds'],
  437.             'width' => $data['details']['width'],
  438.             'height' => $data['details']['height'],
  439.             'added' => date('Y-m-d H:i:s'),
  440.             'filesize' => $data['details']['filesize']
  441.         ));
  442.         $data['torrent_insert_id'] = $this->client_db->insert_id();
  443. //        $json['filename'] = $data['newFileName'];
  444. //        $json['id'] = $data['torrent_insert_id'];
  445. //        echo json_encode($json);
  446.         return $data;
  447.     }
  448.  
  449.  
  450.     public function getMediainfo($fileName, $originalPath)
  451.     {
  452.         if (!empty($fileName)) {
  453.  
  454.             $ssh = new Net_SSH2($this->mbHost);
  455.             if (!$ssh->login($this->mbUsername, $this->mbPassword)) {
  456.                 log_message('error', "V10:Nu s-a putut realiza conectiunea la SSH on host {$this->mbHost}");
  457.                 return FALSE;
  458.             }
  459.  
  460.             $filePath = $originalPath . $fileName;
  461.  
  462.             $data['duration_seconds'] = ceil($ssh->exec("/usr/bin/mediainfo --Inform=\"Video;%Duration%\" $filePath") / 1000);
  463.             $data['duration_milliseconds'] = $ssh->exec("/usr/bin/mediainfo --Inform=\"Video;%Duration%\" $filePath");
  464.             $data['width'] = $ssh->exec("/usr/bin/mediainfo --Inform=\"Video;%Width%\" $filePath");
  465.             $data['height'] = $ssh->exec("/usr/bin/mediainfo --Inform=\"Video;%Height%\" $filePath");
  466.             $data['filesize'] = filesize($filePath);
  467.  
  468.             return $data;
  469.         } else {
  470.             log_message('error', 'V11: Empty $fileName');
  471.             return FALSE;
  472.         }
  473.  
  474.     }
  475.  
  476.     //Get file extension by mime type
  477.     private function getFileExtension($fileName)
  478.     {
  479.         //Define mime type extensions
  480.         $fileTypeExtensions = array(
  481.             "video/x-matroska" => "mkv",
  482.  
  483.             "application/x-troff-msvideo" => "avi",
  484.             "video/avi" => "avi",
  485.             "video/msvideo" => "avi",
  486.             "video/x-msvideo" => "avi",
  487.  
  488.             "video/mpeg" => "mpeg",
  489.  
  490.             "video/quicktime" => "mov",
  491.  
  492.             "video/mp4" => "mp4",
  493.  
  494.             "video/x-flv" => "flv",
  495.  
  496.             "video/x-m4v" => "m4v",
  497.  
  498.  
  499.         );
  500.         $mimeType = mime_content_type($fileName);
  501.  
  502.         if (isset($fileTypeExtensions[$mimeType])) {
  503.             $ext = $fileTypeExtensions[$mimeType];
  504.             return $ext;
  505.         } else {
  506.             return FALSE;
  507.         }
  508.  
  509.  
  510.     }
  511.  
  512.  
  513.     private function encodeVideo($data, $originalPath, $encodesPath, $torrentsPath)
  514.     {
  515.         $fileName = $data['newFileName'];
  516.  
  517.         //Local filepath
  518.         $file = $originalPath . '/' . $fileName;
  519.  
  520.         $ext = $this->getFileExtension($file);
  521.  
  522.         if (empty($ext)) {
  523.             log_message('error', 'V14: Mime Type not allowed.');
  524.             DIE('INVALID MIME TYPE');
  525.         }
  526.  
  527.         //Path with original files filepath
  528.         $remote_file_path = "/home/mediabox-converter/ftp/$fileName";
  529.  
  530.         //Connect to SSH
  531.         $ssh = new Net_SSH2($this->mbConverterHost);
  532.         if (!$ssh->login($this->mbConverterUsername, $this->mbConverterPassword)) {
  533.             log_message('error', 'V15: Cannot connect to SSH on server ' . $this->mbConverterHost);
  534.             return FALSE;
  535.         }
  536.  
  537.         //Connect to SFTP
  538.         $conn_id = ftp_connect($this->mbConverterHost);
  539.         $ftp_connect = ftp_login($conn_id, $this->mbConverterUsername, $this->mbConverterPassword);
  540.  
  541.         if(!$ftp_connect) {
  542.             log_message('error', "V16: Nu s-a putut conecta la serverul de ftp la adresa {$this->mbConverterHost}");
  543.         }
  544.  
  545.         //UPLOAD FILE TO ENCODER SERVER
  546.         if (ftp_put($conn_id, $remote_file_path, $file, FTP_BINARY)) {
  547.             ftp_close($conn_id);
  548.  
  549.             //Save encode command based on video extension/container
  550.             switch ($ext) {
  551.                 case 'mkv':
  552.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName -codec copy /home/mediabox-converter/encodes/$fileName.mp4";
  553.                     break;
  554.                 case 'avi':
  555.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName -c:v libx264 -c:a copy /home/mediabox-converter/encodes/$fileName.mp4";
  556.                     break;
  557.                 case 'mpeg':
  558.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName /home/mediabox-converter/encodes/$fileName.mp4";
  559.                     break;
  560.                 case 'mov':
  561.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName -c copy /home/mediabox-converter/encodes/$fileName.mp4";
  562.                     break;
  563.                 case 'flv':
  564.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName -codec copy /home/mediabox-converter/encodes/$fileName.mp4";
  565.                     break;
  566.                 case 'm4v':
  567.                     $sshCommand['encodeVideo'] = "/usr/bin/avconv -i /home/mediabox-converter/ftp/$fileName -strict -2 /home/mediabox-converter/encodes/$fileName.mp4";
  568.                     break;
  569.             }
  570.  
  571.             if (isset($sshCommand['EncodeVideo'])) { /* If video is not MP4 -> Original MP4 files skips this step. */
  572.                 $sshOutput = ">> /home/mediabox-converter/logs/$fileName.log 2>&1"; /* ssh command to output stderr and stdout in file */
  573.                 //Create log file on Convertor Server
  574.                 $ssh->exec("touch /home/mediabox-converter/logs/$fileName.log"); /* Create log file to log all output of encode */
  575.                 $ssh->setTimeout(0); /* Wait until command finishes before continuing */
  576.                 $ssh->exec($sshCommand['EncodeVideo'] . $sshOutput); /* Encode Video and print output to log file */
  577.                 $ssh->setTimeout(0); /* Wait until command finishes before continuing */
  578.                 $ssh->exec("scp /home/mediabox-converter/encodes/$fileName.mp4 {$this->mbUsername}@{$this->mbHost}:$encodesPath$fileName.mp4 "); /* Move encode back to GUI */
  579.             } else {
  580.                 copy($originalPath . $fileName, $encodesPath . "$fileName.mp4"); /* Copy encode from Original folder to Encodes folder */
  581.             }
  582.  
  583.             //ENCODE DONE. ENCODED FILE MOVED TO GUI !!!
  584.  
  585.             //MOVE ENCODE TO TRACKER
  586.  
  587.             //Tracker Connection
  588.             $ftpConnectionTracker = ftp_connect($this->mbTrackerHost);
  589.             $ftpConnectionTrackerResult = ftp_login($ftpConnectionTracker, $this->mbTrackerUsername, $this->mbTrackerPassword);
  590.  
  591.             if (!$ftpConnectionTrackerResult) {
  592.                 log_message('error', "Nu s-a putut face conexiunea FTP la {$this->mbTrackerHost}.");
  593.             }
  594.  
  595.             //Check if remote encode folder exists. If not, create it
  596.             if (@ftp_chdir($ftpConnectionTracker, "$this->trackerFilePath/client_{$this->parent()}") === false) {
  597.                 ftp_mkdir($ftpConnectionTracker, "$this->trackerFilePath/client_{$this->parent()}"); //directory doesn't exist - so make it
  598.             }
  599.  
  600.             //Check if remote torrent folder exists. If not, create it
  601.             if (@ftp_chdir($ftpConnectionTracker, "$this->trackerTorrentPath/client_{$this->parent()}") === false) {
  602.                 ftp_mkdir($ftpConnectionTracker, "$this->trackerTorrentPath/client_{$this->parent()}"); //directory doesn't exist - so make it
  603.             }
  604.  
  605.  
  606.             //Get tracker's path to encode file
  607.             $trackerPathToFile = "$this->trackerFilePath/client_{$this->parent()}/$fileName.mp4";
  608.  
  609. //            print_r("$this->trackerFilePath/client_{$this->parent()}/$fileName.mp4"); die;
  610.             if (ftp_put($ftpConnectionTracker, $trackerPathToFile, "$encodesPath$fileName.mp4", FTP_BINARY)) {
  611.  
  612.                 $ssh = new Net_SSH2($this->mbTrackerHost);
  613.                 if (!$ssh->login($this->mbTrackerUsername, $this->mbTrackerPassword)) {
  614.                     log_message('error', "Nu s-a putut face conexiunea SSH la {$this->mbTrackerHost}.");
  615.                     return FALSE;
  616.                 }
  617.  
  618.                 //Get torrent filename
  619.                 $torrentFilename = "$fileName.mp4.torrent";
  620.                 $torrentSeederFilename = "$fileName.mp4_seeder.torrent";
  621.  
  622.                 //Get tracker's path to torrent file
  623.                 $trackerPathToTorrent = "/home/mediabox-tracker/torrents/client_{$this->parent()}/$torrentFilename";
  624.                 $trackerPathToTorrentSeeder = "/home/mediabox-tracker/torrents/client_{$this->parent()}/$torrentSeederFilename";
  625.  
  626.                 //create .torrent file
  627.                 $ssh->setTimeout(0);
  628.                 $stream = $ssh->exec("transmission-create -o $trackerPathToTorrent -s 1024KiB -c '$fileName' -t http://{$this->mbTrackerHost}/tracker/announce.php?passkey= $trackerPathToFile");
  629.                 $ssh->setTimeout(0);
  630.                 $stream = $ssh->exec("transmission-create -o $trackerPathToTorrentSeeder -s 1024KiB -c '$fileName' -t http://{$this->mbTrackerHost}/tracker/announce.php?passkey=098f6bcd4621d373cade4e832627b4f0 $trackerPathToFile");
  631.                 $ssh->setTimeout(0);
  632.                 $magnetLink = $ssh->exec("transmission-show -m $trackerPathToTorrent");
  633.  
  634.                 if (!$this->videos_model->updateMagnetDB($data['torrent_insert_id'], $magnetLink)) {
  635.                     log_message("error", "Nu s-a putut ");
  636.                     return FALSE;
  637.                 }
  638.  
  639.                 //Sa trimit la RabbitMQ tuturor cutiilor magnetul cu passkeyul fiecaruia.
  640. //            if (!$this->sendTorrentAll($magnetLink)) {
  641. //                die('eroare: nu s-a trimis magnet torrentul cutiilor;');
  642. //            }
  643.  
  644.                 if (!is_dir($torrentsPath)) {
  645.                     umask(0002);
  646.                     mkdir($torrentsPath, 0777, true);
  647.                 }
  648. //                print_r($torrentsPath . $torrentSeederFilename);
  649. //                print_r(" -- " . $trackerPathToTorrentSeeder); die;
  650. //                var_dump(ftp_get($ftpConnectionTracker, $torrentsPath . $torrentSeederFilename, $trackerPathToTorrentSeeder, FTP_BINARY)); die;
  651.                 if (ftp_get($ftpConnectionTracker, $torrentsPath . $torrentSeederFilename, $trackerPathToTorrentSeeder, FTP_BINARY)) {
  652.  
  653.                     //Move .torrent file and movie to mediabox-seeders
  654.                     ftp_close($ftpConnectionTracker);
  655.                     $this->initSeeders($fileName . '.mp4', $encodesPath, $torrentsPath . $torrentSeederFilename);
  656.                 }
  657.             }
  658.  
  659.  
  660.         } else {
  661.             log_message('error', "V17:Nu s-a putut pune fisierul pe FTP conn_id=$conn_id, remote_file=$remote_file_path, file=$file");
  662.             echo "There was a problem while uploading $file\n";
  663.         }
  664.  
  665.  
  666.     }
  667.  
  668.     //Init seeders to start seeding
  669.     private function initSeeders($fileName, $encodesPath, $torrentsPathToFileGUI)
  670.     {
  671.         $data = $this->getSeeders();
  672. //        print_r($trackerPathToTorrentSeeder); die;
  673.         if ($data) {
  674.             foreach ($data as $seeder) {
  675.                 $ftpConnectionSeeder = ftp_connect($seeder['hostname']);
  676.                 $ftpConnectionSeederResult = ftp_login($ftpConnectionSeeder, $seeder['username'], $seeder['password']);
  677.                 if (ftp_put($ftpConnectionSeeder, "/home/{$seeder['username']}/Downloads/$fileName", $encodesPath . $fileName, FTP_BINARY)) {
  678.                     ftp_put($ftpConnectionSeeder, "/home/{$seeder['username']}/torrents/$fileName.torrent", $torrentsPathToFileGUI, FTP_BINARY);
  679.                 }
  680.             }
  681.         }
  682.  
  683.         ftp_close($ftpConnectionSeeder);
  684.     }
  685.  
  686.     private function getSeeders()
  687.     {
  688.         if ($data = $this->videos_model->getSeeders()) {
  689.             return $data;
  690.         }
  691.         return FALSE;
  692.     }
  693.  
  694.     public function rename_video_ajax()
  695.     {
  696.         $this->auth->restrict($this->permissionEdit);
  697.  
  698.         if ($this->videos_model->renameVideo($this->input->post('id'), $this->input->post('videos_name'))) {
  699.             echo TRUE;
  700.         }
  701.         echo FALSE;
  702.  
  703.     }
  704.  
  705.     public function delete_video_ajax()
  706.     {
  707.         $this->auth->restrict($this->permissionDelete);
  708.  
  709.         if ($this->videos_model->deleteVideo($this->input->post('id'))) {
  710.             echo TRUE;
  711.         }
  712.         echo FALSE;
  713.  
  714.     }
  715.  
  716.  
  717.     public function createFolders($tempPath, $originalPath, $encodesPath, $torrentsPath, $logsPath)
  718.     {
  719.         if (!is_dir($tempPath)) {
  720.             umask(0002);
  721.             if (!mkdir($tempPath, 0777, true)) {
  722.                 log_message('error', 'Nu s-a putut crea folderul cu calea ' . $tempPath);
  723.             }
  724.         }
  725.         if (!is_dir($originalPath)) {
  726.             umask(0002);
  727.             if (!mkdir($originalPath, 0777, true)) {
  728.                 log_message('error', 'V01: Nu s-a putut crea folderul cu calea ' . $tempPath);
  729.             }
  730.         }
  731.         if (!is_dir($encodesPath)) {
  732.             umask(0002);
  733.             if (!mkdir($encodesPath, 0777, true)) {
  734.                 log_message('error', 'V02: Nu s-a putut crea folderul cu calea ' . $tempPath);
  735.             }
  736.         }
  737.         if (!is_dir($torrentsPath)) {
  738.             umask(0002);
  739.             if (!mkdir($torrentsPath, 0777, true)) {
  740.                 log_message('error', 'V03: Nu s-a putut crea folderul cu calea ' . $tempPath);
  741.             }
  742.         }
  743.  
  744.         if (!is_dir($logsPath)) {
  745.             umask(0002);
  746.             if (!mkdir($logsPath, 0777, true)) {
  747.                 log_message('error', 'V04: Nu s-a putut crea folderul cu calea ' . $tempPath);
  748.             }
  749.         }
  750.     }
  751.  
  752. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement