Skip to content

Commit f1b1112

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

2 files changed

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

0 commit comments

Comments
 (0)