-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathS3Example.cs
311 lines (273 loc) · 10.7 KB
/
S3Example.cs
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the AWS Mobile SDK For Unity
// Sample Application License Agreement (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located
// in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;
using System.IO;
using System;
using Amazon.S3.Util;
using System.Collections.Generic;
using Amazon.CognitoIdentity;
using Amazon;
namespace AWSSDK.Examples
{
public class S3Example : MonoBehaviour
{
public string IdentityPoolId = "";
public string CognitoIdentityRegion = RegionEndpoint.USEast1.SystemName;
private RegionEndpoint _CognitoIdentityRegion
{
get { return RegionEndpoint.GetBySystemName(CognitoIdentityRegion); }
}
public string S3Region = RegionEndpoint.USEast1.SystemName;
private RegionEndpoint _S3Region
{
get { return RegionEndpoint.GetBySystemName(S3Region); }
}
public string S3BucketName = null;
public string SampleFileName = null;
public Button GetBucketListButton = null;
public Button PostBucketButton = null;
public Button GetObjectsListButton = null;
public Button DeleteObjectButton = null;
public Button GetObjectButton = null;
public Text ResultText = null;
void Start()
{
UnityInitializer.AttachToGameObject(this.gameObject);
AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;
GetBucketListButton.onClick.AddListener(() => { GetBucketList(); });
PostBucketButton.onClick.AddListener(() => { PostObject(); });
GetObjectsListButton.onClick.AddListener(() => { GetObjects(); });
DeleteObjectButton.onClick.AddListener(() => { DeleteObject(); });
GetObjectButton.onClick.AddListener(() => { GetObject(); });
}
#region private members
private IAmazonS3 _s3Client;
private AWSCredentials _credentials;
private AWSCredentials Credentials
{
get
{
if (_credentials == null)
_credentials = new CognitoAWSCredentials(IdentityPoolId, _CognitoIdentityRegion);
return _credentials;
}
}
private IAmazonS3 Client
{
get
{
if (_s3Client == null)
{
_s3Client = new AmazonS3Client(Credentials, _S3Region);
}
//test comment
return _s3Client;
}
}
#endregion
#region Get Bucket List
/// <summary>
/// Example method to Demostrate GetBucketList
/// </summary>
public void GetBucketList()
{
ResultText.text = "Fetching all the Buckets";
Client.ListBucketsAsync(new ListBucketsRequest(), (responseObject) =>
{
ResultText.text += "\n";
if (responseObject.Exception == null)
{
ResultText.text += "Got Response \nPrinting now \n";
responseObject.Response.Buckets.ForEach((s3b) =>
{
ResultText.text += string.Format("bucket = {0}, created date = {1} \n", s3b.BucketName, s3b.CreationDate);
});
}
else
{
ResultText.text += "Got Exception \n";
}
});
}
#endregion
/// <summary>
/// Get Object from S3 Bucket
/// </summary>
private void GetObject()
{
ResultText.text = string.Format("fetching {0} from bucket {1}", SampleFileName, S3BucketName);
Client.GetObjectAsync(S3BucketName, SampleFileName, (responseObj) =>
{
string data = null;
var response = responseObj.Response;
if (response.ResponseStream != null)
{
using (StreamReader reader = new StreamReader(response.ResponseStream))
{
data = reader.ReadToEnd();
}
ResultText.text += "\n";
ResultText.text += data;
}
});
}
/// <summary>
/// Post Object to S3 Bucket.
/// </summary>
public void PostObject()
{
ResultText.text = "Retrieving the file";
string fileName = GetFileHelper();
var stream = new FileStream(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
ResultText.text += "\nCreating request object";
var request = new PostObjectRequest()
{
Region = _S3Region,
Bucket = S3BucketName,
Key = fileName,
InputStream = stream,
CannedACL = S3CannedACL.Private
};
ResultText.text += "\nMaking HTTP post call";
Client.PostObjectAsync(request, (responseObj) =>
{
if (responseObj.Exception == null)
{
ResultText.text += string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket);
}
else
{
ResultText.text += "\nException while posting the result object";
ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString());
}
});
}
/// <summary>
/// Get Objects from S3 Bucket
/// </summary>
public void GetObjects()
{
ResultText.text = "Fetching all the Objects from " + S3BucketName;
var request = new ListObjectsRequest()
{
BucketName = S3BucketName
};
Client.ListObjectsAsync(request, (responseObject) =>
{
ResultText.text += "\n";
if (responseObject.Exception == null)
{
ResultText.text += "Got Response \nPrinting now \n";
responseObject.Response.S3Objects.ForEach((o) =>
{
ResultText.text += string.Format("{0}\n", o.Key);
});
}
else
{
ResultText.text += "Got Exception \n";
}
});
}
/// <summary>
/// Delete Objects in S3 Bucket
/// </summary>
public void DeleteObject()
{
ResultText.text = string.Format("deleting {0} from bucket {1}", SampleFileName, S3BucketName);
List<KeyVersion> objects = new List<KeyVersion>();
objects.Add(new KeyVersion()
{
Key = SampleFileName
});
var request = new DeleteObjectsRequest()
{
BucketName = S3BucketName,
Objects = objects
};
Client.DeleteObjectsAsync(request, (responseObj) =>
{
ResultText.text += "\n";
if (responseObj.Exception == null)
{
ResultText.text += "Got Response \n \n";
ResultText.text += string.Format("deleted objects \n");
responseObj.Response.DeletedObjects.ForEach((dObj) =>
{
ResultText.text += dObj.Key;
});
}
else
{
ResultText.text += "Got Exception \n";
}
});
}
#region helper methods
private string GetFileHelper()
{
var fileName = SampleFileName;
if (!File.Exists(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName))
{
var streamReader = File.CreateText(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName);
streamReader.WriteLine("This is a sample s3 file uploaded from unity s3 sample");
streamReader.Close();
}
return fileName;
}
private string GetPostPolicy(string bucketName, string key, string contentType)
{
bucketName = bucketName.Trim();
key = key.Trim();
// uploadFileName cannot start with /
if (!string.IsNullOrEmpty(key) && key[0] == '/')
{
throw new ArgumentException("uploadFileName cannot start with / ");
}
contentType = contentType.Trim();
if (string.IsNullOrEmpty(bucketName))
{
throw new ArgumentException("bucketName cannot be null or empty. It's required to build post policy");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("uploadFileName cannot be null or empty. It's required to build post policy");
}
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentException("contentType cannot be null or empty. It's required to build post policy");
}
string policyString = null;
int position = key.LastIndexOf('/');
if (position == -1)
{
policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +
bucketName + "\"},[\"starts-with\", \"$key\", \"" + "\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + contentType + "\"" + "]]}";
}
else
{
policyString = "{\"expiration\": \"" + DateTime.UtcNow.AddHours(24).ToString("yyyy-MM-ddTHH:mm:ssZ") + "\",\"conditions\": [{\"bucket\": \"" +
bucketName + "\"},[\"starts-with\", \"$key\", \"" + key.Substring(0, position) + "/\"],{\"acl\": \"private\"},[\"eq\", \"$Content-Type\", " + "\"" + contentType + "\"" + "]]}";
}
return policyString;
}
}
#endregion
}