Skip to content

Commit 2afebb1

Browse files
Yevhen Babiichuk (DustDFG)theimpulson
andcommitted
Convert newpipe/util/FilenameUtils.java to kotlin
Co-authored-by: Aayush Gupta <aayushgupta219@gmail.com>
1 parent 8ae5a55 commit 2afebb1

2 files changed

Lines changed: 59 additions & 70 deletions

File tree

app/src/main/java/org/schabi/newpipe/util/FilenameUtils.java

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

0 commit comments

Comments
 (0)