@@ -51,23 +51,49 @@ public func isLockFileName(_ filename: String) -> Bool {
5151///
5252/// Example for Microsoft Office: `MyDoc.docx` is extracted from `~$MyDoc.docx`.
5353/// Example for LibreOffice: `MyDoc.odt` is extracted from `.~lock.MyDoc.odt#`.
54- ///
54+ /// Filename with <8 characters: Test.docx → lock file: ~$Test.docx
55+ /// Filename with >8 characters: Document.docx → lock file: ~$cument.docx
56+ /// Filename sandbox-style temporary naming like: Welcome123456.doc.sb-d215eb53-IBAwfU
5557/// - Returns: Either the original file name parsed from the given lock file name or `nil`, if it is not a recognized lock file format.
5658///
57- public func originalFileName( fromLockFileName lockFilename: String ) -> String ? {
59+ public func originalFileName( fromLockFileName lockFilename: String , dbManager: FilesDatabaseManager ) -> String ? {
60+ let logger = FileProviderLogger ( category: " localfileutils " , log: dbManager. logger. log)
61+ logger. debug ( " Called originalFileName with lock filename: \( lockFilename) " )
62+
63+ var targetFilePattern = lockFilename
5864 if lockFilename. hasPrefix ( " ~$ " ) {
59- // Remove the "~$" prefix
6065 let index = lockFilename. index ( lockFilename. startIndex, offsetBy: 2 )
61- return String ( lockFilename [ index... ] )
66+ targetFilePattern = String ( lockFilename [ index... ] )
6267 }
6368
6469 if lockFilename. hasPrefix ( " .~lock. " ) && lockFilename. hasSuffix ( " # " ) {
65- // Strip the prefix and suffix
6670 let start = lockFilename. index ( lockFilename. startIndex, offsetBy: 7 )
6771 let end = lockFilename. index ( before: lockFilename. endIndex)
68- return String ( lockFilename [ start..< end] )
72+ targetFilePattern = String ( lockFilename [ start..< end] )
6973 }
74+
75+ if let sbRange = lockFilename. range ( of: " .sb- " ) {
76+ targetFilePattern = String ( lockFilename [ ..< sbRange. lowerBound] )
77+ }
78+
79+ logger. debug ( " Target filename is: \( targetFilePattern) " )
7080
71- // Not a recognized lock file
81+ guard let itemsMatchingMetadata = dbManager. itemsMetadataFromPattern ( pattern: targetFilePattern) else {
82+ logger. debug ( " Could not find files in db matching pattern: \( targetFilePattern) " )
83+ return targetFilePattern
84+ }
85+
86+ for file in itemsMatchingMetadata {
87+ let potentialOriginalFile = file. fileName
88+
89+ if lockFilename == potentialOriginalFile {
90+ logger. debug ( " Lock filename \( lockFilename) is the same as filename found in db \( potentialOriginalFile) " )
91+ continue ;
92+ }
93+
94+ logger. debug ( " Matched lock filename \( lockFilename) to original filename \( potentialOriginalFile) " )
95+ return potentialOriginalFile
96+ }
97+
7298 return nil
7399}
0 commit comments