Skip to content

Commit 183e84c

Browse files
AlexG-2003Donutcheesezihanpannicolas-raoul
authored
Improve Unique File Name Search (commons-app#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 <[email protected]> Co-authored-by: Zihan Pan <[email protected]> Co-authored-by: Nicolas Raoul <[email protected]>
1 parent 634bc3e commit 183e84c

File tree

1 file changed

+22
-24
lines changed

1 file changed

+22
-24
lines changed

app/src/main/java/fr/free/nrw/commons/upload/worker/UploadWorker.kt

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import kotlinx.coroutines.launch
4747
import kotlinx.coroutines.withContext
4848
import timber.log.Timber
4949
import java.util.Date
50+
import java.util.Random
5051
import java.util.regex.Pattern
5152
import javax.inject.Inject
5253

@@ -548,33 +549,30 @@ class UploadWorker(
548549
}
549550

550551
private fun findUniqueFileName(fileName: String): String {
551-
var sequenceFileName: String?
552-
var sequenceNumber = 1
553-
while (true) {
552+
var sequenceFileName: String? = fileName
553+
val random = Random()
554+
555+
// Loops until sequenceFileName does not match any existing file names
556+
while (mediaClient
557+
.checkPageExistsUsingTitle(
558+
String.format(
559+
"File:%s",
560+
sequenceFileName,
561+
),
562+
).blockingGet()) {
563+
564+
// Generate a random 5-character alphanumeric string
565+
val randomHash = (random.nextInt(90000) + 10000).toString()
566+
554567
sequenceFileName =
555-
if (sequenceNumber == 1) {
556-
fileName
568+
if (fileName.indexOf('.') == -1) {
569+
"$fileName #$randomHash"
557570
} else {
558-
if (fileName.indexOf('.') == -1) {
559-
"$fileName $sequenceNumber"
560-
} else {
561-
val regex =
562-
Pattern.compile("^(.*)(\\..+?)$")
563-
val regexMatcher = regex.matcher(fileName)
564-
regexMatcher.replaceAll("$1 $sequenceNumber$2")
565-
}
571+
val regex =
572+
Pattern.compile("^(.*)(\\..+?)$")
573+
val regexMatcher = regex.matcher(fileName)
574+
regexMatcher.replaceAll("$1 #$randomHash")
566575
}
567-
if (!mediaClient
568-
.checkPageExistsUsingTitle(
569-
String.format(
570-
"File:%s",
571-
sequenceFileName,
572-
),
573-
).blockingGet()
574-
) {
575-
break
576-
}
577-
sequenceNumber++
578576
}
579577
return sequenceFileName!!
580578
}

0 commit comments

Comments
 (0)