1
0

scan.php 12 KB

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