scan.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 unless disabled
  25. $DELETE = true;
  26. if (isset($_ENV['DELETE']) && !$_ENV['DELETE']) {
  27. $DELETE = false;
  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. $name == 'url' || ($name == 'rules' && $ext == 'pm')) {
  193. $type = 'metadata';
  194. } else if ($ext == 'fake' || $ext == 'txt' || $ext == 'json' ||
  195. $ext == 'bup' || $ext == 'ifo') {
  196. $type = 'metadata';
  197. } else if (preg_match('/\.sparsebundle\//i', $shortPath)) {
  198. if ($ext == 'bckup' || $ext == 'plist') {
  199. $type = 'disk';
  200. } else if (preg_match('/\.sparsebundle\/bands\/\w+$/i', $shortPath)) {
  201. $type = 'disk';
  202. } else if (preg_match('/\.sparsebundle\/token$/i', $shortPath)) {
  203. $type = 'disk';
  204. }
  205. }
  206. if ($type == 'other') {
  207. die('Unknown file type: ' . $path . ': ' . $name . '|' . $ext . "\n");
  208. }
  209. # Add missing paths
  210. $select->execute(array(':base' => $BASE, ':path' => $shortPath));
  211. if (!$select->fetch(PDO::FETCH_ASSOC)) {
  212. if ($DEBUG) {
  213. echo 'Adding: ' . $path . ': ' . $type . "\n";
  214. }
  215. $insert->execute(array(':base' => $BASE, ':path' => $shortPath, ':type' => $type));
  216. }
  217. # Grab the DB entry
  218. $check->execute(array(':base' => $BASE, ':path' => $shortPath));
  219. $row = $check->fetch(PDO::FETCH_ASSOC);
  220. if (!$row || !is_array($row)) {
  221. die('Unable to fetch entry for: ' . $path . "\n");
  222. }
  223. # Check the file type
  224. if ($row['type'] != $type) {
  225. if ($DEBUG) {
  226. echo 'Updating type for: ' . $path . "\n";
  227. }
  228. $set_type->execute(array(':base' => $BASE, ':path' => $shortPath, ':type' => $type));
  229. }
  230. # Skip everything else for 'ignored' files
  231. if ($type == 'ignored') {
  232. continue;
  233. }
  234. # Check the file mtime
  235. if ($row['mtime'] < $file->getMTime()) {
  236. if ($DEBUG) {
  237. echo 'Updating mtime for: ' . $file . "\n";
  238. }
  239. $set_mtime->execute(array(':base' => $BASE, ':path' => $shortPath));
  240. }
  241. # Check the file size
  242. if ($row['size'] != $file->getSize()) {
  243. if ($DEBUG) {
  244. echo 'Updating size for: ' . $file . "\n";
  245. }
  246. $set_size->execute(array(':base' => $BASE, ':path' => $shortPath, ':size' => $file->getSize()));
  247. }
  248. # Update hashes as needed
  249. if ($type != 'folder') {
  250. $check_hash->execute(array(':base' => $BASE, ':path' => $shortPath, ':mtime' => $mtime));
  251. $row = $check_hash->fetch(PDO::FETCH_ASSOC);
  252. if ($row) {
  253. if ($DEBUG) {
  254. echo 'Adding hash: ' . $path . "\n";
  255. }
  256. $hash = md5_file($path, false);
  257. if (strlen($hash) == 32) {
  258. $set_hash->execute(array(':base' => $BASE, ':path' => $shortPath, ':hash' => $hash));
  259. } else {
  260. echo 'Unable to hash: ' . $path . "\n";
  261. continue;
  262. }
  263. unset($hash);
  264. }
  265. unset($row);
  266. }
  267. unset($mtime);
  268. unset($name);
  269. unset($ext);
  270. unset($type);
  271. unset($shortPath);
  272. unset($path);
  273. }
  274. unset($FILES);
  275. unset($select);
  276. unset($insert);
  277. unset($check);
  278. unset($set_mtime);
  279. unset($set_size);
  280. unset($check_hash);
  281. unset($set_hash);
  282. # Update priorities
  283. $priority->execute(array(':priority' => $pathsRow['priority'], ':base' => $BASE, ':path' => $PATH_LIKE));
  284. if ($DEBUG) {
  285. echo 'Updated ' . $priority->rowCount() . ' rows from ' . $PATH . ' with priority ' . $pathsRow['priority'] . "\n";
  286. }
  287. # Update the scan time
  288. $scan->execute(array(':base' => $BASE, ':path' => $PATH));
  289. unset($BASE);
  290. unset($PATH);
  291. unset($PATH_LIKE);
  292. unset($MIN_AGE);
  293. unset($LOCAL);
  294. }
  295. unset($priority);
  296. unset($scan);
  297. unset($pathsRow);
  298. unset($paths);
  299. # If remote operations are enabled
  300. if ($REMOTE) {
  301. # Log in to OpenDrive
  302. require_once 'opendrive.php';
  303. $session = NULL;
  304. # Find our scan paths
  305. $paths = NULL;
  306. $scan = $dbh->prepare('UPDATE paths SET remote_last_scan = now() WHERE base = :base AND path = :path');
  307. if (!$LIMIT_PATH) {
  308. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths' .
  309. ' WHERE remote_last_scan < now() - remote_scan_age');
  310. } else {
  311. $paths = $dbh->prepare('SELECT base, path, priority, min_age FROM paths' .
  312. ' WHERE remote_last_scan < now() - remote_scan_age' .
  313. ' AND path LIKE :path');
  314. $paths->execute(array(':path' => $LIMIT_PATH));
  315. }
  316. while ($pathsRow = $paths->fetch(PDO::FETCH_ASSOC)) {
  317. # Grab our globals
  318. $BASE = $pathsRow['base'];
  319. $PATH = $pathsRow['path'];
  320. $PATH_LIKE = $PATH . '/%';
  321. if ($DEBUG) {
  322. echo 'Remote scan for: ' . $PATH . "\n";
  323. }
  324. # Log in to OpenDrive as needed
  325. if (!$session) {
  326. $session = login();
  327. }
  328. # Validate the existence, type and size of all files we think on the remote system
  329. $select = $dbh->prepare('SELECT path, type, size FROM files WHERE remote_mtime IS NOT NULL AND path LIKE :path');
  330. $clear = $dbh->prepare('UPDATE files SET remote_mtime = NULL, remote_hash = NULL WHERE base = :base AND path = :path');
  331. $select->execute(array(':path' => $PATH_LIKE));
  332. while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
  333. $trigger = false;
  334. if ($DEBUG > 2) {
  335. echo 'Checking remote: ' . $row['path'] . "\n";
  336. }
  337. if ($row['type'] == 'ignored') {
  338. continue;
  339. } else if ($row['type'] == 'folder') {
  340. if (!folderID($session, $row['path'])) {
  341. echo 'Missing remote folder: ' . $row['path'] . "\n";
  342. $trigger = true;
  343. }
  344. } else {
  345. $data = fileInfo($session, $row['path']);
  346. if (!$data) {
  347. echo 'Missing remote file: ' . $row['path'] . "\n";
  348. $trigger = true;
  349. } else if ($data['Size'] != $row['size']) {
  350. echo 'Wrong size remote file: ' . $row['path'] . ' (' . $data['size'] . '/' . $row['Size'] . ")\n";
  351. $trigger = true;
  352. }
  353. unset($data);
  354. }
  355. if ($DELETE && $trigger) {
  356. $clear->execute(array(':base' => $BASE, ':path' => $row['path']));
  357. }
  358. unset($trigger);
  359. }
  360. unset($select);
  361. unset($clear);
  362. unset($row);
  363. # Update the remote scan time
  364. $scan->execute(array(':base' => $BASE, ':path' => $PATH));
  365. # Cleanup
  366. unset($PATH);
  367. unset($PATH_LIKE);
  368. }
  369. # Logout of OpenDrive as needed
  370. if ($session) {
  371. logout($session);
  372. }
  373. unset($session);
  374. }
  375. unset($scan);
  376. unset($pathsRow);
  377. unset($paths);
  378. # Cleanup
  379. unset($dbh);
  380. ?>