forked from microsoft/Appsample-Photosharing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DocumentDbRepository.cs
1265 lines (1061 loc) · 52 KB
/
DocumentDbRepository.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using PhotoSharingApp.AppService.Shared.Context;
using PhotoSharingApp.AppService.Shared.Models.DocumentDB;
using PhotoSharingApp.Portable.DataContracts;
namespace PhotoSharingApp.AppService.Shared.Repositories
{
/// <summary>
/// The DocumentDB data layer class.
/// </summary>
public class DocumentDbRepository : IRepository
{
private const int PhotoStreamPageSize = 100;
private const string SystemUserId = "ffffffff-ffff-ffff-ffff-ffffffffffff";
// Stored Procedures
private const string TransferGoldStoredProcedureScriptFileName = @"Models\DocumentDB\js\transferGoldStoredProcedure.js";
private const string TransferGoldStoredProcedureId = "transferGold";
private const string GetRecentPhotosForCategoriesStoredProcedureScriptFileName = @"Models\DocumentDB\js\getRecentPhotosForCategoriesStoredProcedure.js";
private const string GetRecentPhotosForCategoriesStoredProcedureId = "getRecentPhotosForCategories";
private readonly string _currentDocumentVersion;
private readonly DocumentClient _documentClient;
private readonly string _documentCollectionId;
private readonly string _documentDataBaseId;
private readonly int _firstProfilePhotoUpdateGoldIncrement;
private readonly int _newUserGoldBalance;
private readonly int _maxReportsPermitted;
/// <summary>
/// The <see cref="DocumentDbRepository" /> constructor.
/// </summary>
/// <param name="environmentDefinition">The specified environment definition.</param>
public DocumentDbRepository(EnvironmentDefinitionBase environmentDefinition)
{
_maxReportsPermitted = environmentDefinition.MaxReports;
_newUserGoldBalance = environmentDefinition.NewUserGoldBalance;
_firstProfilePhotoUpdateGoldIncrement = environmentDefinition.FirstProfilePhotoUpdateGoldAward;
var documentDbStorage = environmentDefinition.DocumentDbStorage;
_documentDataBaseId = documentDbStorage.DataBaseId;
_documentCollectionId = documentDbStorage.CollectionId;
try
{
_documentClient = new DocumentClient(new Uri(documentDbStorage.EndpointUrl),
documentDbStorage.AuthorizationKey);
}
catch (UriFormatException)
{
throw new DataLayerException(DataLayerError.InvalidConfiguration,
$"Attempted to create the DocumentClient with EndpointUrl {documentDbStorage.EndpointUrl}" +
$" and AuthorizationKey {documentDbStorage.AuthorizationKey} failed");
}
_currentDocumentVersion = BaseDocument.DocumentVersionIdentifier;
}
/// <summary>
/// Checks if database and collection exist.
/// </summary>
/// <returns>True, if both exist. False, otherwise.</returns>
public bool CheckIfDatabaseAndCollectionExist()
{
var database =
_documentClient.CreateDatabaseQuery()
.Where(db => db.Id == _documentDataBaseId)
.AsEnumerable()
.FirstOrDefault();
// The database doesn't exist.
if (database == null)
{
return false;
}
var documentCollection =
_documentClient.CreateDocumentCollectionQuery(database.SelfLink)
.Where(c => c.Id == _documentCollectionId)
.AsEnumerable()
.FirstOrDefault();
// The collection doesn't exist.
if (documentCollection == null)
{
return false;
}
return true;
}
/// <summary>
/// Creates a new category with the provided name.
/// </summary>
/// <param name="name">The category name to be created.</param>
/// <returns>The created category.</returns>
public async Task<CategoryContract> CreateCategory(string name)
{
var document = _documentClient.CreateDocumentQuery<CategoryDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == CategoryDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(c => c.Name == name)
.AsEnumerable().FirstOrDefault();
if (document != null)
{
throw new DataLayerException(DataLayerError.DuplicateKeyInsert, $"Category with name {name} already exists");
}
var categoryDocument = new CategoryDocument
{
Name = name
};
var result = await _documentClient.CreateDocumentAsync(DocumentCollectionUri, categoryDocument);
categoryDocument.Id = result.Resource.Id;
return categoryDocument.ToContract();
}
private async Task<DocumentCollection> CreateDocumentDbCollection(Database database)
{
try
{
return await _documentClient.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection
{
Id = _documentCollectionId
});
}
catch (Exception)
{
throw new DataLayerException(DataLayerError.Unknown, $"Failed to create DocumentDB Collection {_documentCollectionId}");
}
}
private async Task<Database> CreateDocumentDbDatabase()
{
try
{
return await _documentClient.CreateDatabaseAsync(new Database
{
Id = _documentDataBaseId
});
}
catch (Exception)
{
throw new DataLayerException(DataLayerError.Unknown, $"Failed to create DocumentDB Database {_documentDataBaseId}");
}
}
private async Task CreateGetRecentPhotosForCategoriesStoredProcedure(string serverPath)
{
var sproc = new StoredProcedure
{
Id = GetRecentPhotosForCategoriesStoredProcedureId,
Body = File.ReadAllText(Path.Combine(serverPath, GetRecentPhotosForCategoriesStoredProcedureScriptFileName))
};
await _documentClient.UpsertStoredProcedureAsync(DocumentCollectionUri, sproc);
}
/// <summary>
/// Processes a list of photo json documents and creates <see cref="PhotoContract" /> for them,
/// as well as fetching and setting the proper <see cref="UserContract" /> objects for PhotoContract.User
/// and AnnotationContract.From fields.
/// </summary>
/// <param name="photoDocuments"></param>
/// <returns>A list of photo contracts.</returns>
private async Task<IList<PhotoContract>> CreatePhotoContractsAndLoadUserData(IList<PhotoDocument> photoDocuments)
{
// Retrieve all the user documents for the user ids of the photo owners and annotation authors.
var userDocumentsForPhotosAndAnnotations =
await GetAllUserDocumentsFromIdList(photoDocuments.Select(p => p.UserId)
.Concat(photoDocuments.SelectMany(p => p.Annotations).Select(a => a.From)).ToList());
// Pass in the collection of users so ToContract can set the proper user objects for PhotoContract and the AnnotationContracts.
return
photoDocuments.Select(photoDocument => photoDocument.ToContract(userDocumentsForPhotosAndAnnotations))
.ToList();
}
private async Task CreateTransferGoldStoredProcedure(string serverPath)
{
var sproc = new StoredProcedure
{
Id = TransferGoldStoredProcedureId,
Body = File.ReadAllText(Path.Combine(serverPath, TransferGoldStoredProcedureScriptFileName))
};
await _documentClient.UpsertStoredProcedureAsync(DocumentCollectionUri, sproc);
}
/// <summary>
/// Inserts a new user record in the database.
/// </summary>
/// <param name="registrationReference">The Azure Mobile Service user id.</param>
/// <returns>Updated user object.</returns>
public async Task<UserContract> CreateUser(string registrationReference)
{
//Create the new user document with default values and starting gold balance.
var userDocument = new UserDocument
{
GoldBalance = 0,
RegistrationReference = registrationReference,
CreatedAt = new DateDocument
{
Date = DateTime.UtcNow
},
ModifiedAt = new DateDocument
{
Date = DateTime.UtcNow
},
GoldGiven = 0
};
var createdUserId =
(await _documentClient.CreateDocumentAsync(DocumentCollectionUri, userDocument)).Resource.Id;
// Handle gold balance changes and create transaction record
await ExecuteGoldTransactionSproc(createdUserId, SystemUserId, _newUserGoldBalance,
GoldTransactionType.WelcomeGoldTransaction);
userDocument.Id = createdUserId;
userDocument.GoldBalance = _newUserGoldBalance;
return userDocument.ToContract();
}
/// <summary>
/// Deletes an annotation.
/// </summary>
/// <param name="annotationId">Id of annotation to be deleted.</param>
/// <param name="userRegistrationReference">userRegistrationReference of annotation to be deleted.</param>
public async Task DeleteAnnotation(string annotationId, string userRegistrationReference)
{
var photoDocument = GetParentPhotoDocument(annotationId);
photoDocument.Annotations = photoDocument.Annotations.Where(a => a.Id != annotationId).ToList();
await ReplacePhotoDocument(photoDocument);
}
/// <summary>
/// Deletes all the data for the provided photo id.
/// </summary>
/// <param name="photoId">Id of the photo to be deleted.</param>
/// <param name="userRegistrationReference">Azure Mobile Service user id.</param>
public async Task DeletePhoto(string photoId, string userRegistrationReference)
{
try
{
var photoToDelete = GetPhotoDocument(photoId);
var photoOwner = GetUserDocumentByUserId(photoToDelete.UserId);
if (photoOwner.RegistrationReference != userRegistrationReference)
{
throw new DataLayerException(
DataLayerError.NotFound,
$"User={userRegistrationReference} doesn't own the photo, invalid DeletePhoto request.");
}
if (photoOwner.ProfilePhotoId == photoId)
{
throw new DataLayerException(
DataLayerError.NotFound,
$"Photo={photoId} is currently a profile picture and cannot be deleted.");
}
await _documentClient.DeleteDocumentAsync(
UriFactory.CreateDocumentUri(
_documentDataBaseId,
_documentCollectionId,
photoId));
}
catch (DocumentClientException ex)
{
throw new DataLayerException(DataLayerError.Unknown, ex.Message, ex);
}
}
/// <summary>
/// Initiates the process of releasing resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases resources.
/// </summary>
/// <param name="disposing">If we need to release resources or not.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_documentClient.Dispose();
}
}
private string DocumentCollectionUri
{
get { return $"dbs/{_documentDataBaseId}/colls/{_documentCollectionId}"; }
}
private async Task<GoldTransactionDocument> ExecuteGoldTransactionSproc(string toUserId, string fromUserId,
int goldValue, GoldTransactionType transactionType, string photoId = null)
{
try
{
return
await
_documentClient.ExecuteStoredProcedureAsync<GoldTransactionDocument>(
TransferGoldStoredProcedureUri,
toUserId, fromUserId, goldValue, transactionType, photoId, (fromUserId == SystemUserId),
_currentDocumentVersion);
}
catch (Exception ex)
{
throw new DataLayerException(DataLayerError.FailedGoldTransaction,
$"An error occured during the gold transaction \"{ex.Message}\", any unfinished changes have been rolled back");
}
}
private async Task<IList<CategoryDocument>> GetAllCategoryDocuments()
{
var query = _documentClient.CreateDocumentQuery<CategoryDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == CategoryDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.AsDocumentQuery();
var documentResponse = await query.ExecuteNextAsync<CategoryDocument>();
return documentResponse.ToList();
}
private async Task<IList<UserDocument>> GetAllUserDocumentsFromIdList(ICollection<string> listOfUserIds)
{
listOfUserIds = listOfUserIds.Distinct().ToList();
var query = _documentClient.CreateDocumentQuery<UserDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == UserDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(u => listOfUserIds.Contains(u.Id))
.AsDocumentQuery();
var documentResponse = await query.ExecuteNextAsync<UserDocument>();
return documentResponse.ToList();
}
private AnnotationDocument GetAnnotationDocument(string annotationId)
{
var photoDocument = GetParentPhotoDocument(annotationId);
var annotationDocument = photoDocument.Annotations.FirstOrDefault(a => a.Id == annotationId);
if (annotationDocument == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No annotation with id {annotationId} found");
}
return annotationDocument;
}
/// <summary>
/// Fetches all the categories and sorts them by name.
/// </summary>
/// <returns>List interface of CategoryContract sorted by name.</returns>
public async Task<IList<CategoryContract>> GetCategories()
{
return (await GetAllCategoryDocuments()).Select(c => c.ToContract()).OrderBy(c => c.Name).ToList();
}
/// <summary>
/// Retrieves all the categories that have atleast one photo and also retrieves
/// number of provided thumbnails for the photos in each category.
/// </summary>
/// <param name="numberOfThumbnails">Max number of thumbnails per category.</param>
/// <returns>List interface of CategoryPreviewContract.</returns>
public async Task<IList<CategoryPreviewContract>> GetCategoriesPreview(int numberOfThumbnails)
{
var results = new List<CategoryPreviewContract>();
var photosQuery = await _documentClient.ExecuteStoredProcedureAsync<List<PhotoDocument>>(
GetRecentPhotosForCategoriesStoredProcedureUri,
numberOfThumbnails,
_currentDocumentVersion);
var mostRecentCategoryPhotos = photosQuery.Response;
if (mostRecentCategoryPhotos != null && mostRecentCategoryPhotos.Any())
{
// Create a collection of all categories represented in the list of photos we received
var allCategories =
mostRecentCategoryPhotos.GroupBy(p => p.CategoryId)
.Select(group => new CategoryContract { Id = group.First().CategoryId, Name = group.First().CategoryName });
// Create a CategoryPreviewContract for each category represented
// to contain its photos
foreach (var category in allCategories)
{
var photoDocuments = mostRecentCategoryPhotos.Where(p => p.CategoryId == category.Id).ToList();
if (photoDocuments.Any())
{
results.Add(new CategoryPreviewContract
{
Id = category.Id,
Name = category.Name,
PhotoThumbnails = photoDocuments.Select(p => new PhotoThumbnailContract
{
CreatedAt = p.CreatedDateTime.Date,
ImageUrl = p.ThumbnailUrl
}).OrderByDescending(ptc => ptc.CreatedAt).ToList()
});
}
}
}
return results;
}
private CategoryDocument GetCategoryDocument(string categoryId)
{
var category = _documentClient.CreateDocumentQuery<CategoryDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == CategoryDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(c => c.Id == categoryId)
.AsEnumerable().FirstOrDefault();
if (category == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No category with id {categoryId} found");
}
return category;
}
/// <summary>
/// Fetches the photo stream data for a provided category.
/// </summary>
/// <param name="categoryId">The category id.</param>
/// <param name="continuationToken">Continuation token from previous <see cref="PagedResponse{TContract}" />.</param>
/// <returns>List of photos up to the page size.</returns>
public async Task<PagedResponse<PhotoContract>> GetCategoryPhotoStream(string categoryId,
string continuationToken = null)
{
var feedOptions = new FeedOptions
{
MaxItemCount = PhotoStreamPageSize,
RequestContinuation = continuationToken
};
var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(p => p.CategoryId == categoryId)
.Where(p => p.Status == PhotoStatus.Active)
.OrderByDescending(p => p.CreatedDateTime.Epoch)
.AsDocumentQuery();
var documentResponse = await query.ExecuteNextAsync<PhotoDocument>();
var photoContracts = await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());
var result = new PagedResponse<PhotoContract>
{
Items = photoContracts,
ContinuationToken = documentResponse.ResponseContinuation
};
return result;
}
/// <summary>
/// Gets hero photos.
/// </summary>
/// <param name="count">The number of hero photos.</param>
/// <param name="daysOld">The number of days old the photos can be.</param>
/// <returns>List interface of hero photos.</returns>
public async Task<IList<PhotoContract>> GetHeroPhotos(int count, int daysOld)
{
var feedOptions = new FeedOptions
{
MaxItemCount = count
};
var cutOffDate = new DateDocument
{
Date = DateTime.Now.AddDays(-daysOld)
};
var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(p => p.Status == PhotoStatus.Active)
.Where(p => p.CreatedDateTime.Epoch >= cutOffDate.Epoch)
.OrderByDescending(p => p.GoldCount)
.AsDocumentQuery();
var documentResponse = await query.ExecuteNextAsync<PhotoDocument>();
return await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());
}
private async Task<IList<LeaderboardEntryContract<UserContract>>> GetHighestGivingUsers(int count)
{
var feedOptions = new FeedOptions
{
MaxItemCount = count
};
var userQuery = _documentClient.CreateDocumentQuery<UserDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == UserDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(u => u.Id != SystemUserId)
.OrderByDescending(u => u.GoldGiven)
.AsDocumentQuery();
var userDocumentResponse = await userQuery.ExecuteNextAsync<UserDocument>();
var rank = 1;
var mostGivingUsers = userDocumentResponse.Select(u => new LeaderboardEntryContract<UserContract>
{
Model = u.ToContract(),
Value = u.GoldGiven,
Rank = rank++
}).ToList();
return mostGivingUsers;
}
private async Task<IList<LeaderboardEntryContract<CategoryContract>>> GetHighestNetWorthCategories(int count)
{
var allPhotosQuery = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.AsDocumentQuery();
var allPhotos = await allPhotosQuery.ExecuteNextAsync<PhotoDocument>();
var allCategories = allPhotos.GroupBy(p => p.CategoryId).Select(g => new CategoryContract
{
Id = g.Key,
Name = g.FirstOrDefault()?.CategoryName
});
var allCategoryWorths = new List<LeaderboardEntryContract<CategoryContract>>();
foreach (var categoryContract in allCategories)
{
var categoryWorth = allPhotos.Where(p => p.CategoryId == categoryContract.Id).Sum(p => p.GoldCount);
allCategoryWorths.Add(new LeaderboardEntryContract<CategoryContract>
{
Model = categoryContract,
Value = categoryWorth
});
}
var mostGoldCategories = allCategoryWorths.OrderByDescending(e => e.Value).Take(count).ToList();
var rank = 1;
foreach (var leaderboardEntryContract in mostGoldCategories)
{
leaderboardEntryContract.Rank = rank++;
}
return mostGoldCategories;
}
private async Task<IList<LeaderboardEntryContract<PhotoContract>>> GetHighestNetWorthPhotos(int count)
{
var feedOptions = new FeedOptions
{
MaxItemCount = count
};
var photoQuery = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(p => p.Status == PhotoStatus.Active)
.OrderByDescending(p => p.GoldCount)
.AsDocumentQuery();
var photoDocumentResponse = await photoQuery.ExecuteNextAsync<PhotoDocument>();
var photoContracts = await CreatePhotoContractsAndLoadUserData(photoDocumentResponse.ToList());
var rank = 1;
var mostGoldPhotos = photoContracts.Select(p => new LeaderboardEntryContract<PhotoContract>
{
Model = p,
Value = p.NumberOfGoldVotes,
Rank = rank++
}).ToList();
return mostGoldPhotos;
}
private async Task<IList<LeaderboardEntryContract<UserContract>>> GetHighestNetWorthUser(int count)
{
var feedOptions = new FeedOptions
{
MaxItemCount = count
};
var userQuery = _documentClient.CreateDocumentQuery<UserDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == UserDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(u => u.Id != SystemUserId)
.OrderByDescending(u => u.GoldBalance)
.AsDocumentQuery();
var userDocumentResponse = await userQuery.ExecuteNextAsync<UserDocument>();
var rank = 1;
var mostGoldUsers = userDocumentResponse.Select(u => new LeaderboardEntryContract<UserContract>
{
Model = u.ToContract(),
Value = u.GoldBalance,
Rank = rank++
}).ToList();
return mostGoldUsers;
}
/// <summary>
/// Gets the leaderboard data.
/// </summary>
/// <param name="mostGoldCategoriesCount">Count of categories.</param>
/// <param name="mostGoldPhotosCount">Count of photos.</param>
/// <param name="mostGoldUsersCount">Count of wealthiest users.</param>
/// <param name="mostGivingUsersCount">Count of most giving users.</param>
/// <returns>The leaderboard data.</returns>
public async Task<LeaderboardContract> GetLeaderboard(int mostGoldCategoriesCount, int mostGoldPhotosCount,
int mostGoldUsersCount, int mostGivingUsersCount)
{
return new LeaderboardContract
{
MostGoldCategories = await GetHighestNetWorthCategories(mostGoldCategoriesCount),
MostGoldPhotos = await GetHighestNetWorthPhotos(mostGoldPhotosCount),
MostGoldUsers = await GetHighestNetWorthUser(mostGoldUsersCount),
MostGivingUsers = await GetHighestGivingUsers(mostGivingUsersCount)
};
}
private PhotoDocument GetParentPhotoDocument(string annotationId)
{
var photoQuery = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.SelectMany(p => p.Annotations
.Where(a => a.Id == annotationId)
.Select(a => new { photo = p }
))
.AsEnumerable().FirstOrDefault();
var photoDocument = photoQuery?.photo;
if (photoDocument == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No annotation with id {annotationId} found");
}
return photoDocument;
}
/// <summary>
/// Gets the photo data for provided photo id.
/// </summary>
/// <param name="id">The photo id.</param>
/// <returns>The requested photo.</returns>
public async Task<PhotoContract> GetPhoto(string id)
{
var document = GetPhotoDocument(id);
return (await CreatePhotoContractsAndLoadUserData(new List<PhotoDocument> { document })).FirstOrDefault();
}
private PhotoDocument GetPhotoDocument(string id)
{
var document = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(r => r.Id == id)
.AsEnumerable().FirstOrDefault();
if (document == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No photo with id {id} found");
}
return document;
}
/// <summary>
/// Gets the list of photos with a specific status.
/// </summary>
/// <param name="status">The photo status.</param>
/// <returns>A list of photos with provided status.</returns>
public async Task<PagedResponse<PhotoContract>> GetPhotosWithStatus(PhotoStatus status)
{
var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(p => p.Status == status);
var documentQuery = query
.OrderByDescending(p => p.CreatedDateTime.Epoch)
.AsDocumentQuery();
var documentResponse = await documentQuery.ExecuteNextAsync<PhotoDocument>();
var photoContracts = await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());
var result = new PagedResponse<PhotoContract>
{
Items = photoContracts,
ContinuationToken = documentResponse.ResponseContinuation
};
return result;
}
private string GetRecentPhotosForCategoriesStoredProcedureUri
{
get { return $"{StoredProceduresUri}/{GetRecentPhotosForCategoriesStoredProcedureId}"; }
}
/// <summary>
/// Gets the user by an existing app user id OR registrationReference
/// from Azure Mobile Services auth mechanism as the userId may not be known
/// at time of entry.
/// </summary>
/// <param name="userId">The app user id.</param>
/// <param name="registrationReference">[Optional] The Azure App Service user id. Default value is null.</param>
/// <returns>UserContract</returns>
public Task<UserContract> GetUser(string userId, string registrationReference = null)
{
try
{
if (!string.IsNullOrEmpty(userId))
{
return Task.FromResult(GetUserDocumentByUserId(userId).ToContract());
}
return Task.FromResult(GetUserDocumentByRegistrationReference(registrationReference).ToContract());
}
catch (DataLayerException e)
{
// If the user does not exist return a blank user.
if (e.Error == DataLayerError.NotFound)
{
return Task.FromResult(new UserContract());
}
throw new DataLayerException(DataLayerError.Unknown, "Unknown error occured");
}
}
private UserDocument GetUserDocumentByRegistrationReference(string registrationReference)
{
var user = _documentClient.CreateDocumentQuery<UserDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == UserDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(u => u.RegistrationReference == registrationReference)
.AsEnumerable().FirstOrDefault();
if (user == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No user with registrationReference {registrationReference} found");
}
return user;
}
private UserDocument GetUserDocumentByUserId(string userId)
{
var user = _documentClient.CreateDocumentQuery<UserDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == UserDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(u => u.Id == userId)
.AsEnumerable().FirstOrDefault();
if (user == null)
{
throw new DataLayerException(DataLayerError.NotFound, $"No user with id {userId} found");
}
return user;
}
/// <summary>
/// Fetches the photo stream data for a specified user.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="continuationToken">Last captured ticks in the form of a string.</param>
/// <param name="includeNonActivePhotos">By default, false. If true, non-active photos are included.</param>
/// <returns>List of photos up to the page size.</returns>
public async Task<PagedResponse<PhotoContract>> GetUserPhotoStream(string userId, string continuationToken, bool includeNonActivePhotos = false)
{
var feedOptions = new FeedOptions
{
MaxItemCount = PhotoStreamPageSize,
RequestContinuation = continuationToken
};
var query = _documentClient.CreateDocumentQuery<PhotoDocument>(DocumentCollectionUri,
feedOptions)
.Where(d => d.DocumentType == PhotoDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(p => p.UserId == userId);
if (!includeNonActivePhotos)
{
query = query
.Where(p => p.Status == PhotoStatus.Active);
}
var documentQuery = query
.OrderByDescending(p => p.CreatedDateTime.Epoch)
.AsDocumentQuery();
var documentResponse = await documentQuery.ExecuteNextAsync<PhotoDocument>();
var photoContracts = await CreatePhotoContractsAndLoadUserData(documentResponse.ToList());
var result = new PagedResponse<PhotoContract>
{
Items = photoContracts,
ContinuationToken = documentResponse.ResponseContinuation
};
return result;
}
/// <summary>
/// Checks if the defined document database and collection exists
/// and initializes them if they don't.
/// </summary>
public async Task InitializeDatabaseIfNotExisting(string serverPath)
{
var database = _documentClient.CreateDatabaseQuery()
.Where(db => db.Id == _documentDataBaseId)
.AsEnumerable()
.FirstOrDefault();
if (database == null)
{
database = await CreateDocumentDbDatabase();
}
var documentCollection = _documentClient.CreateDocumentCollectionQuery(database.SelfLink)
.Where(c => c.Id == _documentCollectionId)
.AsEnumerable()
.FirstOrDefault();
if (documentCollection == null)
{
await CreateDocumentDbCollection(database);
}
await InitializeStoredProceduresIfNotExisting(serverPath);
}
private async Task InitializeStoredProceduresIfNotExisting(string serverPath)
{
try
{
var sprocs = _documentClient.CreateStoredProcedureQuery(StoredProceduresUri).AsEnumerable();
if (!sprocs.Any(s => s.Id == TransferGoldStoredProcedureId))
{
await CreateTransferGoldStoredProcedure(serverPath);
}
if (!sprocs.Any(s => s.Id == GetRecentPhotosForCategoriesStoredProcedureId))
{
await CreateGetRecentPhotosForCategoriesStoredProcedure(serverPath);
}
}
catch (IOException ex)
{
throw new DataLayerException(DataLayerError.NotFound, "The file given for a stored procedure could not be located.", ex);
}
catch (Exception ex)
{
throw new DataLayerException(DataLayerError.Unknown, "An unknown error occured while inserting a stored procedure.", ex);
}
}
/// <summary>
/// Inserts the annotation object and performs the required gold transactions.
/// </summary>
/// <param name="annotationContract">Annotation to be inserted.</param>
/// <returns>AnnotationContract.</returns>
public async Task<AnnotationContract> InsertAnnotation(AnnotationContract annotationContract)
{
var annotationDocument = AnnotationDocument.CreateFromContract(annotationContract);
annotationDocument.Id = Guid.NewGuid().ToString();
annotationContract.Id = annotationDocument.Id;
annotationDocument.CreatedDateTime = new DateDocument
{
Date = DateTime.UtcNow
};
var photoDocument = PhotoDocument.CreateFromContract(await GetPhoto(annotationContract.PhotoId));
if (photoDocument.Annotations.Any(a => a.Id == annotationContract.Id))
{
throw new DataLayerException(DataLayerError.DuplicateKeyInsert, $"Annotation with Id={annotationContract.Id} already exists");
}
photoDocument.Annotations.Add(annotationDocument);
photoDocument.GoldCount += annotationContract.GoldCount;
// Handle gold balance changes and create transaction record
await
ExecuteGoldTransactionSproc(photoDocument.UserId, annotationContract.From.UserId,
annotationContract.GoldCount,
GoldTransactionType.PhotoGoldTransaction, annotationContract.PhotoId);
await ReplacePhotoDocument(photoDocument);
return annotationContract;
}
/// <summary>
/// Inserts receipt and adds gold to user.
/// </summary>
/// <param name="validatedIapReciept">Validated receipt values.</param>
/// <returns>User object containing new gold balance.</returns>
public async Task<UserContract> InsertIapPurchase(IapPurchaseContract validatedIapReciept)
{
var document = _documentClient.CreateDocumentQuery<IapPurchaseDocument>(DocumentCollectionUri)
.Where(d => d.DocumentType == IapPurchaseDocument.DocumentTypeIdentifier)
.Where(d => d.DocumentVersion == _currentDocumentVersion)
.Where(i => i.Id == validatedIapReciept.IapPurchaseId)
.AsEnumerable().FirstOrDefault();
if (document != null)
{
throw new DataLayerException(DataLayerError.DuplicateKeyInsert,
$"Iap Purchase with Id={validatedIapReciept.IapPurchaseId} already exists");
}
if (validatedIapReciept.GoldIncrement > 0)
{
// Handle gold balance changes and create transaction record
await
ExecuteGoldTransactionSproc(validatedIapReciept.UserId, SystemUserId,
validatedIapReciept.GoldIncrement,
GoldTransactionType.IapGoldTransaction);
}
var iapPurchaseDocument = IapPurchaseDocument.CreateFromContract(validatedIapReciept);
await _documentClient.CreateDocumentAsync(DocumentCollectionUri, iapPurchaseDocument);