public async Task <ActionResult> EditAsync(string id)
        {
            if (id == null)
            {
                return(BadRequest());
            }

            Item item = await _respository.GetItemAsync(id);

            if (item == null)
            {
                return(NotFound());
            }

            return(View(item));
        }
예제 #2
0
        public async Task <ActionResult> EditAsync(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Item item = await db.GetItemAsync(id);

            if (item == null)
            {
                return(HttpNotFound());
            }

            return(View(item));
        }
예제 #3
0
        public async Task <IActionResult> Index(string searchString)
        {
            var result = await _documentDbRepository.GetItemAsync(searchString);

            result.TrashCanStatuses.Sort((x, y) => y.Timestamp.CompareTo(x.Timestamp));

            return(View(result));
        }
예제 #4
0
            public async Task <Unit> Handle(Request request, CancellationToken cancellationToken)
            {
                var orderRequest = await _orderRepository.GetItemAsync(request.Id);

                orderRequest.Reject();

                await _orderRepository.UpdateItemAsync(orderRequest);

                return(Unit.Value);
            }
예제 #5
0
        private async Task <bool> ToggleBotInChannel(IActivity activity, bool enabled, CancellationToken cancellationToken)
        {
            // First, check if the user sending the request is a Team Administrator.
            if (activity.From.Role == "bot")
            {
                return(false);
            }
            // THIS IS NOT THE BEST. I KNOW. I can't figure out how to get the list of admins for a channel.
            // (The Teams Bot documentation sucks for advanced users.)
            // Only let me and TechOps toggle the bot on and off.
            if (activity.From.Name.Contains("TechOps") || activity.From.Name.Contains("Aaron Rosenberger"))
            {
                string channelId = (string)activity.ChannelData["teamsChannelId"];
                string teamId;

                try
                {
                    teamId = (string)activity.ChannelData["teamsTeamId"];
                }
                catch (Exception)
                {
                    Trace.TraceError("Could not get team id.");
                    teamId = "defaultpartition";
                }

                _isEnabled = enabled;
                TeamsChannelMetadataModel metadata = await _db.GetItemAsync(channelId, teamId, cancellationToken);

                bool existsInDb = metadata != null;
                if (!existsInDb)
                {
                    metadata = new TeamsChannelMetadataModel
                    {
                        Id     = channelId,
                        TeamId = teamId
                    };
                }

                metadata.IsEnabled = _isEnabled;

                if (existsInDb)
                {
                    await _db.UpdateItemAsync(metadata.Id, metadata, metadata.TeamId, cancellationToken);
                }
                else
                {
                    await _db.CreateItemAsync(metadata, metadata.TeamId, cancellationToken);
                }

                return(true);
            }

            return(false);
        }
예제 #6
0
        public async Task <string> GetScore(Activity activity, Match match, CancellationToken cancellationToken)
        {
            KarmaModel karma;
            string     response = null;
            var        mention  = Utilities.GetUserMentions(activity).FirstOrDefault();
            var        entity   = match.Groups[1].Value;

            if (mention != null)
            {
                karma = await _db.GetItemAsync(mention.Mentioned.Id, "msteams_user", cancellationToken);

                response = $"{mention.Mentioned.Name}'s karma is {karma.Score}";
            }
            else if (!string.IsNullOrEmpty(entity))
            {
                karma = await _db.GetItemAsync(entity.ToLower(), "msteams_entity", cancellationToken);

                response = $"{entity}'s karma is {karma.Score}";
            }

            return(response);
        }
예제 #7
0
        /// <summary>
        /// Retrieves the indicated file.
        /// </summary>
        /// <param name="id">
        /// ID that uniquely identifies the file to be retrieved. The ID is is the key of the
        /// metadata stored in DocumentDb.
        /// </param>
        /// <returns>The file indicated by the specified ID.</returns>
        public async Task <HttpResponseMessage> Get(Guid?id)
        {
            // Check that token contains a user ID
            var userId = Thread.CurrentPrincipal == null ? null : Thread.CurrentPrincipal.GetUserIdFromPrincipal();

            if (userId == null)
            {
                return(HandleErrors(GeneralErrorCodes.TokenInvalid("UserId"), HttpStatusCode.Unauthorized));
            }

            // Make sure user ID is active
            var userIdGuid = new Guid(userId);
            var user       = await _context.Users.FirstOrDefaultAsync(u => u.Id == userIdGuid);

            if (user == null || !user.IsActive)
            {
                return(HandleErrors(GeneralErrorCodes.TokenInvalid("UserId"), HttpStatusCode.Unauthorized));
            }

            // Make sure there's a tenant associated with the user
            if (user.Tenants.Count < 1)
            {
                return(HandleErrors(GeneralErrorCodes.TokenInvalid("UserId"), HttpStatusCode.Unauthorized));
            }

            // Validate the argument (invalid Guid's are received as nulls)
            if (id == null)
            {
                return(HandleErrors(ValidationErrorCode.PropertyIsInvalid(nameof(id)), HttpStatusCode.BadRequest));
            }

            // Retrieve the metadata associated with the specified ID
            var metadata = await _documentDb.GetItemAsync(id.ToString());

            if (metadata == null || string.IsNullOrWhiteSpace(metadata.BlobStorageContainerName) ||
                string.IsNullOrWhiteSpace(metadata.BlobStorageBlobName))
            {
                return(HandleErrors(EntityErrorCode.EntityNotFound, HttpStatusCode.NotFound));
            }

            // Make sure the user is authorized (intentionally returns Not Found even though it's an authorization problem)
            if (metadata.TenantIds.Count < 1 ||
                !metadata.TenantIds.Intersect(user.Tenants.Select(u => u.Id)).Any())
            {
                return(HandleErrors(EntityErrorCode.EntityNotFound, HttpStatusCode.NotFound));
            }

            // Retrieve the blob
            var stream = new MemoryStream();
            BlobDownloadResult result;

            try
            {
                result = await _blobManager.DownloadBlobAsync(stream, _blobStorageConnectionString,
                                                              metadata.BlobStorageContainerName, metadata.BlobStorageBlobName);
            }
            catch (Exception ex)
            {
                FFLogManager.LogException(ex);
                return(HandleErrors(EntityErrorCode.EntityNotFound, HttpStatusCode.NotFound));
            }

            if (stream.Length == 0)
            {
                return(HandleErrors(EntityErrorCode.EntityNotFound, HttpStatusCode.NotFound));
            }

            // Create the response
            stream.Position = 0;
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            // Determine file name
            string filename = result.BlobName;

            if (!string.IsNullOrWhiteSpace(metadata.OriginalFileName))
            {
                var fileInfo = new FileInfo(metadata.OriginalFileName);
                if (!string.IsNullOrWhiteSpace(fileInfo.Name))
                {
                    filename = fileInfo.Name;
                }
            }

            // Set response content headers
            response.Content.Headers.ContentLength      = stream.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = filename,
                Size     = stream.Length
            };

            return(response);
        }
예제 #8
0
        /// <summary>
        /// Responds to a karma request. NOTE: Assumes <paramref name="karmaString"/> is a valid karma string.
        /// </summary>
        /// <param name="karmaString">A valid karma string.</param>
        /// <param name="uniqueId">If the entity given karma was a Teams user, the unique ID for that user</param>
        /// <param name="givenName">If the entity given karma was a Teams user, the Given Name for that user</param>
        /// <returns>The bot's response including the karma amount difference.</returns>
        public async Task <string> GetReplyMessageForKarma(string karmaString, string uniqueId, string givenName, CancellationToken cancellationToken)
        {
            // We don't want commonly used karma strings to be interpreted as karma, like "C++"
            if (KarmaBlacklist.Contains(karmaString.Replace(" ", "")))
            {
                return(null);
            }

            // Break down the karma string into parts
            Match karmaMatch = GetKarmaRegexMatch(karmaString);

            // Get the entity that was given karma
            string entityForMessaging = karmaMatch.Groups[1].Value;
            string uniqueEntity       = givenName ?? Regex.Replace(entityForMessaging, "<.*?>|@|\"|[\\s]", "").ToLower();

            // Delta: the karma in pluses or minuses.
            string delta = karmaMatch.Groups[2].Value;
            // The amount of karma to give or take away.
            int deltaLength = delta.Length - 1;

            if (delta.Contains("-"))
            {
                deltaLength *= -1;
            }

            string id        = uniqueId ?? uniqueEntity;
            string partition = GetPartitionForKey(karmaString);

            KarmaModel karmaItem = await _db.GetItemAsync(id, partition, cancellationToken);

            bool existsInDb = karmaItem != null;

            if (!existsInDb)
            {
                karmaItem = new KarmaModel
                {
                    Id        = id,
                    Entity    = uniqueEntity,
                    Partition = partition,
                    Score     = 0
                };
            }

            string replyMessage = string.Empty;

            if (deltaLength > 5)
            {
                // BUZZKILL MODE
                deltaLength   = 5;
                replyMessage += $"{Strings.BuzzkillMode} {Strings.BuzzkillModeMessage} ... ";
            }
            else if (deltaLength < -5)
            {
                deltaLength   = -5;
                replyMessage += $"{Strings.BuzzkillMode} {Strings.BuzzkillModeMessage} ... ";
            }

            string messageFormat;

            if (deltaLength > 0)
            {
                messageFormat = ReplyMessageIncreasedFormat;
            }
            else
            {
                messageFormat = ReplyMessageDecreasedFormat;
            }

            karmaItem.Score += deltaLength;
            replyMessage    += string.Format(messageFormat, entityForMessaging, karmaItem.Score);

            if (existsInDb)
            {
                await _db.UpdateItemAsync(id, karmaItem, partition, cancellationToken);
            }
            else
            {
                await _db.CreateItemAsync(karmaItem, partition, cancellationToken);
            }

            return(replyMessage);
        }