Esempio n. 1
0
        private EntityUpdate FindOrCreateEntityUpdate(EntityType entityType, byte entityId)
        {
            // Try to find an already existing instance with the same type and id
            EntityUpdate entityUpdate = null;

            foreach (var existingEntityUpdate in CurrentUpdatePacket.EntityUpdates.DataInstances)
            {
                if (existingEntityUpdate.EntityType.Equals(entityType) && existingEntityUpdate.Id == entityId)
                {
                    entityUpdate = existingEntityUpdate;
                    break;
                }
            }

            // If no existing instance was found, create one and add it to the list
            if (entityUpdate == null)
            {
                entityUpdate = new EntityUpdate {
                    EntityType = entityType,
                    Id         = entityId
                };

                CurrentUpdatePacket.EntityUpdates.DataInstances.Add(entityUpdate);
            }

            return(entityUpdate);
        }
Esempio n. 2
0
 internal MinHeapItem(uint _pqueue, UInt64 _entryorder, EntityUpdate _value)
 {
     entrytime  = Util.EnvironmentTickCount();
     entryorder = _entryorder;
     value      = _value;
     pqueue     = _pqueue;
 }
Esempio n. 3
0
        private void onTimeEntryUpdated(EntityUpdate <IThreadSafeTimeEntry> update)
        {
            var timeEntry = update.Entity;

            if (timeEntry == null)
            {
                return;
            }

            if (timeEntry.IsDeleted || timeEntry.IsRunning())
            {
                onTimeEntryRemoved(timeEntry.Id);
            }
            else
            {
                var timeEntryViewModel = new TimeEntryViewModel(timeEntry, durationFormat);
                if (timeEntry.Id == timeEntryToDelete?.Id)
                {
                    // Ignore this update because the entity is hidden and might be deleted unless the user
                    // undoes the action. In that case bring the time entry but with the updated data.
                    timeEntryToDelete = timeEntryViewModel;
                }
                else
                {
                    TimeEntries.UpdateItem(update.Id, timeEntryViewModel);
                }
            }
        }
Esempio n. 4
0
        private EntityOperationResult UpdateInternal(EntityUpdate update)
        {
            if (!RunInspection(update))
            {
                return(EntityOperationResult.FailResult(new EntityOperationError("Insufficient rights to perform this operation.", EntityOperationError.ACCESS_VIOLATION)));
            }

            EntityOperationContext ctx = new EntityOperationContext();

            this.AppyLogicBefore(update, ctx);

            var entity = update.ToEntity();
            EntityOperationResult result = null;
            bool created = false;

            try
            {
                if (update.Id.HasValue)
                {
                    if (update.PropertyUpdates.Count > 0)
                    {
                        _repository.Update(entity);
                    }
                }
                else
                {
                    update.Id = _repository.Create(entity);
                    created   = true;
                }

                //Order by operation - process detach first
                foreach (var relUpdate in update.RelationUpdates.OrderByDescending(ru => ru.Operation))
                {
                    if (relUpdate.Operation == RelationOperation.Attach)
                    {
                        _repository.Attach(entity, relUpdate.ToRelation());
                    }
                    else if (relUpdate.Operation == RelationOperation.Detach)
                    {
                        _repository.Detach(entity, relUpdate.ToRelation());
                    }
                    else if (relUpdate.PropertyUpdates.Count > 0)
                    {
                        _repository.UpdateRelation(entity, relUpdate.ToRelation());
                    }
                }

                result = EntityOperationResult.SuccessResult();
                if (created)
                {
                    result.Data.Add("Created", update.Id.Value);
                }
            }
            catch (UniqueRuleViolationException rex)
            {
                result = EntityOperationResult.FailResult(new EntityOperationError(rex.Message, EntityOperationError.UNIQUE_RULE_VIOLATION));
            }
            this.AppyLogicAfter(update, ctx, result);
            return(result);
        }
Esempio n. 5
0
        // Make this an AsyncEnumerable so we can still get partial data saved if the servers break in the middle of a pull
        private async IAsyncEnumerable <EntityUpdate> FetchElectionResults(int season)
        {
            using var hasher = new SibrHasher();

            var recap = await _client.GetJsonAsync($"https://www.blaseball.com/database/offseasonRecap?season={season}");

            yield return(EntityUpdate.From(UpdateType.OffseasonRecap, _sourceId, recap.Timestamp, recap.Data, hasher));

            var decreeIds     = recap.Data.Value <JArray>("decreeResults").Values <string>().ToList();
            var decreeResults = await GetUpdatesByIds(UpdateType.DecreeResult, "https://www.blaseball.com/database/decreeResults", decreeIds, hasher);

            _logger.Information("Fetched {DecreeCount} decree results", decreeIds.Count);
            foreach (var result in decreeResults)
            {
                yield return(result);
            }

            var bonusIds     = recap.Data.Value <JArray>("bonusResults").Values <string>().ToList();
            var bonusResults = await GetUpdatesByIds(UpdateType.BonusResult, "https://www.blaseball.com/database/bonusResults", bonusIds, hasher);

            _logger.Information("Fetched {BonusCount} bonus results", bonusIds.Count);
            foreach (var result in bonusResults)
            {
                yield return(result);
            }

            var eventIds     = recap.Data.Value <JArray>("eventResults").Values <string>().ToList();
            var eventResults = await GetUpdatesByIds(UpdateType.EventResult, "https://www.blaseball.com/database/eventResults", eventIds, hasher);

            _logger.Information("Fetched {EventCount} event results", eventIds.Count);
            foreach (var result in eventResults)
            {
                yield return(result);
            }
        }
Esempio n. 6
0
        private async Task <IEnumerable <EntityUpdate> > FetchAllTeams()
        {
            var timestamp = _clock.GetCurrentInstant();
            var json      = await _client.GetStringAsync("https://www.blaseball.com/database/allTeams");

            return(EntityUpdate.FromArray(UpdateType.Team, _sourceId, timestamp, JArray.Parse(json)));
        }
Esempio n. 7
0
        public bool TryOrderedDequeue(out EntityUpdate value, out Int32 timeinqueue)
        {
            MinHeap <MinHeapItem> curheap;

            for (int iq = 0; iq < NumberOfQueues; ++iq)
            {
                curheap = m_heaps[iq];
                if (curheap.Count > 0)
                {
                    MinHeapItem item = curheap.RemoveMin();
                    m_lookupTable.Remove(item.Value.Entity.LocalId);
                    timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
                    value       = item.Value;
                    return(true);
                }
            }

            timeinqueue = 0;
            value       = default(EntityUpdate);
            if (m_lookupTable.Count == 0 && m_added > 8 * m_capacity)
            {
                m_lookupTable = new Dictionary <uint, LookupItem>(m_capacity);
                m_added       = 0;
            }
            return(false);
        }
Esempio n. 8
0
 internal MinHeapItem(uint _pqueue, MinHeapItem other)
 {
     entrytime  = other.entrytime;
     entryorder = other.entryorder;
     value      = other.value;
     pqueue     = _pqueue;
 }
Esempio n. 9
0
 internal MinHeapItem(uint pqueue, MinHeapItem other)
 {
     this.entrytime  = other.entrytime;
     this.entryorder = other.entryorder;
     this.value      = other.value;
     this.pqueue     = pqueue;
 }
Esempio n. 10
0
        private void SendQueued(HashSet <ISceneEntity> entsqueue)
        {
            //NO LOCKING REQUIRED HERE, THE PRIORITYQUEUE IS LOCAL
            //Enqueue them all
            List <KeyValuePair <double, ISceneEntity> > sortableList = new List <KeyValuePair <double, ISceneEntity> >();

            foreach (ISceneEntity ent in entsqueue)
            {
                sortableList.Add(new KeyValuePair <double, ISceneEntity>(
                                     m_prioritizer.GetUpdatePriority(m_presence, ent), ent));
            }
            sortableList.Sort(sortPriority);
            lock (m_objectUpdatesToSendLock)
            {
                foreach (KeyValuePair <double, ISceneEntity> t in sortableList)
                {
                    //Always send the root child first!
                    EntityUpdate update = new EntityUpdate(t.Value.RootChild, PrimUpdateFlags.ForcedFullUpdate);
                    QueueEntityUpdate(update);
                    foreach (ISceneChildEntity child in t.Value.ChildrenEntities().Where(child => !child.IsRoot))
                    {
                        update = new EntityUpdate(child, PrimUpdateFlags.ForcedFullUpdate);
                        QueueEntityUpdate(update);
                    }
                }
            }

            m_lastUpdatePos = (m_presence.IsChildAgent)
                                  ? m_presence.AbsolutePosition
                                  : m_presence.CameraPosition;
        }
Esempio n. 11
0
 public static byte[] CreateDatagram(this EntityUpdate e)
 {
     byte[] data     = e.Data;
     byte[] datagram = new byte[data.Length + 1];
     data.CopyTo(datagram, 1);
     return(datagram);
 }
Esempio n. 12
0
        private void OnEntityUpdate(EntityUpdate entityUpdate)
        {
            // We only propagate entity updates to the entity manager if we have determined the scene host
            if (!_sceneHostDetermined)
            {
                return;
            }

            if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.Position))
            {
                _entityManager.UpdateEntityPosition((EntityType)entityUpdate.EntityType, entityUpdate.Id,
                                                    entityUpdate.Position);
            }

            if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.State))
            {
                List <byte> variables;

                if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.Variables))
                {
                    variables = entityUpdate.Variables;
                }
                else
                {
                    variables = new List <byte>();
                }

                _entityManager.UpdateEntityState(
                    (EntityType)entityUpdate.EntityType,
                    entityUpdate.Id,
                    entityUpdate.State,
                    variables
                    );
            }
        }
Esempio n. 13
0
        protected override async Task ProcessFile(string filename, IAsyncEnumerable <JToken> entries,
                                                  ImportOptions options)
        {
            var timestamp = ExtractTimestampFromFilename(filename, @"idols-(\d+)\.json\.gz");

            if (timestamp == null)
            {
                return;
            }

            await using var conn = await _db.Obtain();

            await using var tx = await conn.BeginTransactionAsync();

            var updates = await entries
                          .Select(entry => EntityUpdate.From(UpdateType.Idols, _sourceId, timestamp.Value, entry))
                          .ToListAsync();

            var res = await _store.SaveUpdates(conn, updates);

            if (res > 0)
            {
                _logger.Information("- Imported idols update at {Timestamp}", timestamp);
            }

            await tx.CommitAsync();
        }
Esempio n. 14
0
        public void UpdateEntityVariables(EntityType entityType, byte entityId, List <byte> fsmVariables)
        {
            lock (_currentUpdatePacket) {
                _currentUpdatePacket.UpdateTypes.Add(UpdateType.EntityUpdate);

                // Try to find an already existing instance with the same type and id
                EntityUpdate entityUpdate = null;
                foreach (var existingEntityUpdate in _currentUpdatePacket.EntityUpdates)
                {
                    if (existingEntityUpdate.EntityType.Equals(entityType) && existingEntityUpdate.Id == entityId)
                    {
                        entityUpdate = existingEntityUpdate;
                        break;
                    }
                }

                // If no existing instance was found, create one and add it to the list
                if (entityUpdate == null)
                {
                    entityUpdate = new EntityUpdate {
                        EntityType = entityType,
                        Id         = entityId
                    };

                    _currentUpdatePacket.EntityUpdates.Add(entityUpdate);
                }

                entityUpdate.UpdateTypes.Add(EntityUpdateType.Variables);
                entityUpdate.FsmVariables.AddRange(fsmVariables);
            }
        }
Esempio n. 15
0
        public EntityUpdate ToEntityUpdate()
        {
            var update = new EntityUpdate(this.Entity);

            update.Id = this.Id;
            if (PropertyUpdates != null)
            {
                foreach (var pu in PropertyUpdates)
                {
                    update.Set(pu.Name, pu.Value);
                }
            }
            if (RelationUpdates != null)
            {
                foreach (var ru in RelationUpdates)
                {
                    var r = new RelationUpdate(ru.Entity, ru.Role, ru.Operation, ru.Id);
                    if (ru.PropertyUpdates != null)
                    {
                        foreach (var pu in ru.PropertyUpdates)
                        {
                            r.Set(pu.Name, pu.Value);
                        }
                    }
                    update.RelationUpdates.Add(r);
                }
            }

            return(update);
        }
Esempio n. 16
0
        /// <summary>
        /// Enqueue an item into the specified priority queue
        /// </summary>
        public bool Enqueue(uint pqueue, EntityUpdate value)
        {
            LookupItem lookup;
            IHandle    lookupH;
            UInt64     entry;

            uint localid = value.Entity.LocalId;

            if (m_lookupTable.TryGetValue(localid, out lookup))
            {
                lookupH = lookup.Handle;
                entry   = lookup.Heap[lookupH].EntryOrder;
                value.Update(lookup.Heap[lookupH].Value);
                lookup.Heap.Remove(lookupH);
            }
            else
            {
                entry = m_nextRequest++;
                ++m_added;
            }

            pqueue      = Util.Clamp <uint>(pqueue, 0, NumberOfQueues - 1);
            lookup.Heap = m_heaps[pqueue];
            lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
            m_lookupTable[localid] = lookup;

            return(true);
        }
Esempio n. 17
0
        public ActionResult ForgottenPassword(string email)
        {
            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", email);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("email", string.Format("В системата няма активен потребител с имейл \"{0}\". За помощ: тел. 02 8110296.", email));
                    return(View());
                }
                else
                {
                    var recoveryCode = Guid.NewGuid().ToString();

                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("RecoveryCode", recoveryCode);
                    var result = _entityService.Update(update);
                    if (result.Success)
                    {
                        return(View("ForgottenPassword_Success", (object)email));
                    }
                    else
                    {
                        ModelState.AddModelError("email", "Възникна грешка при стартиране на процеса по възстановяване на забравена парола. За помощ: тел. 02 8110296.");
                        return(View());
                    }
                }
            }
        }
Esempio n. 18
0
 internal MinHeapItem(uint pqueue, UInt64 entryorder, EntityUpdate value)
 {
     this.entrytime  = Util.EnvironmentTickCount();
     this.entryorder = entryorder;
     this.value      = value;
     this.pqueue     = pqueue;
 }
Esempio n. 19
0
        private void SendIssueToSubscribers(EntityUpdate update)
        {
            var issueQuery = new EntityQuery2(EntityConsts.Issue, update.Id.Value);

            issueQuery.AllProperties = true;
            issueQuery.Include(EntityConsts.Magazine, Roles.Issue);
            issueQuery.Include(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content);
            var issue            = _repository.Read(issueQuery);
            var magazine         = issue.GetSingleRelation(EntityConsts.Magazine, Roles.Issue).Entity;
            var subscribersQuery = new EntityQuery2(User.ENTITY);
            var relQuery         = new RelationQuery(EntityConsts.Magazine, Roles.Subscriber, magazine.Id);

            relQuery.RelationRules.Add(new Condition("IsActive", Condition.Is, true));
            subscribersQuery.WhereRelated(relQuery);
            subscribersQuery.AllProperties = true;
            var subscribers = _repository.Search(subscribersQuery).Select(e => new User(e));

            var contents = issue.GetManyRelations(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content).Select(r => new File(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.NEW_ISSUE));

            string subject = null, body = null;
            Dictionary <string, Entity> templateContext = new Dictionary <string, Entity>(StringComparer.InvariantCultureIgnoreCase);

            templateContext.Add("Magazine", magazine);
            templateContext.Add("Issue", issue);

            _templateService.Render(template, templateContext, out subject, out body);


            _notificationService.SendNotification(true, subscribers, subject, body, contents, new Relation[] { new Relation(Notification.ROLE, issue) });
        }
Esempio n. 20
0
        private void onTimeEntryUpdated(EntityUpdate <IThreadSafeTimeEntry> update)
        {
            var timeEntry     = update.Entity;
            var shouldBeAdded = timeEntry != null && !timeEntry.IsRunning() && !timeEntry.IsDeleted;

            var oldCollectionIndex = TimeEntries.IndexOf(c => c.Any(vm => vm.Id == update.Id));
            var collectionIndex    = TimeEntries.IndexOf(vm => vm.Date == timeEntry.Start.LocalDateTime.Date);
            var wasMovedIntoDifferentCollection = oldCollectionIndex >= 0 && oldCollectionIndex != collectionIndex;

            var shouldBeRemoved = shouldBeAdded == false || wasMovedIntoDifferentCollection;

            if (shouldBeRemoved)
            {
                safeRemoveTimeEntry(update.Id);
            }

            if (shouldBeAdded)
            {
                var timeEntryIndex = collectionIndex < 0 ? -1 : TimeEntries[collectionIndex].IndexOf(vm => vm.Id == update.Id);
                var timeEntryExistsInTheCollection = timeEntryIndex >= 0;
                if (timeEntryExistsInTheCollection)
                {
                    var timeEntryViewModel = new TimeEntryViewModel(timeEntry, durationFormat);
                    TimeEntries.ReplaceInChildCollection(collectionIndex, timeEntryIndex, timeEntryViewModel);
                    return;
                }

                safeInsertTimeEntry(timeEntry);
            }
        }
Esempio n. 21
0
        private async Task HandleStreamData(string obj)
        {
            var timestamp = _clock.GetCurrentInstant();
            var data      = JObject.Parse(obj);

            await using var conn = await _db.Obtain();

            await using (var tx = await conn.BeginTransactionAsync())
            {
                await _updateStore.SaveUpdate(conn, EntityUpdate.From(UpdateType.Stream, _sourceId, timestamp, data));

                await tx.CommitAsync();
            }

            await using (var tx = await conn.BeginTransactionAsync())
            {
                using var hasher = new SibrHasher();
                var extracted = TgbUtils.ExtractUpdatesFromStreamRoot(_sourceId, timestamp, data, hasher);
                var gameRes   = await _gameStore.SaveGameUpdates(conn, extracted.GameUpdates);

                var miscRes = await _updateStore.SaveUpdates(conn, extracted.EntityUpdates);

                var maxPlayCount = extracted.GameUpdates.Count > 0 ? extracted.GameUpdates.Max(gu => gu.PlayCount) : -1;

                _logger.Information(
                    "Received stream update, saved {GameUpdates} game updates, {MiscUpdates} updates, max PC {MaxPlayCount}",
                    gameRes, miscRes, maxPlayCount);

                await tx.CommitAsync();
            }
        }
Esempio n. 22
0
        private async Task <EntityUpdate> FetchElectionDetails(Guid electionId)
        {
            var(electionTimestamp, electionData) =
                await _client.GetJsonAsync($"https://api.blaseball.com/api/elections/{electionId}");

            return(EntityUpdate.From(UpdateType.GammaElectionDetails, _sourceId, electionTimestamp,
                                     electionData, idOverride: electionId));
        }
Esempio n. 23
0
 private List <EntityUpdate> ExtractItems(List <EntityUpdate> playerUpdates)
 {
     return(playerUpdates.SelectMany(update =>
     {
         return update.Data.SelectTokens("items[*]")
         .Select(data => EntityUpdate.From(UpdateType.Item, update.SourceId, update.Timestamp, data));
     }).ToList());
 }
Esempio n. 24
0
        private async Task <EntityUpdate> FetchElectionResults(Guid prizeId)
        {
            var(timestamp, data) =
                await _client.GetJsonAsync($"https://api.blaseball.com/api/elections/{prizeId}/results");

            return(EntityUpdate.From(UpdateType.GammaElectionResults, _sourceId, timestamp,
                                     data, idOverride: prizeId));
        }
Esempio n. 25
0
        private async Task <IEnumerable <EntityUpdate> > FetchPlayers(IEnumerable <Guid> playerIds)
        {
            var queryIds = string.Join(',', playerIds);

            var timestamp = _clock.GetCurrentInstant();
            var json      = await _client.GetStringAsync("https://www.blaseball.com/database/players?ids=" + queryIds);

            return(EntityUpdate.FromArray(UpdateType.Player, _sourceId, timestamp, JArray.Parse(json)));
        }
Esempio n. 26
0
        public ActionResult FinishResigration(RegisterViewModel model)
        {
            User user = new User()
            {
                Email = model.Email,
                Password = model.Password,
                FirstName = model.FirstName,
                MiddleName = model.MiddleName,
                LastName = model.LastName,
                FacultyNumber = model.FacultyNumber,
                CardNumber = model.CardNumber,
                PhoneNumber = model.PhoneNumber,
                UserType = UserTypes.Customer
            };
            var update = new EntityUpdate(user);
            update.Attach(UserGroup.ENTITY, UserGroup.DEFAULT_ROLE, model.UserGroup);
            EntityOperationResult result = null;
            using (_securityService.BeginSystemContext())
            {
                result = _entityService.Update(update);
            }

            if (result.Success)
                return View("RegisterComplete");
            else
            {
                IEnumerable<UserGroup> availableGroups = null;
                using (_securityService.BeginSystemContext())
                {
                    var query = new EntityQuery2(UserGroup.ENTITY);
                    query.AllProperties = true;
                    query.WhereIs("UserType", UserTypes.Customer);
                    availableGroups = _entityService.Query(query).Select(e => new UserGroup(e));
                }

                if (result.Errors == null || result.Errors.Count == 0)
                    ModelState.AddModelError("", "Unexpected error occured. Please, try again. If there is still a problem, contact the administrator.");
                else
                {
                    foreach (var err in result.Errors)
                    {
                        ModelState.AddModelError("", err.Message);
                    }
                }

                var selectedGroup = availableGroups.Single(g => g.Id == model.UserGroup);
                if (selectedGroup.Name.Equals("Студенти", StringComparison.InvariantCultureIgnoreCase)
                    || selectedGroup.Name.Equals("Преподаватели", StringComparison.InvariantCultureIgnoreCase))
                {
                    return View("RegisterStudent", new RegisterStudentViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
                }
                else if (selectedGroup.Name.Equals("Външни", StringComparison.InvariantCultureIgnoreCase))
                    return View("RegisterExternal", new RegisterExternalViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
                else
                    return View("RegisterOther", new RegisterViewModel() { UserGroup = model.UserGroup, UserGroupName = selectedGroup.Name });
            }
        }
Esempio n. 27
0
        private async Task <EntityUpdate> QueryRenovationProgress(Guid stadiumId)
        {
            var data = await _client.GetStringAsync($"https://www.blaseball.com/database/renovationProgress?id={stadiumId}");

            var json      = JToken.Parse(data);
            var timestamp = _clock.GetCurrentInstant();

            return(EntityUpdate.From(UpdateType.RenovationProgress, _sourceId, timestamp, json, idOverride: stadiumId));
        }
Esempio n. 28
0
        public static void TCP(string command, string parameter, Player player)
        {
            switch (command)
            {
            case "spawn":
                break;

            case "reload_world":
                break;

            case "xp":
                try {
                    int amount = Convert.ToInt32(parameter);

                    var xpDummy = new EntityUpdate()
                    {
                        guid      = 1000,
                        hostility = (byte)Hostility.enemy
                    };
                    xpDummy.Write(player.writer);

                    var kill = new ServerUpdate.Kill()
                    {
                        killer = player.entityData.guid,
                        victim = 1000,
                        xp     = amount
                    };
                    var serverUpdate = new ServerUpdate();
                    serverUpdate.kills.Add(kill);
                    serverUpdate.Write(player.writer, true);
                    break;
                } catch (Exception) {
                    //invalid syntax
                }
                break;

            case "time":
                try {
                    int index  = parameter.IndexOf(":");
                    int hour   = Convert.ToInt32(parameter.Substring(0, index));
                    int minute = Convert.ToInt32(parameter.Substring(index + 1));

                    var time = new Time()
                    {
                        time = (hour * 60 + minute) * 60000
                    };
                    time.Write(player.writer, true);
                } catch (Exception) {
                    //invalid syntax
                }
                break;

            default:
                break;
            }
        }
Esempio n. 29
0
        private async Task <IEnumerable <EntityUpdate> > GetUpdatesByIds(UpdateType type, string baseUrl, IEnumerable <string> ids, SibrHasher hasher)
        {
            var(timestamp, data) = await _client.GetJsonAsync($"{baseUrl}?ids={string.Join(',', ids)}");

            return(data.Values <JObject>().Select(obj =>
            {
                var id = TgbUtils.GenerateGuidFromString(obj.Value <string>("id"));
                return EntityUpdate.From(type, _sourceId, timestamp, obj, hasher, id);
            }));
        }
Esempio n. 30
0
        /// <summary>
        /// Callback method for when an entity update is received from a player.
        /// </summary>
        /// <param name="id">The ID of the player.</param>
        /// <param name="entityUpdate">The EntityUpdate packet data.</param>
        private void OnEntityUpdate(ushort id, EntityUpdate entityUpdate)
        {
            if (!_playerData.TryGetValue(id, out var playerData))
            {
                Logger.Get().Warn(this, $"Received EntityUpdate data, but player with ID {id} is not in mapping");
                return;
            }

            if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.Position))
            {
                SendDataInSameScene(
                    id,
                    playerData.CurrentScene,
                    otherId => {
                    _netServer.GetUpdateManagerForClient(otherId)?.UpdateEntityPosition(
                        entityUpdate.EntityType,
                        entityUpdate.Id,
                        entityUpdate.Position
                        );
                }
                    );
            }

            if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.State))
            {
                SendDataInSameScene(
                    id,
                    playerData.CurrentScene,
                    otherId => {
                    _netServer.GetUpdateManagerForClient(otherId)?.UpdateEntityState(
                        entityUpdate.EntityType,
                        entityUpdate.Id,
                        entityUpdate.State
                        );
                }
                    );
            }

            if (entityUpdate.UpdateTypes.Contains(EntityUpdateType.Variables))
            {
                SendDataInSameScene(
                    id,
                    playerData.CurrentScene,
                    otherId => {
                    _netServer.GetUpdateManagerForClient(otherId)?.UpdateEntityVariables(
                        entityUpdate.EntityType,
                        entityUpdate.Id,
                        entityUpdate.Variables
                        );
                }
                    );
            }
        }
Esempio n. 31
0
        private async Task TickerHandler(JToken obj)
        {
            var(timestamp, data) = await _client.GetJsonAsync("https://api.blaseball.com/database/globalEvents");

            var update = EntityUpdate.From(UpdateType.GlobalEvents, _sourceId, timestamp, data);

            await using var conn = await _db.Obtain();

            await _updateStore.SaveUpdate(conn, update);

            _logger.Information("Pulled GlobalEvents based on Pusher event");
        }
Esempio n. 32
0
        public ActionResult Upload()
        {
            var response = new FileUploadResponse();
            foreach (string filename in Request.Files)
            {
                var file = Request.Files[filename];
                var stat = _fileService.CanUpload(file.FileName, file.ContentLength);
                if (stat == CanUploadStatus.FileTypeNotAllowed)
                    throw new Exception("Files of this type are not allowed.");
                else if(stat == CanUploadStatus.DiskUsageLimitExceeded)
                    throw new Exception("Disk usage limit exceeded.");

                Guid id = _fileService.StoreFileContent(file.InputStream);
                var f = new File()
                {
                    FileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName),
                    ContentType = file.ContentType,
                    ContentPath = id.ToString(),
                    Extension = System.IO.Path.GetExtension(file.FileName),
                    Size = file.ContentLength
                };

                EntityUpdate create = new EntityUpdate(f);
                var result = _entityService.Update(create);
                if (result.Success)
                {
                    response.files.Add(new FileUploadResponse.File()
                    {
                        id = create.Id.Value,
                        name = file.FileName,
                        size = file.ContentLength,
                        url = Url.Action("Download") + "?id=" + create.Id.Value
                    });
                }
            }

            //System.Threading.Thread.Sleep(500);

            return Json(response);
        }
Esempio n. 33
0
        public ActionResult RecoverPassword(PasswordRecoveryModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", model.Email);
                q.WhereIs("RecoveryCode", model.RecoveryCode);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("", "Грешен имейл или код за възстановяване. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                    return View(model);
                }
                else
                {
                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("Password", model.Password);
                    var result = _entityService.Update(update);
                    if(result.Success)
                    {
                        return View("RecoverPassword_Success");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Възникна грешка при смяна на паролата. Започнете процеса по възстановяване (през забравена парола) отново или позвънете на тел. 02 8110296.");
                        return View(model);
                    }
                }
            }
        }
Esempio n. 34
0
        public ActionResult ForgottenPassword(string email)
        {
            using (_securityService.BeginSystemContext())
            {
                var q = new EntityQuery2("User");
                q.WhereIs("Email", email);
                q.WhereIs("IsActive", true);
                Entity user = _entityService.Query(q).SingleOrDefault();
                if (user == null)
                {
                    ModelState.AddModelError("email", string.Format("В системата няма активен потребител с имейл \"{0}\". За помощ: тел. 02 8110296.", email));
                    return View();
                }
                else
                {
                    var recoveryCode = Guid.NewGuid().ToString();

                    var update = new EntityUpdate(user.Name, user.Id);
                    update.Set("RecoveryCode", recoveryCode);
                    var result = _entityService.Update(update);
                    if(result.Success)
                        return View("ForgottenPassword_Success", (object)email);
                    else
                    {
                        ModelState.AddModelError("email", "Възникна грешка при стартиране на процеса по възстановяване на забравена парола. За помощ: тел. 02 8110296.");
                        return View();
                    }
                }

            }
        }
Esempio n. 35
0
        private void SendMagazineNotActiveToSubscribers(EntityUpdate update)
        {
            var magazineQuery = new EntityQuery2(EntityConsts.Magazine, update.Id.Value);
            magazineQuery.AllProperties = true;
            magazineQuery.Include(User.ENTITY, Roles.Subscriber);

            var magazine = _repository.Read(magazineQuery);

            var subscribers = magazine.GetManyRelations(User.ENTITY, Roles.Subscriber).Select(r => new User(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.DEACTIVATED_MAGAZINE));

            string subject = null, body = null;
            Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
            templateContext.Add("Magazine", magazine);
            _templateService.Render(template, templateContext, out subject, out body);
            _notificationService.SendNotification(true, subscribers, subject, body, null, new Relation[] { new Relation(Notification.ROLE, magazine) });
        }
Esempio n. 36
0
        private void SendIssueToSubscribers(EntityUpdate update)
        {
            var issueQuery = new EntityQuery2(EntityConsts.Issue, update.Id.Value);
            issueQuery.AllProperties = true;
            issueQuery.Include(EntityConsts.Magazine, Roles.Issue);
            issueQuery.Include(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content);
            var issue = _repository.Read(issueQuery);
            var magazine = issue.GetSingleRelation(EntityConsts.Magazine, Roles.Issue).Entity;
            var subscribersQuery = new EntityQuery2(User.ENTITY);
            var relQuery = new RelationQuery(EntityConsts.Magazine, Roles.Subscriber, magazine.Id);
            relQuery.RelationRules.Add(new Condition("IsActive", Condition.Is, true));
            subscribersQuery.WhereRelated(relQuery);
            subscribersQuery.AllProperties = true;
            var subscribers = _repository.Search(subscribersQuery).Select(e => new User(e));

            var contents = issue.GetManyRelations(NbuLibrary.Core.Domain.File.ENTITY, Roles.Content).Select(r => new File(r.Entity));

            var template = _templateService.Get(new Guid(NotificationTemplates.NEW_ISSUE));

            string subject = null, body = null;
            Dictionary<string, Entity> templateContext = new Dictionary<string, Entity>(StringComparer.InvariantCultureIgnoreCase);
            templateContext.Add("Magazine", magazine);
            templateContext.Add("Issue", issue);

            _templateService.Render(template, templateContext, out subject, out body);

            _notificationService.SendNotification(true, subscribers, subject, body, contents, new Relation[] { new Relation(Notification.ROLE, issue) });
        }
Esempio n. 37
0
        //[TestMethod]
        public void Test_EntityRepo_Perf()
        {
            var r = new Random();
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            using (var ctx = dbService.GetDatabaseContext(true))
            {
                for (int i = 0; i < 1000; i++)
                {
                    EntityUpdate update = new EntityUpdate("author");
                    update.Set("firstname", "Robert" + i);
                    update.Set("lastname", "Jordan");
                    update.Set("isalive", false);
                    update.Set("Born", new DateTime(1948, 10, 17));
                    update.Set("Rating", 5.5m + r.Next(4));
                    var id = repository.Create(update.ToEntity());
                    Assert.IsTrue(id > 0);

                    EntityQuery2 q = new EntityQuery2("author", id);
                    q.AddProperties("FirstName", "lastname", "isalive", "born", "rating");
                    var e = repository.Read(q);
                    foreach (var pu in update.PropertyUpdates)
                    {
                        Assert.AreEqual(pu.Value, e.Data[pu.Key]);
                    }

                    EntityUpdate update2 = new EntityUpdate(e.Name, e.Id);
                    update2.Set("rating", 5.5m + r.Next(4));
                    update2.Set("lastname", e.Data["lastname"] + "_EDIT");

                    repository.Update(update2.ToEntity());
                    e = repository.Read(q);
                    foreach (var pu in update2.PropertyUpdates)
                    {
                        Assert.AreEqual(pu.Value, e.Data[pu.Key]);
                    }
                    foreach (var pu in update.PropertyUpdates)
                    {
                        if (!pu.Key.Equals("rating", StringComparison.InvariantCultureIgnoreCase) && !pu.Key.Equals("lastname", StringComparison.InvariantCultureIgnoreCase))
                            Assert.AreEqual(pu.Value, e.Data[pu.Key]);
                    }

                }

                ctx.Complete();
            }

            using (var ctx = dbService.GetDatabaseContext(true))
            {
                var qAll = new EntityQuery2("Author");
                var all = repository.Search(qAll);
                Assert.AreEqual(1000, all.Count());
                foreach (var a in all)
                    repository.Delete(a);
                Assert.AreEqual(0, repository.Search(qAll).Count());
            }
        }
Esempio n. 38
0
        public void Test_EntityOperation_Update()
        {
            var dbService = new TestDatabaseService();
            var repo = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            IEntityOperationService svc = new EntityOperationService(repo, dbService, new IEntityOperationInspector[] { new Inspector() }, new IEntityQueryInspector[] { new Inspector() }, new IEntityOperationLogic[] { new Logic() });
            EntityUpdate update = new EntityUpdate("Author");
            update.Set("FirstName", "John");
            update.Set("LastName", "Tolkin");
            update.Set("Numberofawards", 2);
            update.Set("IsAlive", false);

            EntityUpdate book = new EntityUpdate("book");
            book.Set("Title", "The Eye of the World");
            book.Set("genre", Genre.Fantasy);

            svc.Update(book);
            update.Attach("Book", "author", book.Id.Value);

            var result = svc.Update(update);
            Assert.AreEqual(true, result.Success);

            EntityQuery2 query = new EntityQuery2("Author");
            query.AddProperties("FirstName", "LastName", "IsAlive", "CreatedOn");
            query.Include("book", "author");
            var res = repo.Search(query);
            Assert.AreEqual(1, res.Count());
            var a = res.Single();
            Assert.AreEqual("John", a.GetData<string>("Firstname"));
            Assert.AreEqual("Tolkin", a.GetData<string>("LastName"));
            var created = a.GetData<DateTime>("createdon");
            Assert.AreEqual(DateTime.Now.Date, created.Date);
            var books = a.GetManyRelations("book", "author");
            Assert.AreEqual(1, books.Count());
            var b = books.Single().Entity;
            Assert.AreEqual("The Eye of the World", b.GetData<string>("title"));
            Assert.AreEqual(Genre.Fantasy, b.GetData<Genre>("genre"));
            created = b.GetData<DateTime>("createdon");
            Assert.AreEqual(DateTime.Now.Date, created.Date);

            repo.Delete(a, true);
            repo.Delete(b);
        }
Esempio n. 39
0
        public EntityUpdate ToEntityUpdate()
        {
            var update = new EntityUpdate(this.Entity);
            update.Id = this.Id;
            if (PropertyUpdates != null)
                foreach (var pu in PropertyUpdates)
                    update.Set(pu.Name, pu.Value);
            if (RelationUpdates != null)
                foreach (var ru in RelationUpdates)
                {
                    var r = new RelationUpdate(ru.Entity, ru.Role, ru.Operation, ru.Id);
                    if (ru.PropertyUpdates != null)
                        foreach (var pu in ru.PropertyUpdates)
                            r.Set(pu.Name, pu.Value);
                    update.RelationUpdates.Add(r);
                }

            return update;
        }
Esempio n. 40
0
        public EntityOperationResult Update(EntityUpdate update)
        {
            using (var dbContext = _dbService.GetDatabaseContext(true))
            {
                var result = UpdateInternal(update);
                if (result.Success)
                    dbContext.Complete();

                return result;
            }
        }
Esempio n. 41
0
        private EntityOperationResult UpdateInternal(EntityUpdate update)
        {
            if (!RunInspection(update))
                return EntityOperationResult.FailResult(new EntityOperationError("Insufficient rights to perform this operation.", EntityOperationError.ACCESS_VIOLATION));

            EntityOperationContext ctx = new EntityOperationContext();

            this.AppyLogicBefore(update, ctx);

            var entity = update.ToEntity();
            EntityOperationResult result = null;
            bool created = false;
            try
            {
                if (update.Id.HasValue)
                {
                    if (update.PropertyUpdates.Count > 0)
                        _repository.Update(entity);
                }
                else
                {
                    update.Id = _repository.Create(entity);
                    created = true;
                }

                //Order by operation - process detach first
                foreach (var relUpdate in update.RelationUpdates.OrderByDescending(ru => ru.Operation))
                {
                    if (relUpdate.Operation == RelationOperation.Attach)
                        _repository.Attach(entity, relUpdate.ToRelation());
                    else if (relUpdate.Operation == RelationOperation.Detach)
                        _repository.Detach(entity, relUpdate.ToRelation());
                    else if (relUpdate.PropertyUpdates.Count > 0)
                    {
                        _repository.UpdateRelation(entity, relUpdate.ToRelation());
                    }
                }

                result = EntityOperationResult.SuccessResult();
                if (created)
                    result.Data.Add("Created", update.Id.Value);
            }
            catch (UniqueRuleViolationException rex)
            {
                result = EntityOperationResult.FailResult(new EntityOperationError(rex.Message, EntityOperationError.UNIQUE_RULE_VIOLATION));
            }
            this.AppyLogicAfter(update, ctx, result);
            return result;
        }