patrickkfkan / patreon-dl

Patreon Downloader
98 stars 7 forks source link

SaveAsCopy not working for all instances #38

Open patg75 opened 1 week ago

patg75 commented 1 week ago

I have the problem, that a post may contain several images that either all end with or are all named 1.jpg Which results in images being recognized as already downloaded and skipped. Even with "SaveAsCopy" there is only 1 more copy being created. I would expect the behavior to be more like: 001(1).jpg 001(2).jpg 001(3).jpg ...

what it does: 001.jpg 001(1).jpg 001(1).jpg [overwriting previous] 001(1).jpg [overwriting previous] ...

Downloading these manually, I get different long cryptic filenames, all ending on 001 any ideas / fixes?

patg75 commented 6 days ago

I know, I should fork the whole thing... but since I'm new to the game, please forgive me. A suggestion for a change in src/utils/FShelper.ts what might work, and did in my first tests, but of course might introduce new problems? EDIT: and seems to do so, because some did some to just recreate more instances of the same image, and some worked fine...

  checkFileExistsAndIncrement(file: string) {
    const { name, base, dir, ext } = path.parse(file);
    // Regex to match filename pattern: 'filename (number).ext'
    const regex = new RegExp(`^${escapeStringRegexp(name)} \\((\\d+)\\)${escapeStringRegexp(ext)}$`);
    let currentLargestInc = -1;
    let currentLargestIncFilename = base;
    const files = this.readdir(dir);

    for (const _file of files) {
      const match = regex.exec(_file);
      if (match && match[1] !== undefined) {
        const num = Number(match[1]);
        if (num > currentLargestInc) {
          currentLargestInc = num;
          currentLargestIncFilename = _file;
        }
      }
    }

    // If no incremented file was found, start at 0
    if (currentLargestInc === -1) {
      if (!fse.existsSync(file)) {
        // Original file doesn't exist, return it as the file to use
        const fileParts = path.parse(file);
        return {
          filename: fileParts.base,
          filePath: path.resolve(file),
          preceding: null
        };
      }
      currentLargestInc = 0; // Start incrementing from 0 if original file exists
    }

    // Create new filename with incremented number
    const _filename = FSHelper.createFilename({
      name,
      suffix: `-${currentLargestInc + 1}`,
      ext
    });
    const _filePath = path.resolve(dir, _filename);

    return {
      filename: _filename,
      filePath: _filePath,
      preceding: path.resolve(dir, currentLargestIncFilename)
    };
  }