05 plugin.js (3/5)

  async function scan(root) {
    const books = [];
    const queue = [root.replace(/\/+$/, '') || '/'];
    let dirs = 0;
    while (queue.length) {
      const dir = queue.shift();
      if (++dirs > 500) throw new Error('more than 500 folders; pick a smaller scan folder');
      $('[data-status]').textContent = `Scanning ${dir} ... (${books.length} books so far)`;
      for (const e of await listDir(dir)) {
        const path = (dir === '/' ? '' : dir) + '/' + e.name;
        if (e.name.startsWith('.')) continue;               // hidden files and folders
        if (e.isDirectory) {
          if (!SKIP_DIRS.includes(path)) queue.push(path);
        } else if (BOOK.test(e.name)) {
          books.push({ path, dir, name: e.name, size: e.size });
        }
      }
    }
    return books;
  }

  // "Dune (1).epub", "dune.epub", "Dune - copy.EPUB" -> "dune.epub".
  // The extension stays part of the key: Dune.epub and Dune.txt are not duplicates.
  const key = (name) => {
    const ext = (name.match(BOOK) || [''])[0].toLowerCase();
    return name.toLowerCase()
      .replace(BOOK, '')
      .replace(/\s*(\(\d+\)|- ?copy|copy)\s*$/g, '')
      .replace(/[^a-z0-9]+/g, '') + ext;
  };
‹ PreviousReader file (.txt)Next ›