Ejemplo n.º 1
0
        public async Task <IActionResult> GetUserInfo()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(Unauthorized());
            }
            var userDetail = await _context.Users.FirstOrDefaultAsync(x => x.Id == user.Id);

            return(Json(new {
                userDetail?.Name,
                userDetail?.Surname,
                Email = user.Email.ToLowerInvariant(),
                user.DateOfAccident,
                ProfilePicture = AmazonS3Helper.GenerateUrl(user.ProfilePictureKey),
                IsAssigned = user.AssignedToAttorneyId.HasValue
            }));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Index(int page = 0, int itemPerPage = 10)
        {
            Predicate <ApplicationUser> conditionalResults = x => true;

            var user = await _userManager.GetUserAsync(User);

            if (User.IsInRole("Attorney"))
            {
                var userId   = new Guid(user.Id);
                var attorney = await _context.Attorneys.FirstOrDefaultAsync(x => x.AttorneyUserId == userId);

                conditionalResults = x => x.AssignedToAttorneyId == attorney.Id;
            }

            var total = await _context.Users.CountAsync();

            var list = await _context.Users
                       .Include(x => x.AssignedToAttorney)
                       .Where(x => conditionalResults(x))
                       .Select(x => new CreateClientViewModel {
                //RegistrationCode = x.Code,
                Surname            = x.Surname,
                Name               = x.Name,
                Email              = x.UserName,
                Id                 = x.Id,
                CreatedAt          = x.DateOfAccident,
                AssignedToAttorney = x.AssignedToAttorneyId.HasValue ? (x.AssignedToAttorney.Name + " " + x.AssignedToAttorney.Surname) : "Not Assigned",
                ImageURL           = AmazonS3Helper.GenerateUrl(x.ProfilePictureKey, "attorney-journal-dev")
            })
                       .OrderByDescending(x => x.CreatedAt)
                       // .Skip (page * itemPerPage)
                       // .Take (itemPerPage)
                       .ToListAsync();

            return(View(new TablePagination <CreateClientViewModel> {
                Total = total,
                Lists = list
            }));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Upload()
        {
            //StringValues UniqueUploadId = default(StringValues);
            //StringValues UploadType = default(StringValues);

            //Request.Headers.TryGetValue("unique-upload-id", out UniqueUploadId);
            //Request.Headers.TryGetValue("upload-type", out UploadType);
            Request.Headers.TryGetValue("X-Upload-Title", out StringValues uploadTitle);
            Request.Headers.TryGetValue("X-Date-Taken", out StringValues dateTaken);

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(BadRequest());
            }

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }

            // Used to accumulate all the form url encoded key value pairs in the
            // request.
            var formAccumulator = new KeyValueAccumulator();

            var         objectKey      = Guid.NewGuid().ToString();
            var         thumbObjectKey = $"{Guid.NewGuid()}.jpg";
            FileStorage parent         = null;

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        var targetFilePath = Path.GetTempFileName();
                        using (var targetStream = System.IO.File.Create(targetFilePath)) {
                            await section.Body.CopyToAsync(targetStream);

                            _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'");
                        }

                        var partName         = contentDisposition.Name;
                        var strippedFileName = contentDisposition.FileName.Replace("\"", string.Empty);
                        var mimeType         = MimeTypesHelper.GetMimeType(strippedFileName);
                        var fileExtension    = $".{strippedFileName.Split('.').LastOrDefault()}";
                        var originalFileName = strippedFileName.Replace(fileExtension, string.Empty);

                        var type   = FileStorageType.Thumb;
                        var isFile = partName.Replace("\"", string.Empty) == "file";

                        if (mimeType.Contains("image") && isFile)
                        {
                            type = FileStorageType.Image;
                        }
                        else if (mimeType.Contains("video") && isFile)
                        {
                            type = FileStorageType.Video;
                        }

                        if (isFile)
                        {
                            objectKey = $"{objectKey}{fileExtension}";
                        }

                        try {
                            using (var amazonClient = new AmazonS3Helper(_amazonS3, "attorney-journal-dev")) {
                                await amazonClient.UploadFileAsync(targetFilePath, isFile?objectKey : thumbObjectKey);
                            }

                            var date = new DateTime();
                            try {
                                date = DateTime.Parse(dateTaken);
                            } catch (System.Exception) { }

                            var newFile = new FileStorage {
                                Parent          = parent,
                                AmazonObjectKey = isFile ? objectKey : thumbObjectKey,
                                CreatedAt       = DateTime.UtcNow,
                                FileExtension   = fileExtension,
                                OriginalName    = originalFileName,
                                MimeType        = mimeType,
                                Owner           = user,
                                Type            = type,
                                Title           = uploadTitle.FirstOrDefault() ?? string.Empty,
                                DateTaken       = date
                            };

                            _context.Files.Add(newFile);

                            parent = isFile ? newFile : null;
                        } catch (AmazonS3Exception s3Exception) {
                            Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // Bind form data to a model
            var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture);

            var bindingSuccessful = await TryUpdateModelAsync(new { }, string.Empty, formValueProvider);

            if (!bindingSuccessful || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _context.SaveChangesAsync(CancellationToken.None);

            return(Json(new { fileUrl = AmazonS3Helper.GenerateUrl(objectKey), thumbUrl = AmazonS3Helper.GenerateUrl(thumbObjectKey), result = true }));
        }
Ejemplo n.º 4
0
        public static async Task <UserTimelineModel> GetTimeLine(ApplicationDbContext context, string userId, List <Guid> listIds = null, bool showDummy = false)
        {
            var userDetail = await context.Users.FirstOrDefaultAsync(x => x.Id == userId);

            if (userDetail == null)
            {
                return(null);
            }

            var userTimeline = new UserTimelineModel();
            IQueryable <FileStorage> files = context.Files;

            if (listIds != null && listIds.Any())
            {
                files = context.Files.Where(x => listIds.Contains(x.Id));
            }

            userTimeline.Name           = userDetail.Name;
            userTimeline.Surname        = userDetail.Surname;
            userTimeline.UserId         = userDetail.Id;
            userTimeline.DateOfAccident = userDetail.DateOfAccident.GetValueOrDefault(DateTime.UtcNow);
            userTimeline.PhotoURL       = AmazonS3Helper.GenerateUrl(userDetail.ProfilePictureKey, "attorney-journal-dev");

            userTimeline.Items = await files.Where(x => x.Owner.Id == userId && x.Parent == null).Select(
                x => new TimelineItemModel {
                CreatedAt = x.CreatedAt,
                File      = new ItemModel {
                    Id            = x.Id,
                    Title         = x.Title,
                    Content       = x.Content,
                    FileExtension = x.FileExtension,
                    MimeType      = x.MimeType,
                    ObjectKey     = x.AmazonObjectKey,
                    ObjectUrl     = AmazonS3Helper.GenerateUrl(x.AmazonObjectKey, "attorney-journal-dev"),
                    Type          = x.Type,
                    Viewed        = x.Viewed,
                    DateTaken     = x.DateTaken
                },
                Thumb = context.Files.Where(y => y.Parent == x).Select(y => new ItemModel {
                    FileExtension = y.FileExtension,
                    MimeType      = y.MimeType,
                    ObjectKey     = y.AmazonObjectKey,
                    ObjectUrl     = GetImageAsBase64Url(AmazonS3Helper.GenerateUrl(y.AmazonObjectKey, "attorney-journal-dev")),
                    DateTaken     = x.DateTaken
                }).FirstOrDefault()
            }).OrderByDescending(x => x.CreatedAt).ToListAsync(CancellationToken.None);

            if (showDummy)
            {
                userTimeline.Items.Add(new TimelineItemModel
                {
                    CreatedAt = DateTime.Now,
                    File      = new ItemModel
                    {
                        Id            = Guid.NewGuid(),
                        Title         = "test image",
                        Content       = "this is test image",
                        Type          = FileStorageType.Image,
                        FileExtension = "jpg",
                        MimeType      = "img/jpg",
                        ObjectUrl     = "https://appwrk.com/wp-content/themes/appwrk_theme/images/testi_1.jpg",
                        Viewed        = true,
                        DateTaken     = DateTime.Now
                    },
                    Thumb = new ItemModel
                    {
                        FileExtension = "jpg",
                        MimeType      = "img/jpg",
                        ObjectUrl     = GetImageAsBase64Url("https://appwrk.com/wp-content/themes/appwrk_theme/images/testi_1.jpg"),
                        DateTaken     = DateTime.Now
                    }
                });

                userTimeline.Items.Add(new TimelineItemModel
                {
                    CreatedAt = DateTime.Now,
                    File      = new ItemModel
                    {
                        Id        = Guid.NewGuid(),
                        Title     = "test video",
                        Content   = "this is test video",
                        Type      = FileStorageType.Video,
                        ObjectUrl = "https://www.youtube.com/watch?v=e_04ZrNroTo",
                        Viewed    = true,
                        DateTaken = DateTime.Now
                    },
                    Thumb = new ItemModel
                    {
                        ObjectUrl = GetImageAsBase64Url("http://i3.ytimg.com/vi/e_04ZrNroTo/hqdefault.jpg"),
                        DateTaken = DateTime.Now
                    }
                });
            }

            return(userTimeline);
        }