Beispiel #1
0
        public async Task LoadAsync(string id)
        {
            try
            {
                _isLoaded.Value = false;

                var itemDocument = await _firestore.GetCollection(Models.Item.CollectionPath)
                                   .GetDocument(id)
                                   .GetDocumentAsync()
                                   .ConfigureAwait(false);

                var item = itemDocument.ToObject <Item>();

                if (item != null)
                {
                    _item.Value = item;

                    var likeTask = _firestore.GetDocument($"{User.CollectionPath}/{_accountService.UserId}/{Like.CollectionPath}/{id}")
                                   .GetDocumentAsync();

                    if (!string.IsNullOrEmpty(item.OwnerId))
                    {
                        var ownerDocument = await _firestore.GetCollection(User.CollectionPath)
                                            .GetDocument(item.OwnerId)
                                            .GetDocumentAsync()
                                            .ConfigureAwait(false);

                        _owner.Value = ownerDocument.ToObject <User>();
                    }

                    var likeDocument = await likeTask.ConfigureAwait(false);

                    _isLiked.Value = likeDocument.Exists;

                    _isLoaded.Value = true;

                    CrossFirebaseAnalytics.Current.LogEvent(EventName.ViewItem, new Parameter(ParameterName.ItemId, id));
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                _loadErrorNotifier.OnNext(e.Message);
            }
        }
Beispiel #2
0
        public async Task Contribute()
        {
            if (!CanContribute.Value)
            {
                return;
            }

            try
            {
                using (_contributingNotifier.ProcessStart())
                {
                    var id = Guid.NewGuid().ToString();

                    var uri = await _storageService.UploadImage(ItemImage.Value, $"items/{id}/image.jpg").ConfigureAwait(false);

                    var item = new Item
                    {
                        Title     = ItemTitle.Value,
                        Image     = uri.AbsoluteUri,
                        Comment   = ItemComment.Value,
                        OwnerId   = _accountService.UserId.Value,
                        Timestamp = DateTime.Now.Ticks
                    };

                    await _firestore.GetCollection(Item.CollectionPath)
                    .GetDocument(id)
                    .SetDataAsync(item)
                    .ConfigureAwait(false);

                    await _accountService.IncrementContributionCountAsync(1);
                }
                _contributeCompletedNotifier.OnNext(Unit.Default);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                _contributeErrorNotifier.OnNext(e.Message);
            }
        }
        public AccountService()
        {
            _firebaseAuth = CrossFirebaseAuth.Current.Instance;
            _firestore    = CrossCloudFirestore.Current.Instance;

            IsInitialized     = _isInitialized.ToReadOnlyReactivePropertySlim();
            IsLoggedIn        = _isLoggedIn.ToReadOnlyReactivePropertySlim();
            UserId            = _userId.ToReadOnlyReactivePropertySlim();
            UserName          = _userName.ToReadOnlyReactivePropertySlim();
            UserImage         = _userImage.ToReadOnlyReactivePropertySlim();
            ContributionCount = _contributionCount.ToReadOnlyReactivePropertySlim();

            UserId.Select(userId => string.IsNullOrEmpty(userId) ?
                          Observable.Return <User>(null) :
                          _firestore.GetCollection(User.CollectionPath)
                          .GetDocument(userId)
                          .AsObservable()
                          .Select(d => d.ToObject <User>()))
            .Switch()
            .Subscribe(user =>
            {
                if (user != null)
                {
                    _userName.Value          = user.Name;
                    _userImage.Value         = user.Image;
                    _contributionCount.Value = user.ContributionCount;
                }
                else
                {
                    _userName.Value          = null;
                    _userImage.Value         = null;
                    _contributionCount.Value = 0;
                }
            })
            .AddTo(_disposables);
        }
        public async Task LoadAsync()
        {
            try
            {
                var documents = await _firestore.GetCollection(Item.CollectionPath)
                                .WhereEqualsTo(nameof(Item.OwnerId), _userId)
                                .OrderBy(nameof(Item.Timestamp), true)
                                .LimitTo(Count)
                                .StartAfter(_lastTimestamp)
                                .GetDocumentsAsync()
                                .ConfigureAwait(false);

                if ((!documents.IsEmpty || _disposables == null) && !_isClosed)
                {
                    lock (_lock)
                    {
                        if (!_isClosed)
                        {
                            if (!documents.IsEmpty)
                            {
                                var lastItem = documents.Documents.Last().ToObject <Item>();
                                _lastTimestamp = lastItem.Timestamp;
                            }
                            else
                            {
                                _lastTimestamp = DateTime.Now.Ticks;
                            }

                            _disposables?.Dispose();
                            _disposables = new CompositeDisposable();

                            var query = _firestore.GetCollection(Item.CollectionPath)
                                        .WhereEqualsTo(nameof(Item.OwnerId), _userId)
                                        .OrderBy(nameof(Item.Timestamp), true)
                                        .EndAt(_lastTimestamp);

                            query.ObserveAdded()
                            .Where(d => _items.FirstOrDefault(i => i.Id == d.Document.Id) == null)
                            .Subscribe(d => _items.Insert(d.NewIndex, d.Document.ToObject <Item>()))
                            .AddTo(_disposables);

                            query.ObserveModified()
                            .Select(d => d.Document.ToObject <Item>())
                            .Subscribe(item =>
                            {
                                var targetItem = _items.FirstOrDefault(i => i.Id == item.Id);
                                if (targetItem != null)
                                {
                                    item.CopyTo(targetItem);
                                }
                            })
                            .AddTo(_disposables);

                            query.ObserveRemoved()
                            .Select(d => _items.FirstOrDefault(i => i.Id == d.Document.Id))
                            .Where(item => item != null)
                            .Subscribe(item => _items.Remove(item))
                            .AddTo(_disposables);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }
        }
Beispiel #5
0
        public async Task <bool> CreateUserAsync(User user)
        {
            bool result = false;

            if (user != null)
            {
                result = true;

                try
                {
                    await _firestore.GetCollection(nameof(User)).GetDocument(user.Email).SetDataAsync(user).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    result = false;
                    App.LogException(e);
                }
            }

            return(result);
        }
        public async Task Initialize()
        {
            if (IsInitialized.Value)
            {
                return;
            }

            Plugin.FirebaseAuth.IListenerRegistration registration = null;
            try
            {
                var tcs = new TaskCompletionSource <string>();

                registration = _firebaseAuth.AddAuthStateChangedListener(auth =>
                {
                    tcs.TrySetResult(auth?.CurrentUser?.Uid);
                });

                var userId = await tcs.Task.ConfigureAwait(false);

                if (userId != null)
                {
                    var reference = _firestore.GetCollection(User.CollectionPath)
                                    .GetDocument(userId);

                    var document = await reference.GetDocumentAsync().ConfigureAwait(false);

                    if (document.Exists)
                    {
                        var user = document.ToObject <User>();

                        _userId.Value            = user.Id;
                        _userName.Value          = user.Name;
                        _userImage.Value         = user.Image;
                        _contributionCount.Value = user.ContributionCount;
                        _isLoggedIn.Value        = true;
                    }
                    else
                    {
                        _userId.Value            = null;
                        _userName.Value          = null;
                        _userImage.Value         = null;
                        _contributionCount.Value = 0;
                        _isLoggedIn.Value        = false;
                    }
                }
                else
                {
                    _userId.Value            = null;
                    _userName.Value          = null;
                    _userImage.Value         = null;
                    _contributionCount.Value = 0;
                    _isLoggedIn.Value        = false;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
            }
            finally
            {
                registration?.Remove();
                _isInitialized.Value = true;
            }
        }