-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Media.swift
109 lines (93 loc) · 2.98 KB
/
Media.swift
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import Foundation
import UniformTypeIdentifiers
extension Media {
// MARK: - AutoUpload Failure Count
static let maxAutoUploadFailureCount = 3
/// Increments the AutoUpload failure count for this Media object.
///
@objc
func incrementAutoUploadFailureCount() {
autoUploadFailureCount = NSNumber(value: autoUploadFailureCount.intValue + 1)
}
/// Resets the AutoUpload failure count for this Media object.
///
@objc
func resetAutoUploadFailureCount() {
autoUploadFailureCount = 0
}
/// Returns true if a new attempt to upload the media will be done later.
/// Otherwise, false.
///
func willAttemptToUploadLater() -> Bool {
return autoUploadFailureCount.intValue < Media.maxAutoUploadFailureCount
}
/// Returns true if media has any associated post
///
func hasAssociatedPost() -> Bool {
guard let posts = posts else {
return false
}
return !posts.isEmpty
}
/// If `false`, the only course of action is to cancel the upload.
var canRetry: Bool {
absoluteLocalURL != nil
}
// MARK: - Media Type
/// Returns the MIME type, e.g. "image/png".
@objc var mimeType: String? {
guard let fileExtension = self.fileExtension(),
let type = UTType(filenameExtension: fileExtension),
let mimeType = type.preferredMIMEType else {
return "application/octet-stream"
}
return mimeType
}
func setMediaType(forFilenameExtension filenameExtension: String) {
let type = UTType(filenameExtension: filenameExtension)
setMediaType(getMediaType(for: type))
}
func setMediaType(forMimeType mimeType: String) {
var mimeType = mimeType
if mimeType == "video/videopress" {
mimeType = "video/mp4"
}
setMediaType(getMediaType(for: UTType(mimeType: mimeType)))
}
private func setMediaType(_ newType: MediaType) {
guard self.mediaType != newType else { return }
self.mediaType = newType
}
private func getMediaType(for type: UTType?) -> MediaType {
type.map(MediaType.init) ?? .document
}
// MARK: - Media Link
var link: String {
get {
guard let siteURL = self.blog.url,
let mediaID = self.mediaID else {
return ""
}
return "\(siteURL)/?p=\(mediaID)"
}
}
}
private extension MediaType {
init(type: UTType) {
if type.conforms(to: .image) {
self = .image
} else if type.conforms(to: .video) {
self = .video
} else if type.conforms(to: .movie) {
self = .video
} else if type.conforms(to: .mpeg4Movie) {
self = .video
} else if type.conforms(to: .presentation) {
self = .powerpoint
} else if type.conforms(to: .audio) {
self = .audio
} else {
self = .document
}
}
}