Skip to content

Commit 5a9dbd0

Browse files
author
Yevhen Babiichuk (DustDFG)
committed
Convert newpipe/util/FilenameUtils.java to kotlin
1 parent 8e32e7a commit 5a9dbd0

2 files changed

Lines changed: 61 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: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
var selectedCharset = sharedPreferences.getString(
31+
context.getString(R.string.settings_file_charset_key), ""
32+
)!!
33+
34+
if (selectedCharset.isEmpty()) {
35+
selectedCharset = defaultCharset
36+
}
37+
38+
val charset = when (selectedCharset) {
39+
charsetLd -> CHARSET_ONLY_LETTERS_AND_DIGITS
40+
charsetMs -> CHARSET_MOST_SPECIAL
41+
else -> selectedCharset // Is the user using a custom charset?
42+
}
43+
44+
return createFilename(title, charset, Matcher.quoteReplacement(replacementChar))
45+
}
46+
47+
/**
48+
* Create a valid filename.
49+
*
50+
* @param title the title to create a filename from
51+
* @param invalidCharacters patter matching invalid characters
52+
* @param replacementChar the replacement
53+
* @return the filename
54+
*/
55+
private fun createFilename(
56+
title: String, invalidCharacters: String,
57+
replacementChar: String
58+
): String {
59+
return title.replace(invalidCharacters.toRegex(), replacementChar)
60+
}
61+
}

0 commit comments

Comments
 (0)