aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Library/URLAdditions.swift
blob: 0ba21002b3ea110a54a43ebcb66832e8b0db5c68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import Foundation
import UniformTypeIdentifiers

extension URL {
  func generateUniqueFilePath(filename base: String) -> String {
    let fileManager = FileManager.default
    var finalName = base
    var counter = 2
    
    // Helper function to generate a new filename with a counter
    func makeFileName() -> String {
      let baseName = (base as NSString).deletingPathExtension
      let extensionName = (base as NSString).pathExtension
      return extensionName.isEmpty ? "\(baseName) \(counter)" : "\(baseName) \(counter).\(extensionName)"
    }
    
    // Check if file exists and append counter until a unique name is found
    var filePath = self.appending(component: finalName).path(percentEncoded: false)
    while fileManager.fileExists(atPath: filePath) {
      finalName = makeFileName()
      filePath = self.appending(component: finalName).path(percentEncoded: false)
      counter += 1
    }
    
    return filePath
  }
}

extension UTType {
  var canBePreviewedByQuickLook: Bool {
    // QuickLook supports most common document types
    let supportedSupertypes: [UTType] = [
      .image,
      .movie,
      .audio,
      .pdf,
      .font,
      .usdz,
      .text,
      .sourceCode,
      .spreadsheet,
      .presentation,
      
//       Microsoft Office
      .init(filenameExtension: "doc")!,
      .init(filenameExtension: "docx")!,
      .init(filenameExtension: "xls")!,
      .init(filenameExtension: "xlsx")!,
      .init(filenameExtension: "ppt")!,
      .init(filenameExtension: "pptx")!,
    ]
    
    return supportedSupertypes.contains { self.conforms(to: $0) }
  }
}