1
0
Zachary Kotlarek 12 лет назад
Родитель
Сommit
133992a928
4 измененных файлов с 921 добавлено и 0 удалено
  1. 1 0
      .gitignore
  2. 463 0
      opendrive.php
  3. 335 0
      scan.php
  4. 122 0
      upload.php

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+.secrets

+ 463 - 0
opendrive.php

@@ -0,0 +1,463 @@
+<?php
+
+# Debug
+$DEBUG = 0;
+if ($_ENV['DEBUG']) {
+	$DEBUG = intval($_ENV['DEBUG']);
+	if (!$DEBUG) {
+		$DEBUG = 1;
+	}
+}
+
+# On-disk config
+require_once '.secrets';
+
+# Config
+global $API_BASE;
+global $API_VERSION;
+global $API_CHUNK_SIZE;
+$API_BASE = 'https://dev.opendrive.com/api/v1';
+$API_VERSION = 10;
+$API_CHUNK_SIZE = 100 * 1024 * 1024;
+
+# PHP version support
+if (!function_exists('curl_file_create')) {
+	function curl_file_create($filename, $mimetype = '', $postname = '') {
+		return '@' . $filename . ';filename=' .
+		($postname ?: basename($filename)) .
+		($mimetype ? ';type=' . $mimetype : '');
+	}
+}
+
+# Open the DB connection
+function dbOpen() {
+	global $DB_STRING;
+	global $DB_USER;
+	global $DB_PASSWD;
+	try {
+		$dbh = new PDO($DB_STRING, $DB_USER, $DB_PASSWD);
+	} catch (PDOException $e) {
+		die('DB error: ' . $e->getMessage() . "\n");
+	}
+	return $dbh;
+}
+
+# Cleanup a path for better matching at OpenDrive
+function pathCleanup($path) {
+	$path = preg_replace('/\/+$/', '', $path);
+	$path = preg_replace('/^\/+/', '', $path);
+	return $path;
+}
+
+# Return the clean parent path of a provided path
+function parentPath($path) {
+	return dirname(pathCleanup($path));
+}
+
+# Return the clean base name of a provided path
+function basePath($path) {
+	return basename(pathCleanup($path));
+}
+
+function curlPostRaw($url, $data, $header = NULL) {
+	global $API_BASE;
+	global $CA_PATH;
+	global $DEBUG;
+
+	# Setup cURL
+	$ch = curl_init($API_BASE . $url);
+	curl_setopt_array($ch, array(
+		CURLOPT_CAINFO => $CA_PATH,
+		CURLOPT_POST => true,
+		CURLOPT_RETURNTRANSFER => true,
+		CURLOPT_POSTFIELDS => $data
+	));
+	if ($DEBUG >= 3) {
+		curl_setopt($ch, CURLOPT_VERBOSE, true);
+	}
+	if ($header != NULL) {
+		if (!is_array($header)) {
+			$header = array($header);
+		}
+		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
+	}
+
+	# Send the request
+	if ($DEBUG >= 2) {
+		echo 'Request: ' . $url . "\n";
+		print_r($data);
+		echo "\n";
+	}
+	$response = curl_exec($ch);
+
+	# Check for errors
+	if ($response === FALSE){
+	    die(curl_error($ch));
+	}
+
+	# Return
+	if ($DEBUG >= 4) {
+		echo "Response:\n";
+		print_r($response);
+	}
+	return($response);
+}
+
+# POST the provided data to OpenDrive
+function curlPost($url, $data) {
+	$data = json_encode($data);
+	$response = curlPostRaw($url, $data, 'Content-Type: application/json');
+	$responseData = json_decode($response, true);
+	if ($DEBUG >= 3) {
+		echo "Response Data:\n";
+		print_r($responseData);
+	}
+	return($responseData);
+}
+
+# GET from OpenDrive
+function curlGet($url) {
+	global $API_BASE;
+	global $CA_PATH;
+	global $DEBUG;
+
+	# Setup cURL
+	$ch = curl_init($API_BASE . $url);
+	curl_setopt_array($ch, array(
+		CURLOPT_CAINFO => $CA_PATH,
+		CURLOPT_RETURNTRANSFER => true
+	));
+	if ($DEBUG >= 3) {
+		curl_setopt($ch, CURLOPT_VERBOSE, true);
+	}
+
+	# Send the request
+	if ($DEBUG >= 2) {
+		echo 'Request: ' . $url . "\n";
+		print_r($data);
+		echo "\n";
+	}
+	$response = curl_exec($ch);
+
+	# Check for errors
+	if ($response === FALSE){
+	    die(curl_error($ch));
+	}
+
+	# Return
+	$responseData = json_decode($response, true);
+	return($responseData);
+}
+
+# Login to OD and return the SessionID
+function login() {
+	global $API_VERSION;
+	global $OD_USER;
+	global $OD_PASSWD;
+	$data = array(
+		'username' 	=> $OD_USER,
+		'passwd'	=> $OD_PASSWD,
+		'version'	=> $API_VERSION
+	);
+	$response = curlPost('/session/login.json', $data);
+
+	# Check the result
+	if ($response['SessionID']) {
+		return $response['SessionID'];
+	}
+	return false;
+}
+
+# Logout of OpenDrive
+function logout($session) {
+	$data = array(
+		'session_id'	=> $session
+	);
+	$response = curlPost('/session/logout.json', $data);
+
+	# Check the result
+	if ($response['result'] == 'true') {
+		return true;
+	}
+	return false;
+}
+
+# Return the ID of a folder
+function folderID($session, $path) {
+	$data = array(
+		'session_id'	=> $session,
+		'path'		=> $path
+	);
+	$response = curlPost('/folder/idbypath.json', $data);
+
+	# Check the result
+	if ($response['FolderId']) {
+		return($response['FolderId']);
+	}
+	return false;
+}
+
+# Find the parent ID for a given path
+function parentID($session, $path) {
+	$parent = parentPath($path);
+
+	$parentID = 0;
+	if ($parent != '.') {
+		$parentID = folderID($session, $parent);
+	}
+	return $parentID;
+}
+
+# Create a folder
+function mkFolder($session, $path) {
+	global $DEBUG;
+
+	# Find the parent ID (if any)
+	$parentID = parentID($session, $path);
+	if ($parentID === false) {
+		if ($DEBUG) {
+			echo 'Invalid parent for path: ' . $path . "\n";
+		}
+		return false;
+	}
+
+	# POST
+	$data = array(
+		'session_id'		=> $session,
+		'folder_name'		=> basePath($path),
+		'folder_sub_parent'	=> $parentID,
+		'folder_is_public'	=> 0
+	);
+	$response = curlPost('/folder.json', $data);
+
+	# Check the result
+	if ($response['FolderId']) {
+		return($response['FolderId']);
+	}
+	return false;
+}
+
+# Trash a folder
+function rmFolder($session, $path) {
+	$id = folderID($session, $path);
+	if (!$id) {
+		return false;
+	}
+
+	$data = array(
+		'session_id'	=> $session,
+		'folder_id'	=> $id
+	);
+	$response = curlPost('/folder/trash.json', $data);
+
+	# Check the result
+	if ($response['DirUpdateTime']) {
+		return true;
+	}
+	return false;
+}
+
+# Return the ID of a file
+function fileID($session, $path) {
+	$data = array(
+		'session_id'	=> $session,
+		'path'		=> $path
+	);
+	$response = curlPost('/file/idbypath.json', $data);
+
+	# Check the result
+	if ($response['FileId']) {
+		return($response['FileId']);
+	}
+	return false;
+}
+
+# Return all file metadata
+function fileInfo($session, $path) {
+	$id = fileID($session, $path);
+	if (!$id) {
+		return false;
+	}
+
+	# GET
+	$response = curlGet('/file/info.json/' . $session . '/' . $id);
+
+	# Check the result
+	if ($response['FileId']) {
+		return($response);
+	}
+	return false;
+}
+
+# Upload the provided file to the given path
+function fileUpload($session, $path, $file) {
+	global $DEBUG;
+	global $API_CHUNK_SIZE;
+
+	# Find the local file
+	$stat = @stat($file);
+	if ($stat === false) {
+		if ($DEBUG) {
+			echo 'Unable to stat: ' . $file . "\n";
+		}
+		return false;
+	}
+
+	# Find the parent ID
+	$parentID = parentID($session, $path);
+	if ($parentID === false) {
+		if ($DEBUG) {
+			echo 'No parent for path: ' . $path . "\n";
+		}
+		return false;
+	}
+
+	# Allocate
+	$data = array(
+		'session_id'	=> $session,
+		'folder_id'	=> $parentID,
+		'file_name'	=> basePath($path),
+		'file_size'	=> $stat['size']
+	);
+	$response = curlPost('/upload/create_file.json', $data);
+	$id = $response['FileId'];
+	if (!$id) {
+		if ($DEBUG) {
+			echo 'Unable to allocate: ' . $path . "\n";
+		}
+		return false;
+	}
+
+	# Open
+	$data = array(
+		'session_id'	=> $session,
+		'file_id'	=> $id,
+		'file_size'	=> $stat['size']
+	);
+	$response = curlPost('/upload/open_file_upload.json', $data);
+	$tmpPath = $response['TempLocation'];
+	if (!$tmpPath) {
+		if ($DEBUG) {
+			echo 'Unable to open: ' . $path . "\n";
+		}
+		return false;
+	}
+
+	# Split if needed
+	$tempDir = false;
+	$files = array();
+	if ($stat['size'] > $API_CHUNK_SIZE) {
+		if ($DEBUG) {
+			echo 'Splitting file: ' . $file . ' (' . $API_CHUNK_SIZE . '/' . $stat['size'] . ")\n";
+		}
+
+		# Create a temporary directory
+		$tempDir = trim(shell_exec('mktemp -d'));
+		if (!is_dir($tempDir)) {
+			echo "Unable to create temp directory\n";
+			return false;
+		}
+
+		# Split into chunk-sized parts
+		shell_exec('cd ' . escapeshellarg($tempDir) .
+			' && split -b ' . escapeshellarg($API_CHUNK_SIZE) . ' ' . escapeshellarg($file));
+
+		# Find all their paths
+		$fh = opendir($tempDir);
+		if (!$fh) {
+			echo 'Unable to open temp directory: ' . $tempDir . "\n";
+			return false;
+		}
+		while (($chunk = readdir($fh)) !== false) {
+			if (preg_match('/^x\w+$/', $chunk)) {
+				$files[] = $tempDir . '/' . $chunk;
+			}
+		}
+		unset($chunk);
+
+		# Cleanup
+		closedir($fh);
+		unset($fh);
+	} else {
+		$files[] = $file;
+	}
+
+	# Sort the list to ensure the chunks are uploaded in order
+	sort($files);
+
+	# Upload
+	$offset = 0;
+	foreach ($files as $chunk) {
+		if ($DEBUG > 1) {
+			echo 'Uploading chunk: ' . $chunk . "\n";
+		}
+
+		# Find the chunk size
+		$chunkStat = @stat($chunk);
+		if ($chunkStat === false) {
+			echo 'Unable to stat chunk: ' . $chunk . "\n";
+			return false;
+		}
+
+		# Setup cURL
+		$cfile = curl_file_create($chunk, 'application/octet-stream', basePath($file));
+		$data = array(
+			'session_id'	=> $session,
+			'file_id'	=> $id,
+			'temp_location'	=> $tmpPath,
+			'chunk_offset'	=> $offset,
+			'chunk_size'	=> $chunkStat['size'],
+			'file_data'	=> $cfile
+		);
+
+		# Upload
+		$response = curlPostRaw('/upload/upload_file_chunk.json', $data, 'Expect:');
+		if ($response) {
+			$response = json_decode($response, true);
+		}
+		if (!$response || $response['TotalWritten'] != $chunkStat['size']) {
+			echo 'Unable to upload: ' . $chunk . "\n";
+			return false;
+		}
+
+		# Remove chunks as we use them
+		if ($tempDir) {
+			unlink($chunk);
+		}
+
+		# Increment the offset
+		$offset += $chunkStat['size'];
+		unset($chunkStat);
+		unset($response);
+	}
+	unset($offset);
+
+	# Remove the temporary directory, if it exists
+	if ($tempDir && is_dir($tempDir)) {
+		rmdir($tempDir);
+	}
+	unset($tempDir);
+
+	# Close
+	$data = array(
+		'session_id'	=> $session,
+		'file_id'	=> $id,
+		'temp_location'	=> $tmpPath,
+		'file_time'	=> $stat['mtime'],
+		'file_size'	=> $stat['size']
+	);
+	$response = curlPost('/upload/close_file_upload.json', $data);
+
+	# Ignore 500 errors on close. It works anyway.
+	if ($response && !$response['DirUpdateTime']) {
+		if ($DEBUG) {
+			echo 'Unable to close: ' . $path . "\n";
+		}
+		return false;
+	}
+
+	# Return the file size on success
+	return $stat['size'];
+}
+
+?>

+ 335 - 0
scan.php

@@ -0,0 +1,335 @@
+#!/usr/local/bin/php
+<?php
+
+# Debug
+$DEBUG = false;
+if ($_ENV['DEBUG']) {
+	$DEBUG = true;
+}
+
+# Includes
+require_once 'opendrive.php';
+
+# Command-line parameters
+global $argc;
+global $argv;
+$SUB_DIR = '';
+if (($argc > 1) && (strlen($argv[1]) > 0)) {
+	$SUB_DIR = trim($argv[1]);
+}
+
+# Wait DELAY_DAYS before considering a file
+$DELAY_DAYS = 30;
+if (isset($_ENV['DELAY_DAYS'])) {
+	$DELAY_DAYS = $_ENV['DELAY_DAYS'];
+}
+
+# Allow local-only scanning
+$REMOTE = true;
+if (isset($_ENV['REMOTE'])) {
+	if (!$_ENV['REMOTE']) {
+		$REMOTE = false;
+	}
+}
+
+# Delete only if specified
+$DELETE = false;
+if ($_ENV['DELETE']) {
+	$DELETE = true;
+}
+
+# Build our local base path
+$VIDEO_DIR=$_ENV['HOME'] . '/bin/video';
+if (isset($_ENV['VIDEO_DIR'])) {
+	$VIDEO_DIR = $_ENV['VIDEO_DIR'];
+}
+$BASE_LOCAL='';
+if (isset($_ENV['BASE_LOCAL'])) {
+	$BASE_LOCAL = $_ENV['BASE_LOCAL'];
+} else {
+	$BASE_LOCAL = trim(shell_exec($VIDEO_DIR . '/mediaPath'));
+}
+
+# Allow usage with absolute local paths
+if (substr($SUB_DIR, 0, 1) == '/') {
+	$SUB_DIR = preg_replace('/^' . preg_quote($BASE_LOCAL, '/') . '\//', '', $SUB_DIR);
+}
+
+# Usage checks
+if (strlen($SUB_DIR) < 1 || $DELAY_DAYS < 1) {
+	die('Usage: ' . $argv[0] . " sub_directory\n");
+}
+
+# Sanity checks
+$LOCAL = $BASE_LOCAL . '/' . $SUB_DIR;
+if (!file_exists($LOCAL) || !is_dir($LOCAL)) {
+	die('Invalid local directory: ' . $LOCAL . "\n");
+}
+
+# Open the DB connection
+$dbh = dbOpen();
+
+# Look for files in the DB that no longer exist or have changed types
+$delete = $dbh->prepare('DELETE FROM files WHERE base = :base AND path = :path');
+$missing = $dbh->prepare('SELECT base, path, type FROM files');
+$missing->execute();
+while ($row = $missing->fetch(PDO::FETCH_ASSOC)) {
+	$trigger = false;
+	$file = $row['base'] . '/' . $row['path'];
+
+	if ($row['type'] == 'folder') {
+		# Ensure the path exists and is a folder
+		if (!is_dir($file)) {
+			echo 'Missing folder: ' . $file . "\n";
+			$trigger = true;
+		}
+	} else if ($row['type'] == 'ignored') {
+		# Silently delete missing ignored files of any type
+		if (!file_exists($file)) {
+			if ($DEBUG) {
+				echo 'Missing ignored file: ' . $file . "\n";
+			}
+			$trigger = true;
+		}
+	} else {
+		# Ensure the path exists and is a regular file
+		if (!is_file($file)) {
+			echo 'Missing file: ' . $file . "\n";
+			$trigger = true;
+		}
+	}
+
+	# Delete if global DELETE is enabled
+	if ($DELETE && $trigger) {
+		$delete->execute(array(':base' => $row['base'], ':path' => $row['path']));
+	}
+
+	unset($trigger);
+	unset($file);
+}
+unset($delete);
+
+# Grab the file list -- limit files by mtime, but include all directories
+$FIND=tempnam(sys_get_temp_dir(), 'scanLocal-find');
+exec('cd ' . escapeshellarg($BASE_LOCAL) . ' && find ' . escapeshellarg($SUB_DIR) .
+	' -type f -mtime +' . escapeshellarg($DELAY_DAYS) . ' > ' . escapeshellarg($FIND));
+exec('cd ' . escapeshellarg($BASE_LOCAL) . ' && find ' . escapeshellarg($SUB_DIR) .
+	' -type d >> ' . escapeshellarg($FIND));
+
+# Sort and injest
+exec('cat ' . escapeshellarg($FIND) . ' | sort ', $FILES);
+unlink($FIND);
+unset($FIND);
+
+# Loop through all the files we found
+$select = $dbh->prepare('SELECT base, path, type FROM files WHERE base = :base AND path = :path');
+$insert = $dbh->prepare('INSERT INTO files (base, path, type, mtime) VALUES (:base, :path, :type, now())');
+$check = $dbh->prepare('SELECT type, size, EXTRACT(EPOCH FROM mtime) AS mtime FROM files WHERE base = :base AND path = :path');
+$set_mtime = $dbh->prepare('UPDATE files SET mtime = now() WHERE base = :base AND path = :path');
+$set_size = $dbh->prepare('UPDATE files SET size = :size WHERE base = :base AND path = :path');
+$set_type = $dbh->prepare('UPDATE files SET type = :type WHERE base = :base AND path = :path');
+$check_hash = $dbh->prepare('SELECT hash, EXTRACT(EPOCH FROM hash_time) AS hash_time ' .
+	'FROM files WHERE base = :base AND path = :path AND ' .
+	'(hash_time IS NULL OR EXTRACT(EPOCH FROM hash_time) < :mtime)');
+$set_hash = $dbh->prepare('UPDATE files SET hash = :hash, hash_time = now() WHERE base = :base AND path = :path');
+foreach ($FILES as $file) {
+
+	# Construct the absolute path
+	$path = $BASE_LOCAL . '/' . $file;
+
+	# Pick a file type
+	$parts = pathinfo($path);
+	$EXT = strtolower($parts['extension']);
+	$NAME = strtolower($parts['filename']);
+	unset($parts);
+
+	$TYPE = 'other';
+	if (preg_match('/\/\.git(\/.*)?$/', $path)) {
+		$TYPE = 'ignored';
+	} else if (preg_match('/\/\._/', $path)) {
+		$TYPE = 'ignored';
+	} else if ($EXT == 'lastfindrecode' || $NAME == 'placeholder' || $EXT == 'plexignore') {
+		$TYPE = 'ignored';
+	} else if ($EXT == 'tmp' || $EXT == 'gitignore' || $EXT == 'ds_store' ||
+		preg_match('/^\.smbdelete/', $NAME) || preg_match('/\.mkv\.\w+$/', $file)) {
+			$TYPE = 'ignored';
+	} else if (preg_match('/^iTunes\/Album Artwork\/Cache/', $file)) {
+		$TYPE = 'ignored';		
+	} else if (is_dir($path)) {
+		$TYPE = 'folder';
+		if ($EXT == '' && $NAME == 'cmd') {
+			$TYPE = 'ignored';
+		}
+	} else if ($EXT == 'm4v' || $EXT == 'mkv' || $EXT == 'mp4' || $EXT == 'mov' ||
+		$EXT == 'vob' || $EXT == 'iso' || $EXT == 'avi') {
+			$TYPE = 'video';
+	} else if ($EXT == 'mp3' || $EXT == 'aac' || $EXT == 'm4a' || $EXT == 'm4b' ||
+		$EXT == 'm4p' || $EXT == 'wav') {
+			$TYPE = 'audio';
+	} else if ($EXT == 'epub' || $EXT == 'pdf') {
+		$TYPE = 'book';
+	} else if ($EXT == 'jpg' || $EXT == 'png') {
+		$TYPE = 'image';
+	} else if ($EXT == 'gz' || $EXT == 'zip' || $EXT == 'xz') {
+		$TYPE = 'archive';
+	} else if ($EXT == 'itc' || $EXT == 'itl' || $EXT == 'strings' || $EXT == 'itdb' ||
+		$EXT == 'plist' || $EXT == 'ipa' || $EXT == 'ini') {
+			$TYPE = 'database';
+	} else if ($EXT == 'clip' || $EXT == 'riff' || $EXT == 'nfo') {
+		$TYPE = 'metadata';
+	} else if ($EXT == 'webloc' || $NAME == 'skip' || $NAME == 'season_done' || 
+		$NAME == 'more_number_formats' || $NAME == 'no_quality_checks' ||
+		$NAME == 'filler' || $NAME == 'search_name' || $EXT == 'disabled' ||
+		$NAME == 'must_match' || $EXT == 'fakeshow' || $EXT == 'filler' ||
+		$NAME == 'excludes' || $NAME == 'search_by_date' || $EXT == 'twopart') { 
+			$TYPE = 'metadata';
+	} else if ($EXT == 'fake' || $EXT == 'txt' || $EXT == 'json' ||
+		$EXT == 'bup' || $EXT == 'ifo') {
+			$TYPE = 'metadata';
+	}
+	if ($TYPE == 'other') {
+		die('Unknown file type: ' . $path . ': ' . $NAME . '|' . $EXT . "\n");
+	}
+
+	# Add missing paths
+	$select->execute(array(':base' => $BASE_LOCAL, ':path' => $file));
+	if (!$select->fetch(PDO::FETCH_ASSOC)) {
+		if ($DEBUG) {
+			echo 'Adding: ' . $path . ': ' . $TYPE . "\n";
+		}
+		$insert->execute(array(':base' => $BASE_LOCAL, ':path' => $file, ':type' => $TYPE));
+	}
+
+	# Grab the DB entry
+	$check->execute(array(':base' => $BASE_LOCAL, ':path' => $file));
+	$row = $check->fetch(PDO::FETCH_ASSOC);
+	if (!$row || !is_array($row)) {
+		die('Unable to fetch entry for: ' . $file . "\n");
+	}
+
+	# Check the file type
+	if ($row['type'] != $TYPE) {
+		if ($DEBUG) {
+			echo 'Updating type for: ' . $file . "\n";
+		}
+		$set_type->execute(array(':base' => $BASE_LOCAL, ':path' => $file, ':type' => $TYPE));
+	}
+
+	# Skip everything else for 'ignored' files
+	if ($TYPE == 'ignored') {
+		continue;
+	}
+
+	# Check the file mtime
+	$mtime = trim(shell_exec('stat -c "%Y" ' . escapeshellarg($path)));
+	if ($row['mtime'] < $mtime) {
+		if ($DEBUG) {
+			echo 'Updating mtime for: ' . $file . "\n";
+		}
+		$set_mtime->execute(array(':base' => $BASE_LOCAL, ':path' => $file));
+	}
+
+	# Check the file size
+	$size = trim(shell_exec('stat -c "%s" ' . escapeshellarg($path)));
+	if ($row['size'] != $size) {
+		if ($DEBUG) {
+			echo 'Updating size for: ' . $file . "\n";
+		}
+		$set_size->execute(array(':base' => $BASE_LOCAL, ':path' => $file, ':size' => $size));
+	}
+	unset($size);
+
+	# Update hashes as needed
+	if ($TYPE != 'folder') {
+		$check_hash->execute(array(':base' => $BASE_LOCAL, ':path' => $file, ':mtime' => $mtime));
+                $row = $check_hash->fetch(PDO::FETCH_ASSOC);
+                if ($row) {
+			if ($DEBUG) {
+				echo 'Adding hash: ' . $path . "\n";
+			}
+			$hash = trim(shell_exec('md5sum ' . escapeshellarg($path) . ' | cut -d " " -f 1'));
+			if (strlen($hash) == 32) {
+				$set_hash->execute(array(':base' => $BASE_LOCAL, ':path' => $file, ':hash' => $hash));
+			} else {
+				die('Invalid hash (' . $hash . ') for file: ' . $path . "\n");
+			}
+			unset($hash);
+		}
+		unset($row);
+	}
+	unset($mtime);
+
+	unset($NAME);
+	unset($EXT);
+	unset($TYPE);
+	unset($path);
+}
+unset($FILES);
+unset($select);
+unset($insert);
+unset($check);
+unset($set_mtime);
+unset($set_size);
+unset($check_hash);
+unset($set_hash);
+
+# Update priorities
+$priority = $dbh->prepare('UPDATE files SET priority = :priority WHERE path LIKE :path');
+$priority->execute(array(':priority' => 100,	':path' => 'Movies/%'));
+$priority->execute(array(':priority' => 50,	':path' => 'iTunes/%'));
+$priority->execute(array(':priority' => -50,	':path' => 'Backups/%'));
+$priority->execute(array(':priority' => -100,	':path' => 'TV/%'));
+unset($priority);
+
+# If remote operations are enabled
+if ($REMOTE) {
+	# Log in to OpenDrive
+	require_once 'opendrive.php';
+	$session = login();
+
+	# Validate the existence, type and size of all files we think on the remote system
+	$select = $dbh->prepare('SELECT base, path, type, size FROM files WHERE remote_mtime IS NOT NULL AND path LIKE :subdir');
+	$clear = $dbh->prepare('UPDATE files SET remote_mtime = NULL, remote_hash = NULL WHERE base = :base AND path = :path');
+	$select->execute(array(':subdir' => $SUB_DIR . '/%'));
+	while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
+		$trigger = false;
+		if ($DEBUG > 2) {
+			echo 'Checking remote: ' . $row['path'] . "\n";
+		}
+
+		if ($row['type'] == 'ignored') {
+			continue;
+		} else if ($row['type'] == 'folder') {
+			if (!folderID($session, $row['path'])) {
+				echo 'Missing remote folder: ' . $row['path'] . "\n";
+				$trigger = true;
+			}
+		} else {
+			$data = fileInfo($session, $row['path']);
+			if (!$data) {
+				echo 'Missing remote file: ' . $row['path'] . "\n";
+				$trigger = true;
+			} else if ($data['Size'] != $row['size']) {
+				echo 'Wrong size remote file: ' . $row['path'] . ' (' . $data['size'] . '/' . $row['Size'] . ")\n";
+				$trigger = true;
+			}
+			unset($data);
+		}
+
+		if ($DELETE && $trigger) {
+			$clear->execute(array(':base' => $row['base'], ':path' => $row['path']));
+		}
+		unset($trigger);
+	}
+	unset($select);
+	unset($clear);
+
+	# Logout of OpenDrive
+	logout($session);
+	unset($session);
+}
+
+# Cleanup
+unset($dbh);
+
+?>

+ 122 - 0
upload.php

@@ -0,0 +1,122 @@
+#!/usr/local/bin/php
+<?php
+
+# Debug
+$DEBUG = false;
+if ($_ENV['DEBUG']) {
+	$DEBUG = true;
+}
+
+# Includes
+require_once 'opendrive.php';
+
+# Command-line parameters
+global $argc;
+global $argv;
+$BYTES = 1 * 1024 * 1024 * 1024;
+if (($argc > 1) && (strlen($argv[1]) > 0)) {
+	$BYTES = intval($argv[1]) * 1024 * 1024;
+}
+
+# Run serially
+$PID_FILE = sys_get_temp_dir() . '/upload.pid';
+if (file_exists($PID_FILE)) {
+	$OLD_PID = trim(@file_get_contents($PID_FILE));
+	if ($OLD_PID && posix_kill($OLD_PID, 0)) {
+
+		# Already running
+		if ($DEBUG) {
+			echo 'Already running: ' . $OLD_PID . "\n";
+		}
+		exit(0);
+	}
+}
+file_put_contents($PID_FILE, posix_getpid());
+unset($PID_FILE);
+
+# Open the DB connection
+$dbh = dbOpen();
+
+# Open the OpenDrive session
+$session = login();
+if (!$session) {
+	die("Unable to connect to OpenDrive\n");
+}
+
+# Prepare statements
+$folders = $dbh->prepare('SELECT base, path FROM files WHERE ' .
+	"type = 'folder' AND " .
+	'(remote_mtime IS NULL OR remote_mtime < mtime) ' .
+	'ORDER BY base, path');
+$files = $dbh->prepare('SELECT base, path FROM files WHERE ' .
+	"(type != 'ignored' AND type != 'folder') AND " .
+	'(remote_mtime IS NULL OR remote_mtime < mtime) ' .
+	'ORDER BY priority DESC, path'
+);
+$update = $dbh->prepare('UPDATE files SET remote_mtime = now() WHERE base = :base AND path = :path');
+
+# Create all the folders
+if ($DEBUG) {
+	echo "Creating folders\n";
+}
+$folders->execute();
+while ($row = $folders->fetch()) {
+
+	# Ensure the local reference is valid
+	$file = $row['base'] . '/' . $row['path'];
+	if (!is_dir($file)) {
+		echo 'Invalid directory: ' . $file . "\n";
+		continue;
+	}
+
+	# Create the folder
+	if ($DEBUG) {
+		echo 'Creating folder: ' . $row['path'] . "\n";
+	}
+	if (folderID($session, $row['path']) || mkFolder($session, $row['path'])) {
+		$update->execute(array(':base' => $row['base'], ':path' => $row['path']));
+	}
+}
+
+# Loop through all the files
+if ($DEBUG) {
+	echo 'Uploading files with byte limit: ' . $BYTES . "\n";
+}
+$uploaded = 0;
+$files->execute();
+while ($row = $files->fetch()) {
+
+	# Ensure the local reference is valid
+	$file = $row['base'] . '/' . $row['path'];
+	if (!is_readable($file)) {
+		echo 'Invalid file: ' . $file . "\n";
+		continue;
+	}
+	$stat = stat($file);
+
+	# Upload the file
+	if ($DEBUG) {
+		echo 'Uploading file (' . $stat['size'] . ' bytes): ' . $row['path'] . "\n";
+	}
+	$result = fileUpload($session, $row['path'], $file);
+	if ($result !== false && $result == $stat['size']) {
+		$uploaded += $result;
+		$update->execute(array(':base' => $row['base'], ':path' => $row['path']));
+	}
+
+	# Bail if we exceed the byte limit
+	if ($DEBUG) {
+		echo 'Uploaded ' . $uploaded . ' of ' . $BYTES . " bytes\n";
+	}
+	if ($BYTES && $uploaded >= $BYTES) {
+		if ($DEBUG) {
+			echo "Exiting due to byte limit\n";
+		}
+		break;
+	}
+}
+
+# Logout from OpenDrive
+logout($session);
+
+?>