<commit_before>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.novoda.downloadmanager.lib;

import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.webkit.MimeTypeMap;

import com.novoda.notils.logger.simple.Log;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Some helper functions for the download manager
 */
class Helpers {
    public static Random sRandom = new Random(SystemClock.uptimeMillis());

    /**
     * Regex used to parse content-disposition headers
     */
    private static final Pattern CONTENT_DISPOSITION_PATTERN =
            Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");

    private static final Object UNIQUE_LOCK = new Object();

    private Helpers() {
    }

    /*
     * Parse the Content-Disposition HTTP Header. The format of the header
     * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
     * This header provides a filename for content that is going to be
     * downloaded to the file system. We only support the attachment type.
     */
    private static String parseContentDisposition(String contentDisposition) {
        try {
            Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
            if (m.find()) {
                return m.group(1);
            }
        } catch (IllegalStateException ex) {
            // This function is defined as returning null when it can't parse the header
        }
        return null;
    }

    /**
     * Creates a filename (where the file should be saved) from info about a download.
     */
    static String generateSaveFile(String url, String hint, String contentDisposition,
                                   String contentLocation, String mimeType, int destination, long contentLength,
                                   StorageManager storageManager) throws StopRequestException {
        if (contentLength < 0) {
            contentLength = 0;
        }
        String path;
        File base = null;
        if (destination == Downloads.Impl.DESTINATION_FILE_URI) {
            path = Uri.parse(hint).getPath();
        } else {
            base = storageManager.locateDestinationDirectory(mimeType, destination, contentLength);
            path = chooseFilename(url, hint, contentDisposition, contentLocation);
        }
        storageManager.verifySpace(destination, path, contentLength);
        if (DownloadDrmHelper.isDrmConvertNeeded(mimeType)) {
            path = DownloadDrmHelper.modifyDrmFwLockFileExtension(path);
        }
        path = getFullPath(path, mimeType, destination, base);
        return path;
    }

    static String getFullPath(String filename, String mimeType, int destination, File base)
            throws StopRequestException {
        String extension = null;
        int dotIndex = filename.lastIndexOf('.');
        boolean missingExtension = dotIndex < 0 || dotIndex < filename.lastIndexOf('/');
        if (destination == Downloads.Impl.DESTINATION_FILE_URI) {
            // Destination is explicitly set - do not change the extension
            if (missingExtension) {
                extension = "";
            } else {
                extension = filename.substring(dotIndex);
                filename = filename.substring(0, dotIndex);
            }
        } else {
            // Split filename between base and extension
            // Add an extension if filename does not have one
            if (missingExtension) {
                extension = chooseExtensionFromMimeType(mimeType, true);
            } else {
                extension = chooseExtensionFromFilename(mimeType, filename, dotIndex);
                filename = filename.substring(0, dotIndex);
            }
        }

        boolean recoveryDir = Constants.RECOVERY_DIRECTORY.equalsIgnoreCase(filename + extension);

        if (base != null) {
            filename = base.getPath() + File.separator + filename;
        }

        Log.v("target file: " + filename + extension);

        synchronized (UNIQUE_LOCK) {
            final String path = chooseUniqueFilenameLocked(
                    destination, filename, extension, recoveryDir);

            // Claim this filename inside lock to prevent other threads from
            // clobbering us. We're not paranoid enough to use O_EXCL.
            try {
                new File(path).createNewFile();
            } catch (IOException e) {
                throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR, "Failed to create target file " + path, e);
            }
            return path;
        }
    }

    private static String chooseFilename(String url, String hint, String contentDisposition,
                                         String contentLocation) {
        String filename = null;

        // First, try to use the hint from the application, if there's one
        if (filename == null && hint != null && !hint.endsWith("/")) {<commit_msg>Remove condition that's always true<commit_after>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.novoda.downloadmanager.lib;

import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.webkit.MimeTypeMap;

import com.novoda.notils.logger.simple.Log;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Some helper functions for the download manager
 */
class Helpers {
    public static Random sRandom = new Random(SystemClock.uptimeMillis());

    /**
     * Regex used to parse content-disposition headers
     */
    private static final Pattern CONTENT_DISPOSITION_PATTERN =
            Pattern.compile("attachment;\\s*filename\\s*=\\s*\"([^\"]*)\"");

    private static final Object UNIQUE_LOCK = new Object();

    private Helpers() {
    }

    /*
     * Parse the Content-Disposition HTTP Header. The format of the header
     * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
     * This header provides a filename for content that is going to be
     * downloaded to the file system. We only support the attachment type.
     */
    private static String parseContentDisposition(String contentDisposition) {
        try {
            Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
            if (m.find()) {
                return m.group(1);
            }
        } catch (IllegalStateException ex) {
            // This function is defined as returning null when it can't parse the header
        }
        return null;
    }

    /**
     * Creates a filename (where the file should be saved) from info about a download.
     */
    static String generateSaveFile(String url, String hint, String contentDisposition,
                                   String contentLocation, String mimeType, int destination, long contentLength,
                                   StorageManager storageManager) throws StopRequestException {
        if (contentLength < 0) {
            contentLength = 0;
        }
        String path;
        File base = null;
        if (destination == Downloads.Impl.DESTINATION_FILE_URI) {
            path = Uri.parse(hint).getPath();
        } else {
            base = storageManager.locateDestinationDirectory(mimeType, destination, contentLength);
            path = chooseFilename(url, hint, contentDisposition, contentLocation);
        }
        storageManager.verifySpace(destination, path, contentLength);
        if (DownloadDrmHelper.isDrmConvertNeeded(mimeType)) {
            path = DownloadDrmHelper.modifyDrmFwLockFileExtension(path);
        }
        path = getFullPath(path, mimeType, destination, base);
        return path;
    }

    static String getFullPath(String filename, String mimeType, int destination, File base)
            throws StopRequestException {
        String extension = null;
        int dotIndex = filename.lastIndexOf('.');
        boolean missingExtension = dotIndex < 0 || dotIndex < filename.lastIndexOf('/');
        if (destination == Downloads.Impl.DESTINATION_FILE_URI) {
            // Destination is explicitly set - do not change the extension
            if (missingExtension) {
                extension = "";
            } else {
                extension = filename.substring(dotIndex);
                filename = filename.substring(0, dotIndex);
            }
        } else {
            // Split filename between base and extension
            // Add an extension if filename does not have one
            if (missingExtension) {
                extension = chooseExtensionFromMimeType(mimeType, true);
            } else {
                extension = chooseExtensionFromFilename(mimeType, filename, dotIndex);
                filename = filename.substring(0, dotIndex);
            }
        }

        boolean recoveryDir = Constants.RECOVERY_DIRECTORY.equalsIgnoreCase(filename + extension);

        if (base != null) {
            filename = base.getPath() + File.separator + filename;
        }

        Log.v("target file: " + filename + extension);

        synchronized (UNIQUE_LOCK) {
            final String path = chooseUniqueFilenameLocked(
                    destination, filename, extension, recoveryDir);

            // Claim this filename inside lock to prevent other threads from
            // clobbering us. We're not paranoid enough to use O_EXCL.
            try {
                new File(path).createNewFile();
            } catch (IOException e) {
                throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR, "Failed to create target file " + path, e);
            }
            return path;
        }
    }

    private static String chooseFilename(String url, String hint, String contentDisposition,
                                         String contentLocation) {
        String filename = null;

        // First, try to use the hint from the application, if there's one
        if (hint != null && !hint.endsWith("/")) {
{'fraction_non_alphanumeric': 0.08465189873417721, 'fraction_numerical': 0.004395218002812939, 'mean_word_length': 2.319813247738547, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4939810', 'n_tokens_mistral': 2885, 'n_tokens_neox': 2781, 'n_words': 918}