Skip to content

Commit a6b0e49

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

2 files changed

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

0 commit comments

Comments
 (0)