|
| 1 | +package org.schabi.newpipe.util |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import androidx.preference.PreferenceManager |
| 5 | +import org.schabi.newpipe.R |
| 6 | +import java.util.regex.Matcher |
| 7 | + |
| 8 | +object FilenameUtils { |
| 9 | + private const val CHARSET_MOST_SPECIAL = "[\\n\\r|?*<\":\\\\>/']+" |
| 10 | + private const val CHARSET_ONLY_LETTERS_AND_DIGITS = "[^\\w\\d]+" |
| 11 | + |
| 12 | + /** |
| 13 | + * #143 #44 #42 #22: make sure that the filename does not contain illegal chars. |
| 14 | + * |
| 15 | + * @param context the context to retrieve strings and preferences from |
| 16 | + * @param title the title to create a filename from |
| 17 | + * @return the filename |
| 18 | + */ |
| 19 | + @JvmStatic |
| 20 | + fun createFilename(context: Context, title: String): String { |
| 21 | + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) |
| 22 | + |
| 23 | + val charsetLd = context.getString(R.string.charset_letters_and_digits_value) |
| 24 | + val charsetMs = context.getString(R.string.charset_most_special_value) |
| 25 | + val defaultCharset = context.getString(R.string.default_file_charset_value) |
| 26 | + |
| 27 | + val replacementChar: String = sharedPreferences.getString( |
| 28 | + context.getString(R.string.settings_file_replacement_character_key), "_" |
| 29 | + )!! |
| 30 | + val selectedCharset = sharedPreferences.getString( |
| 31 | + context.getString(R.string.settings_file_charset_key), "" |
| 32 | + )!!.ifEmpty { defaultCharset } |
| 33 | + |
| 34 | + val charset = when (selectedCharset) { |
| 35 | + charsetLd -> CHARSET_ONLY_LETTERS_AND_DIGITS |
| 36 | + charsetMs -> CHARSET_MOST_SPECIAL |
| 37 | + else -> selectedCharset // Is the user using a custom charset? |
| 38 | + } |
| 39 | + |
| 40 | + return createFilename(title, charset, Matcher.quoteReplacement(replacementChar)) |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Create a valid filename. |
| 45 | + * |
| 46 | + * @param title the title to create a filename from |
| 47 | + * @param invalidCharacters patter matching invalid characters |
| 48 | + * @param replacementChar the replacement |
| 49 | + * @return the filename |
| 50 | + */ |
| 51 | + private fun createFilename( |
| 52 | + title: String, invalidCharacters: String, |
| 53 | + replacementChar: String |
| 54 | + ): String { |
| 55 | + return title.replace(invalidCharacters.toRegex(), replacementChar) |
| 56 | + } |
| 57 | +} |
0 commit comments