/
AmazonS3.swift
256 lines (220 loc) · 10.2 KB
/
AmazonS3.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import Foundation
import AWSCore
import AWSS3
import PromiseKit
public class AmazonS3 {
public static let shared = AmazonS3()
let deviceDirectoryForUploads: URL
let deviceDirectoryForDownloads: URL
let fileManager = FileManager.default
enum CacheErros: Int {
case miss
case noSuchKey
}
init() {
// create temporary directory
func createLocalTmpDirectory(_ directoryName: String) -> URL? {
do {
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(directoryName)
try
FileManager.default.createDirectory(
at: url,
withIntermediateDirectories: true,
attributes: nil)
return url
} catch let error as NSError {
print("Creating \(directoryName) directory failed. Error: \(error)")
return nil
}
}
// a temporary directory is needed to upload photos,
// because the Amazon's API does not work directly with NSData, but rather with URL
self.deviceDirectoryForUploads = createLocalTmpDirectory("upload")!
// we will also create a temporary directory for download,
// because we will use as cache
self.deviceDirectoryForDownloads = createLocalTmpDirectory("download")!
}
public func performCredentials(regionType: AWSRegionType, identityPoolId: String) {
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: regionType,
identityPoolId: identityPoolId)
let configuration = AWSServiceConfiguration(
region: regionType,
credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
}
fileprivate func checkDownloadCache(bucket: String, key: String) -> Promise<String> {
let keyFullPath = key.components(separatedBy: "/")
let keyDirectories = keyFullPath[0..<keyFullPath.count-1]
var url = deviceDirectoryForDownloads
keyDirectories.forEach { path in
url.appendPathComponent(path)
}
return Promise { fulfill, reject -> Void in
// create cache folder if needed
do {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("RuAWSS3 ERROR: Could not create cache folder")
print(error.localizedDescription)
return reject(error)
}
// check if the file exists in cache
let fileCachePath = url.appendingPathComponent(keyFullPath.last!).systemPath()
if fileManager.fileExists(atPath: fileCachePath) {
// the file exists,
// but we still need to check if it is not obsolete
let attr = try! fileManager.attributesOfItem(atPath: url.path)
let modDate = attr[FileAttributeKey.modificationDate] as! Date
let request = AWSS3HeadObjectRequest()!
request.bucket = bucket
request.key = key
AWSS3.default().headObject(request).continue({
task -> Any? in
if let result = task.result,
((result as AWSS3HeadObjectOutput) != nil) {
let servDate = result.lastModified!
if modDate < servDate {
// obsolete cache file; cache miss
return reject(NSError(domain: "miss", code: CacheErros.miss.rawValue, userInfo: nil))
}
// cache hit
fulfill(fileCachePath)
} else {
// file has been deleted from S3; no such key
do {
try self.fileManager.removeItem(atPath: fileCachePath)
} catch let error as NSError {
print("RuAWSS3 ERROR: Could not delete old cache file")
print(error.localizedDescription)
}
return reject(NSError(domain: "no such key", code: CacheErros.noSuchKey.rawValue, userInfo: nil))
}
return nil
})
} else {
// file does not exist in cache; cache miss
return reject(NSError(domain: "miss", code: CacheErros.miss.rawValue, userInfo: nil))
}
}
}
/**
Download a file from S3
- Parameter bucket: Bucket's name that you want get a file
- Parameter key: Full file's path on bucket
- Returns: Promise with string of the path of the downloaded file
*/
public func download(bucket: String, key: String) -> Promise<String> {
return Promise { fulfill, reject in
firstly {
checkDownloadCache(bucket: bucket, key: key)
}.then { downloadPath -> Void in
// cache hit; send cache file
fulfill(downloadPath)
}.catch { error in
// cache miss
let errorCode = CacheErros.init(rawValue: (error as NSError).code)!
switch errorCode {
case .noSuchKey:
// file does not exist in S3
reject(NSError(domain: "no such key", code: 0, userInfo: nil))
case .miss:
// was cache miss; make download
let downloadRequest = AWSS3TransferManagerDownloadRequest()!
downloadRequest.bucket = bucket
downloadRequest.key = key
let transferManager = AWSS3TransferManager.default()!
transferManager.download(downloadRequest).continue({
task in
// error
if let error = task.error {
let errorCode = (error._userInfo as! [String: String])["Code"]!
return reject(NSError(domain: errorCode, code: 0, userInfo: nil))
}
// succes
let results = task.result! as! AWSS3TransferManagerDownloadOutput
let body = results.body as! URL
do {
let cachePath = self.deviceDirectoryForDownloads.appendingPathComponent(key)
if self.fileManager.fileExists(atPath: cachePath.systemPath()) {
try self.fileManager.removeItem(at: cachePath)
}
try self.fileManager.moveItem(at: body as URL, to: cachePath)
fulfill(cachePath.systemPath())
} catch let error as NSError {
print("RuAWSS3 ERROR: Error trying to move the file to the cache folder!")
print(error.localizedDescription)
fulfill(body.systemPath())
}
return nil
})
}
}
}
}
func imageToUrl(image: UIImage, fileName: String) -> URL {
let fileURL = deviceDirectoryForUploads.appendingPathComponent(fileName)
try! UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
return fileURL
}
/**
Upload a file to S3
- Parameter bucket: Bucket's name that you want upload a file
- Parameter key: Path on S3 where the file will be stored
- Parameter filePath: Path local of the file that you want to upload
- Returns: Promise without parameters
*/
public func upload(bucket: String, key: String, filePath: URL) -> Promise<Void> {
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = filePath
uploadRequest.key = key
uploadRequest.bucket = bucket
let transferManager = AWSS3TransferManager.default()!
return Promise { fulfill, reject in
transferManager.upload(uploadRequest).continue({
task in
if let error = task.error {
let errorCode = (error._userInfo as! [String: String])["Code"]!
reject(NSError(domain: errorCode, code: 0, userInfo: nil))
} else {
fulfill()
}
return nil
})
}
}
/**
Upload a image to S3
- Parameter bucket: Bucket's name that you want upload a file
- Parameter key: Path on S3 where the file will be stored
- Parameter image: Image that you want to upload
- Returns: Promise without parameters
*/
public func uploadImage(bucket: String, key: String, image: UIImage) -> Promise<Void> {
return self.upload(
bucket: bucket,
key: key,
filePath: imageToUrl(image: image, fileName: key.components(separatedBy: "/").last!)
)
}
public func delete(bucket: String, key: String) -> Promise<Void> {
let deleteRequest = AWSS3DeleteObjectRequest()!
deleteRequest.bucket = bucket
deleteRequest.key = key
return Promise { fulfill, reject in
AWSS3.default().deleteObject(deleteRequest).continue({
task -> Any? in
if let error = task.error {
return reject(error)
}
fulfill()
return nil
})
}
}
}
extension URL {
func systemPath() -> String {
return self.absoluteString.replacingOccurrences(of: "file://", with: "")
}
}