1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package Torello.HTML.Tools.Images;

import Torello.Java.UnreachableError;

import java.util.function.Function;

class ComputeFileName 
{
    @FunctionalInterface
    interface ISExFunction 
    { public String apply(Exception e) throws ImageScraperException; }

    static String run(
            final Request       request,
            final ImageInfo     imageInfo,
            final int           successCounter,
            final ISExFunction  execptionHandler
        )
        throws ImageScraperException
    {
        final String preFix = (request.fileNamePrefix != null)
            ? request.fileNamePrefix
            : "";


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Use User-Provided "Get File-Name Lambda" - 'Request.getImageFileSaveName'
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        if (request.getImageFileSaveName != null)
        {
            try
            {
                final String file = request.getImageFileSaveName.apply(imageInfo);
                return preFix + file;
            }

            catch (Exception e)
                { return execptionHandler.apply(e); }
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Use 'Results.successCounter' for the File-Name
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        else if (request.useDefaultCounterForImageFileNames)

            return preFix + request.counterPrinter.apply(successCounter);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Use the original URL's "File-Name" (Remember, on Yahoo! News, this don't work!)
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        else
        {
            final String temp = imageInfo.url.getFile().substring(1);

            if (imageInfo.guessedExtension == null) return preFix + temp;

            String ext = imageInfo.guessedExtension.extension;

            if (temp.toLowerCase().endsWith('.' + ext))
                return preFix + temp.substring(0, temp.length() - 1 - ext.length());

            if (imageInfo.guessedExtension.alternateExtension == null)
                return preFix + temp;

            ext = imageInfo.guessedExtension.alternateExtension;

            if (temp.toLowerCase().endsWith('.' + ext))
                return preFix + temp.substring(0, temp.length() - 1 - ext.length());

            throw new UnreachableError();
        }
    }

}