Skip to content

Instantly share code, notes, and snippets.

Created December 31, 2014 18:54
Show Gist options
  • Select an option

  • Save anonymous/cad438c29505a56ee568 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/cad438c29505a56ee568 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Dec 31, 2014.
    364 changes: 364 additions & 0 deletions sort.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,364 @@
    #!/usr/bin/php
    <?php
    echo "\r \r"; // if you have executed this with the php CLI (php filename), we remove the shebang
    /*
    The MIT License (MIT)
    Copyright (c) 2014-2015 Daniel Troger
    Permission is hereby granted, free of charge, to any person obtaining a copy of
    this software and associated documentation files (the "Software"), to deal in
    the Software without restriction, including without limitation the rights to
    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
    the Software, and to permit persons to whom the Software is furnished to do so,
    subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
    FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
    COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    ----------------------------------------------------------------------------
    Grab some video files from a CD / DVD which have the time / date format yymmdd in the file name and sort them into $HOME/Videos/yyyy/mm/dd.
    Has lots of checks, checks if the medium is already mounted and mounts it otherwise, saves a nice log to $HOME/Videos/dvd.log, asks for overriding, checks if the filesize is the same of the copied and copying file, calculates average speed, displays copying percentage, takes the time to copy / file, has colorised output displays file size and maybe some things more :).
    Maybe uploading screenshot when I get better internet.
    */

    // config

    define("colorize",true);
    define("home",dirfix(getenv("HOME")));
    define("target",home . "Videos");
    define("source","%c"); // %c = cdrom mountpoint, mounting if not mounted
    define("unmount",true); // unmount after successfull copying when mounted by this script ?
    define("cdrom","/dev/cdrom||/dev/sr0"); // seperate multiple posibilities with ||
    define("cdtype","udf"); // cd type to check for when traversing mountpoints
    define("ftype","MPG"); // file type to search for
    define("block",1048576); // blocksize to use when copying
    date_default_timezone_set("Europe/Stockholm");

    // internal variables, do not change except the filename of the logfile.
    $target = dirfix(target);
    $log = fopen($target . "dvd.log","a");
    $UID = posix_getuid();
    $devices = explode("||",cdrom);
    $mountpoint = false;
    $blk_dev = false;
    $blank = NULL; for($aio = 0; $aio < 120; $aio++) $blank .= " ";

    if(!$log) error("Couldn't open log.");

    // cdrom checks & mounter
    $exists = false;
    foreach($devices as $device)
    {
    if(file_exists($device))
    {
    $blk_dev = $device;
    }
    }
    if(!$blk_dev) error("Can't find the block cdrom device. Please check that " . str_replace("||"," or ",cdrom) . " exists or update the config");
    succ("Found block device specified in config.");

    $m = mnts();
    foreach($m as $mount)
    {
    if($mount['type'] == cdtype)
    {
    if($mount['block_device'] == $blk_dev)
    {
    $mountpoint = $mount['mountpoint'];
    succ("Found cdrom device {$blk_dev} mounted at " . $mountpoint);
    }
    else
    {
    warn("A device which probaly is a cdrom has been found, but not one of the block devices you specified in the config.");
    }
    }
    }

    if(!$mountpoint)
    {
    info("Couldn't find any mounted CD device. Mounting it myself.");
    if($UID != 0) error("Can't mount without being root.");
    p_log("UID = {$UID}, continuing...");
    $mpoint = dirfix(sys_get_temp_dir()) . "cdrom" . rand(1,10);
    if(!is_dir($mpoint)) mkdir($mpoint);
    $mcmd = "mount -t " . cdtype . " " . $blk_dev . " " . $mpoint;
    shell($mcmd);
    $f = false;
    foreach(mnts() as $point)
    {
    if($point['mountpoint'] == $mpoint)
    {
    $f = true;
    }
    }
    if($f)
    {
    succ("Successfully mounted " . $blk_dev . " at " . $mpoint);
    $mountpoint = $mpoint;
    }
    else
    {
    error("Something went wrong with mounting " . $blk_dev);
    }
    }

    // every shit is passed now and the cd must be mounted at $mountpoint

    $mountpoint = dirfix($mountpoint);
    $asterixd = $mountpoint . "*.";
    $fn1 = $asterixd . strtolower(ftype);
    $fn2 = $asterixd . strtoupper(ftype);
    $files1 = glob($fn1);
    $files2 = glob($fn2);
    $movies= array_merge($files1,$files2);

    foreach($movies as $movie)
    {
    $n = basename($movie);
    $b = ext($n,true)[1];
    $year = substr($b,0,2);
    $month = substr($b,2,2);
    $day = substr($b,4,2);
    $y = (int) $year;
    if($y > date("y"))
    {
    $year = "19" . $year;
    }
    else
    {
    $year = "20" . $year;
    }
    $yd = dirfix($target . $year);
    cdir($yd);
    $md = dirfix($yd . $month);
    cdir($md);
    $dd = dirfix($md . $day);
    cdir($dd);
    $o = $dd . $n;
    $s = filesize($movie);
    $size = formatsize($s);
    $cont = true;
    $ow = false;
    if(file_exists($o))
    {
    if(filesize($o) == $s)
    {
    $m = "File {$o} already exists and has the same size as {$movie} ({$size}), shall we override it anyways ? [y/n]: ";
    }
    else
    {
    $m = "File {$o} already exists, shall we override it ? ({$size}) [y/n]: ";
    }
    echo colorize ? "\033[33m{$m}\033[0m": $m;
    p_log("Prompting if we shall override {$o} with {$movie}...");
    $i = fopen("php://stdin","r");
    $l = fgets($i);
    fclose($i);
    $l = substr($l,0,-1);
    $l = strtolower($l);
    p_log("User response: {$l}");
    if($l != "y")
    {
    $cont = false;
    info("Not overwriting.");
    }
    else
    {
    $ow = true;
    }
    }
    if($cont)
    {
    if($ow)
    {
    $msg = "Overriding {$o} with {$movie}";
    }
    else
    {
    $msg = "Copying {$n} to {$o}...";
    }
    echo colorize ? "\033[33m{$msg} ({$size})\033[0m\r": $msg . " ({$size})\r";
    p_log($msg);
    $h = fopen($movie,"r");
    $oh = fopen($o,"w");
    $pos = 0;
    $pchunk = $s / 100;
    $t1 = time();
    while(!feof($h))
    {
    echo $blank . "\r";
    if($pos == 0)
    {
    $m = "{$msg} (0 Byte of {$size}, 0%)";
    }
    else
    {
    $percentage = round($pos / $pchunk,2);
    $copied = formatsize($pos);
    $tss = time()-$t1; // time since start
    $speed = $tss == 0 ? "0 Bytes" : formatsize($pos/$tss);
    $m = "{$msg} ({$copied} of {$size}, {$speed}/s, {$percentage}%)";
    }
    echo colorize ? "\033[33m{$m}\033[0m\r": $m . "\r";
    fwrite($oh,fread($h,block));
    $pos += block;
    }
    $t2 = time();
    fclose($h);
    fclose($oh);
    echo $blank . "\r";
    if(file_exists($o))
    {
    $s1 = filesize($o);
    $s2 = filesize($movie);
    $tss = $t2-$t1;
    if($s1 != $s2) warn("Size missmatch between files {$o} and {$movie} ({$s1} != {$s2})! The target file may be corrupt.");
    succ("Successfully copied {$movie} to {$o}, {$size} in " . $tss . " seconds.");
    }
    else
    {
    warn("Something went wrong that {$n} couldn't be copied :(");
    }
    }
    }

    succ("All files were successfully copied. Exiting...");

    // exit
    error(NULL,1);

    // functions
    function dirfix($dir)
    {
    $a = substr($dir,-1) == DIRECTORY_SEPARATOR ? $dir : $dir . DIRECTORY_SEPARATOR;
    return $a;
    }

    // log functions
    function info($msg, $newline = PHP_EOL)
    {
    p_log($msg);
    echo colorize ? "\033[36m{$msg}\033[0m" . $newline : $msg . $newline;
    }
    function succ($msg, $newline = PHP_EOL)
    {
    p_log($msg);
    echo colorize ? "\033[32m{$msg}\033[0m" . $newline : $msg . $newline;
    }
    function warn($msg, $newline = PHP_EOL)
    {
    p_log($msg);
    echo colorize ? "\033[33mWarning: {$msg}\033[0m" . $newline : $msg . $newline;
    }
    function cdir($dir) // checks if a directory exists and creates it if it doesn't
    {
    if(!is_dir($dir))
    {
    mkdir($dir);
    info("Created directory {$dir}");
    }
    }
    function error($msg,$q = false)
    {
    $bt = debug_backtrace();
    $caller = array_shift($bt);
    $line = $caller['line'];
    if(!$q)
    {
    p_log("function error() called from line {$line}. Exiting with message: {$msg}",$msg);
    }
    else
    {
    p_log("Exiting.");
    }
    if(!$q) echo(colorize ? "\033[31mERROR: {$msg}\033[0m" . PHP_EOL : $msg . PHP_EOL);
    if(!empty($GLOBALS['mpoint']))
    {
    info("Unmounting CD if mounted myself due to coming exit.");
    $p = $GLOBALS['mountpoint'];
    shell("umount {$p}");
    rmdir($p);
    }
    fclose($GLOBALS['log']);
    exit;
    }
    function p_log($txt)
    {
    fwrite($GLOBALS['log'],date("Y-m-d H:i:s") . " " . $txt . PHP_EOL);
    }
    function shell($cmd)
    {
    $cmd = $cmd . " 2>&1";
    p_log("SHELL {$cmd}" . PHP_EOL);
    $sh = popen($cmd,"r");
    while(!feof($sh))
    {
    $buff = fread($sh,1024);
    echo $buff;
    fwrite($GLOBALS['log'],$buff);
    }
    pclose($sh);
    p_log("Shell exited.");
    }
    function mnts() // mount list
    {
    $out = Array();
    $mounts = file("/proc/mounts");
    foreach($mounts as $mount)
    {
    $mount = substr($mount,0,-1);
    $m = explode(" ",$mount);
    list($blk,$point,$type) = $m;
    $out[] = Array('block_device' => $blk,
    'mountpoint' => $point,
    'type' => $type);
    }
    return $out;
    }
    function formatsize($size)
    {
    if($size < 1) return false;
    if($size > 1024 * 1024 * 1024)
    {
    return round($size / 1024 / 1024 / 1024,2) . " GiB";
    }
    elseif($size > 1024 * 1024)
    {
    return round($size / 1024 / 1024,2) . " MiB";
    }
    elseif($size > 1024)
    {
    return round($size / 1024,2) . " KiB";
    }
    elseif($size < 1024)
    {
    return "{$size} Bytes";
    }
    }
    function ext($file,$split = false)
    {
    $extension = explode(".",$file);
    $asize = sizeof($extension);
    $ext = strtolower($extension[$asize-1]);
    if(!$split)
    {
    return $ext;
    }
    else
    {
    unset($extension[$asize-1]);
    return array($ext,implode(".",$extension));
    }
    }