Improve Unique File Name Search (#5877)

* Modified findUniqueFileName() in UploadWorker.kt to use a random 3-digit alphanumeric hash to append to a file name to make it unique. This improves speed over using an incrementing number to append as there are fewer collisions.

* Modified findUniqueFileName() in UploadWorker.kt to use a random 5-digit numeric hash rather than the previous 3-digit alphanumeric hash

* Removed unnecessary variable "chars"

---------

Co-authored-by: Jinniu Du <127721018+Donutcheese@users.noreply.github.com>
Co-authored-by: Zihan Pan <u7726755@anu.edu.au>
Co-authored-by: Nicolas Raoul <nicolas.raoul@gmail.com>
This commit is contained in:
Alex Gailis 2024-11-14 13:35:05 +11:00 committed by GitHub
parent 634bc3ede1
commit 183e84c098
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -47,6 +47,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.Date
import java.util.Random
import java.util.regex.Pattern
import javax.inject.Inject
@ -548,33 +549,30 @@ class UploadWorker(
}
private fun findUniqueFileName(fileName: String): String {
var sequenceFileName: String?
var sequenceNumber = 1
while (true) {
var sequenceFileName: String? = fileName
val random = Random()
// Loops until sequenceFileName does not match any existing file names
while (mediaClient
.checkPageExistsUsingTitle(
String.format(
"File:%s",
sequenceFileName,
),
).blockingGet()) {
// Generate a random 5-character alphanumeric string
val randomHash = (random.nextInt(90000) + 10000).toString()
sequenceFileName =
if (sequenceNumber == 1) {
fileName
if (fileName.indexOf('.') == -1) {
"$fileName #$randomHash"
} else {
if (fileName.indexOf('.') == -1) {
"$fileName $sequenceNumber"
} else {
val regex =
Pattern.compile("^(.*)(\\..+?)$")
val regexMatcher = regex.matcher(fileName)
regexMatcher.replaceAll("$1 $sequenceNumber$2")
}
val regex =
Pattern.compile("^(.*)(\\..+?)$")
val regexMatcher = regex.matcher(fileName)
regexMatcher.replaceAll("$1 #$randomHash")
}
if (!mediaClient
.checkPageExistsUsingTitle(
String.format(
"File:%s",
sequenceFileName,
),
).blockingGet()
) {
break
}
sequenceNumber++
}
return sequenceFileName!!
}