scan.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #!/usr/local/bin/php
  2. <?php
  3. # Debug
  4. $DEBUG = false;
  5. if ($_ENV['DEBUG']) {
  6. $DEBUG = true;
  7. }
  8. # Includes
  9. require_once 'opendrive.php';
  10. # Command-line parameters
  11. global $argc;
  12. global $argv;
  13. $LIMIT_PATH = '';
  14. if (($argc > 1) && (strlen($argv[1]) > 0)) {
  15. $LIMIT_PATH = trim($argv[1]);
  16. }
  17. # Allow local-only scanning
  18. $REMOTE = true;
  19. if (isset($_ENV['REMOTE'])) {
  20. if (!$_ENV['REMOTE']) {
  21. $REMOTE = false;
  22. }
  23. }
  24. # Delete only if specified
  25. $DELETE = false;
  26. if ($_ENV['DELETE']) {
  27. $DELETE = true;
  28. }
  29. # Open the DB connection
  30. $dbh = dbOpen();
  31. # Find our scan paths
  32. $paths = NULL;
  33. $priority = $dbh->prepare('UPDATE files SET priority = :priority WHERE base = :base AND path LIKE :path');
  34. $scan = $dbh->prepare('UPDATE paths SET last_scan = now() WHERE base = :base AND path = :path');
  35. if (!$LIMIT_PATH) {
  36. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths WHERE last_scan < now() - scan_age');
  37. } else {
  38. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths WHERE last_scan < now() - scan_age' .
  39. ' AND path LIKE :path');
  40. $paths->execute(array(':path' => $LIMIT_PATH));
  41. }
  42. while ($pathsRow = $paths->fetch(PDO::FETCH_ASSOC)) {
  43. # Grab our globals
  44. $BASE = $pathsRow['base'];
  45. $PATH = $pathsRow['path'];
  46. $PATH_LIKE = $PATH . '/%';
  47. $MIN_AGE = $pathsRow['min_age'];
  48. $LOCAL = $BASE . '/' . $PATH;
  49. # Sanity check
  50. if (!@is_dir($LOCAL) | !@is_readable($LOCAL)) {
  51. die('Invalid local directory: ' . $LOCAL . "\n");
  52. }
  53. # Look for files in the DB that no longer exist or have changed types
  54. $delete = $dbh->prepare('DELETE FROM files WHERE base = :base AND path = :path');
  55. $missing = $dbh->prepare('SELECT path, type FROM files WHERE base = :base AND path LIKE :path');
  56. $missing->execute(array(':base' => $BASE, ':path' => $PATH_LIKE));
  57. while ($row = $missing->fetch(PDO::FETCH_ASSOC)) {
  58. $trigger = false;
  59. $file = $BASE . '/' . $row['path'];
  60. if ($row['type'] == 'folder') {
  61. # Ensure the path exists and is a folder
  62. if (!is_dir($file)) {
  63. echo 'Missing folder: ' . $file . "\n";
  64. $trigger = true;
  65. }
  66. } else if ($row['type'] == 'ignored') {
  67. # Silently delete missing ignored files of any type
  68. if (!file_exists($file)) {
  69. if ($DEBUG) {
  70. echo 'Missing ignored file: ' . $file . "\n";
  71. }
  72. $trigger = true;
  73. }
  74. } else {
  75. # Ensure the path exists and is a regular file
  76. if (!is_file($file)) {
  77. echo 'Missing file: ' . $file . "\n";
  78. $trigger = true;
  79. }
  80. }
  81. # Delete if global DELETE is enabled
  82. if ($DELETE && $trigger) {
  83. $delete->execute(array(':base' => $BASE, ':path' => $row['path']));
  84. }
  85. unset($trigger);
  86. unset($file);
  87. }
  88. unset($row);
  89. unset($missing);
  90. unset($delete);
  91. # Grab the file list
  92. $FILES = array();
  93. $compAge = time() - ($MIN_AGE * 86400);
  94. $fsh = NULL;
  95. try {
  96. $fsh = new RecursiveIteratorIterator(
  97. new RecursiveDirectoryIterator(
  98. $LOCAL,
  99. FilesystemIterator::KEY_AS_PATHNAME |
  100. FilesystemIterator::CURRENT_AS_FILEINFO |
  101. FilesystemIterator::SKIP_DOTS |
  102. FilesystemIterator::UNIX_PATHS
  103. ),
  104. RecursiveIteratorIterator::SELF_FIRST
  105. );
  106. } catch (Exception $e) {
  107. die('Invalid filesystem path: ' . $LOCAL . "\n");
  108. }
  109. foreach ($fsh as $path => $file) {
  110. # Ignore anything that isn't a file and isn't a directory
  111. if (!$file->isDir() && !$file->isFile()) {
  112. continue;
  113. }
  114. # Ignore file less than $MIN_AGE old
  115. if ($file->isFile() && $file->getMTime() > $compAge) {
  116. continue;
  117. }
  118. # Keep everything else
  119. $FILES[] = $file;
  120. unset($path);
  121. unset($file);
  122. }
  123. unset($compAge);
  124. unset($fsh);
  125. # Loop through all the files we found
  126. $select = $dbh->prepare('SELECT base, path, type FROM files WHERE base = :base AND path = :path');
  127. $insert = $dbh->prepare('INSERT INTO files (base, path, type, mtime) VALUES (:base, :path, :type, now())');
  128. $check = $dbh->prepare('SELECT type, size, EXTRACT(EPOCH FROM mtime) AS mtime FROM files WHERE base = :base AND path = :path');
  129. $set_mtime = $dbh->prepare('UPDATE files SET mtime = now() WHERE base = :base AND path = :path');
  130. $set_size = $dbh->prepare('UPDATE files SET size = :size WHERE base = :base AND path = :path');
  131. $set_type = $dbh->prepare('UPDATE files SET type = :type WHERE base = :base AND path = :path');
  132. $check_hash = $dbh->prepare('SELECT hash, EXTRACT(EPOCH FROM hash_time) AS hash_time ' .
  133. 'FROM files WHERE base = :base AND path = :path AND ' .
  134. '(hash_time IS NULL OR EXTRACT(EPOCH FROM hash_time) < :mtime)');
  135. $set_hash = $dbh->prepare('UPDATE files SET hash = :hash, hash_time = now() WHERE base = :base AND path = :path');
  136. foreach ($FILES as $file) {
  137. # Construct the absolute path
  138. $path = $file->getPathname();
  139. $shortPath = substr($path, strlen($BASE) + 1);
  140. if ($DEBUG) {
  141. echo 'Scanning: ' . $path . "\n";
  142. }
  143. # Pick a file type
  144. $ext = $file->getExtension();
  145. $name = strtolower($file->getBasename('.' . $ext));
  146. $ext = strtolower($ext);
  147. $type = 'other';
  148. if (preg_match('/\/\.git(\/.*)?$/', $shortPath)) {
  149. $type = 'ignored';
  150. } else if (preg_match('/\/\._/', $shortPath)) {
  151. $type = 'ignored';
  152. } else if ($ext == 'lastfindrecode' || $name == 'placeholder' || $ext == 'plexignore') {
  153. $type = 'ignored';
  154. } else if ($ext == 'tmp' || $ext == 'gitignore' || $ext == 'ds_store' ||
  155. preg_match('/^\.smbdelete/', $name) || preg_match('/\.mkv\.\w+$/', $shortPath)) {
  156. $type = 'ignored';
  157. } else if (preg_match('/^iTunes\/Album Artwork\/Cache/', $shortPath) || $shortPath == 'iTunes/sentinel') {
  158. $type = 'ignored';
  159. } else if ($file->isDir()) {
  160. $type = 'folder';
  161. if ($ext == '' && $name == 'cmd') {
  162. $type = 'ignored';
  163. }
  164. } else if ($ext == 'm4v' || $ext == 'mkv' || $ext == 'mp4' || $ext == 'mov' ||
  165. $ext == 'vob' || $ext == 'iso' || $ext == 'avi') {
  166. $type = 'video';
  167. } else if ($ext == 'mp3' || $ext == 'aac' || $ext == 'm4a' || $ext == 'm4b' ||
  168. $ext == 'm4p' || $ext == 'wav') {
  169. $type = 'audio';
  170. } else if ($ext == 'epub' || $ext == 'pdf') {
  171. $type = 'book';
  172. } else if ($ext == 'jpg' || $ext == 'png') {
  173. $type = 'image';
  174. } else if ($ext == 'gz' || $ext == 'zip' || $ext == 'xz') {
  175. $type = 'archive';
  176. } else if ($ext == 'itc' || $ext == 'itl' || $ext == 'strings' || $ext == 'itdb' ||
  177. $ext == 'xml' || $ext == 'plist' || $ext == 'ipa' || $ext == 'ini') {
  178. $type = 'database';
  179. } else if ($ext == 'clip' || $ext == 'riff' || $ext == 'nfo') {
  180. $type = 'metadata';
  181. } else if ($ext == 'webloc' || $name == 'skip' || $name == 'season_done' ||
  182. $name == 'more_number_formats' || $name == 'no_quality_checks' ||
  183. $name == 'filler' || $name == 'search_name' || $ext == 'disabled' ||
  184. $name == 'must_match' || $ext == 'fakeshow' || $ext == 'filler' ||
  185. $name == 'excludes' || $name == 'search_by_date' || $ext == 'twopart') {
  186. $type = 'metadata';
  187. } else if ($ext == 'fake' || $ext == 'txt' || $ext == 'json' ||
  188. $ext == 'bup' || $ext == 'ifo') {
  189. $type = 'metadata';
  190. } else if (preg_match('/\.sparsebundle\//i', $shortPath)) {
  191. if ($ext == 'bckup' || $ext == 'plist') {
  192. $type = 'disk';
  193. } else if (preg_match('/\.sparsebundle\/bands\/\w+$/i', $shortPath)) {
  194. $type = 'disk';
  195. }
  196. }
  197. if ($type == 'other') {
  198. die('Unknown file type: ' . $path . ': ' . $name . '|' . $ext . "\n");
  199. }
  200. # Add missing paths
  201. $select->execute(array(':base' => $BASE, ':path' => $shortPath));
  202. if (!$select->fetch(PDO::FETCH_ASSOC)) {
  203. if ($DEBUG) {
  204. echo 'Adding: ' . $path . ': ' . $type . "\n";
  205. }
  206. $insert->execute(array(':base' => $BASE, ':path' => $shortPath, ':type' => $type));
  207. }
  208. # Grab the DB entry
  209. $check->execute(array(':base' => $BASE, ':path' => $shortPath));
  210. $row = $check->fetch(PDO::FETCH_ASSOC);
  211. if (!$row || !is_array($row)) {
  212. die('Unable to fetch entry for: ' . $path . "\n");
  213. }
  214. # Check the file type
  215. if ($row['type'] != $type) {
  216. if ($DEBUG) {
  217. echo 'Updating type for: ' . $path . "\n";
  218. }
  219. $set_type->execute(array(':base' => $BASE, ':path' => $shortPath, ':type' => $type));
  220. }
  221. # Skip everything else for 'ignored' files
  222. if ($type == 'ignored') {
  223. continue;
  224. }
  225. # Check the file mtime
  226. if ($row['mtime'] < $file->getMTime()) {
  227. if ($DEBUG) {
  228. echo 'Updating mtime for: ' . $file . "\n";
  229. }
  230. $set_mtime->execute(array(':base' => $BASE, ':path' => $shortPath));
  231. }
  232. # Check the file size
  233. if ($row['size'] != $file->getSize()) {
  234. if ($DEBUG) {
  235. echo 'Updating size for: ' . $file . "\n";
  236. }
  237. $set_size->execute(array(':base' => $BASE, ':path' => $shortPath, ':size' => $file->getSize()));
  238. }
  239. # Update hashes as needed
  240. if ($type != 'folder') {
  241. $check_hash->execute(array(':base' => $BASE, ':path' => $shortPath, ':mtime' => $mtime));
  242. $row = $check_hash->fetch(PDO::FETCH_ASSOC);
  243. if ($row) {
  244. if ($DEBUG) {
  245. echo 'Adding hash: ' . $path . "\n";
  246. }
  247. $hash = md5_file($path, false);
  248. if (strlen($hash) == 32) {
  249. $set_hash->execute(array(':base' => $BASE, ':path' => $shortPath, ':hash' => $hash));
  250. } else {
  251. echo 'Unable to hash: ' . $path . "\n";
  252. continue;
  253. }
  254. unset($hash);
  255. }
  256. unset($row);
  257. }
  258. unset($mtime);
  259. unset($name);
  260. unset($ext);
  261. unset($type);
  262. unset($shortPath);
  263. unset($path);
  264. }
  265. unset($FILES);
  266. unset($select);
  267. unset($insert);
  268. unset($check);
  269. unset($set_mtime);
  270. unset($set_size);
  271. unset($check_hash);
  272. unset($set_hash);
  273. # Update priorities
  274. $priority->execute(array(':priority' => $pathsRow['priority'], ':base' => $BASE, ':path' => $PATH_LIKE));
  275. if ($DEBUG) {
  276. echo 'Updated ' . $priority->rowCount() . ' rows from ' . $PATH . ' with priority ' . $pathsRow['priority'] . "\n";
  277. }
  278. # Update the scan time
  279. $scan->execute(array(':base' => $BASE, ':path' => $PATH));
  280. unset($BASE);
  281. unset($PATH);
  282. unset($PATH_LIKE);
  283. unset($MIN_AGE);
  284. unset($LOCAL);
  285. }
  286. unset($priority);
  287. unset($scan);
  288. unset($pathsRow);
  289. unset($paths);
  290. # If remote operations are enabled
  291. if ($REMOTE) {
  292. # Log in to OpenDrive
  293. require_once 'opendrive.php';
  294. $session = login();
  295. # Find our scan paths
  296. $paths = NULL;
  297. $scan = $dbh->prepare('UPDATE paths SET remote_last_scan = now() WHERE base = :base AND path = :path');
  298. if (!$LIMIT_PATH) {
  299. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths' .
  300. ' WHERE remote_last_scan < now() - remote_scan_age');
  301. } else {
  302. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths' .
  303. ' WHERE remote_last_scan < now() - remote_scan_age' .
  304. ' AND path LIKE :path');
  305. $paths->execute(array(':path' => $LIMIT_PATH));
  306. }
  307. while ($pathsRow = $paths->fetch(PDO::FETCH_ASSOC)) {
  308. # Grab our globals
  309. $BASE = $pathsRow['base'];
  310. $PATH = $pathsRow['path'];
  311. $PATH_LIKE = $PATH . '/%';
  312. if ($DEBUG) {
  313. echo 'Remote scan for: ' . $PATH . "\n";
  314. }
  315. # Validate the existence, type and size of all files we think on the remote system
  316. $select = $dbh->prepare('SELECT path, type, size FROM files WHERE remote_mtime IS NOT NULL AND path LIKE :path');
  317. $clear = $dbh->prepare('UPDATE files SET remote_mtime = NULL, remote_hash = NULL WHERE base = :base AND path = :path');
  318. $select->execute(array(':path' => $PATH_LIKE));
  319. while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
  320. $trigger = false;
  321. if ($DEBUG > 2) {
  322. echo 'Checking remote: ' . $row['path'] . "\n";
  323. }
  324. if ($row['type'] == 'ignored') {
  325. continue;
  326. } else if ($row['type'] == 'folder') {
  327. if (!folderID($session, $row['path'])) {
  328. echo 'Missing remote folder: ' . $row['path'] . "\n";
  329. $trigger = true;
  330. }
  331. } else {
  332. $data = fileInfo($session, $row['path']);
  333. if (!$data) {
  334. echo 'Missing remote file: ' . $row['path'] . "\n";
  335. $trigger = true;
  336. } else if ($data['Size'] != $row['size']) {
  337. echo 'Wrong size remote file: ' . $row['path'] . ' (' . $data['size'] . '/' . $row['Size'] . ")\n";
  338. $trigger = true;
  339. }
  340. unset($data);
  341. }
  342. if ($DELETE && $trigger) {
  343. $clear->execute(array(':base' => $BASE, ':path' => $row['path']));
  344. }
  345. unset($trigger);
  346. }
  347. unset($select);
  348. unset($clear);
  349. unset($row);
  350. # Update the remote scan time
  351. $scan->execute(array(':base' => $BASE, ':path' => $PATH));
  352. # Cleanup
  353. unset($PATH);
  354. unset($PATH_LIKE);
  355. }
  356. # Logout of OpenDrive
  357. logout($session);
  358. unset($session);
  359. }
  360. unset($scan);
  361. unset($pathsRow);
  362. unset($paths);
  363. # Cleanup
  364. unset($dbh);
  365. ?>