Esempio n. 1
0
        public async Task <IActionResult> PutPostAttachment([FromRoute] int id, [FromBody] PostAttachment postAttachment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != postAttachment.PostAttachmentId)
            {
                return(BadRequest());
            }

            _context.Entry(postAttachment).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostAttachmentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 2
0
        public async Task <IActionResult> PostPostAttachment([FromBody] PostAttachment postAttachment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.PostAttachment.Add(postAttachment);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetPostAttachment", new { id = postAttachment.PostAttachmentId }, postAttachment));
        }
Esempio n. 3
0
        public async Task <IActionResult> Create(Guid?postId, PostAttachmentEditModel model)
        {
            if (postId == null)
            {
                return(this.NotFound());
            }

            var post = await this.context.Posts
                       .SingleOrDefaultAsync(m => m.Id == postId);

            if (post == null || !this.userPermissions.CanEditPost(post))
            {
                return(this.NotFound());
            }

            var fileName = Path.GetFileName(ContentDispositionHeaderValue.Parse(model.File.ContentDisposition).FileName.Value.Trim('"'));
            var fileExt  = Path.GetExtension(fileName);

            if (!PostAttachmentsController.AllowedExtensions.Contains(fileExt))
            {
                this.ModelState.AddModelError(nameof(model.File), "This file type is prohibited");
            }

            if (this.ModelState.IsValid)
            {
                var postAttachment = new PostAttachment
                {
                    PostId  = post.Id,
                    Created = DateTime.UtcNow,
                };

                var attachmentPath = Path.Combine(this.hostingEnvironment.WebRootPath, "attachments", postAttachment.Id.ToString("N") + fileExt);
                postAttachment.Path = $"/attachments/{postAttachment.Id:N}{fileExt}";
                using (var fileStream = new FileStream(attachmentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read))
                {
                    await model.File.CopyToAsync(fileStream);
                }

                this.context.Add(postAttachment);
                await this.context.SaveChangesAsync();

                return(this.RedirectToAction("Details", "Posts", new { id = post.Id }));
            }

            this.ViewBag.Post = post;
            return(this.View(model));
        }
Esempio n. 4
0
        public async Task <bool> publishAttachment(PostAttachment x)
        {
            await sem.WaitAsync();

            Uri                 uri      = new Uri(string.Format("https://saabstudent2020.azurewebsites.net/observation/" + x.obsID + "/attachment", string.Empty));
            string              json     = JsonConvert.SerializeObject(x, Formatting.Indented);
            StringContent       content  = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                sem.Release();
                return(true);
            }
            sem.Release();
            return(false);
        }
Esempio n. 5
0
 public abstract void AddPostAttachment(Post post, PostAttachment attachment);
Esempio n. 6
0
        public static PostAttachment PopulatePostAttachmentFromIReader(IDataReader reader)
        {
            PostAttachment attachment = new PostAttachment();

            attachment.AttachmentID       = (Guid) reader["AttachmentID"];
            attachment.PostID       = (int) reader["PostID"];
            attachment.Content      = (byte[]) reader["Content"];
            attachment.ContentType  = (string) reader["ContentType"];
            attachment.Length       = (int) reader["ContentSize"];
            attachment.FileName     = (string) reader["FileName"];
            attachment.RealFileName = (string) reader["RealFileName"];
            attachment.UserID       = (int) reader["UserID"];
            attachment.ForumID      = (int) reader["SectionID"];
            attachment.DownloadCount = (int) reader["DownloadCount"];
            attachment.DateCreated  = (DateTime) reader["Created"];

            return attachment;
        }
Esempio n. 7
0
        public static async Task <Post> FromCacheAsync(
            IResourceCacheService resourceCacheService,
            IInternalUserLoader internalUserLoader,
            IAttachmentLoader attachmentLoader,
            IPostLicenseLoader postLicenseLoader,
            CachePost cachePost,
            CancellationToken cancellationToken)
        {
            Ensure.Argument.IsNotNull(internalUserLoader, nameof(internalUserLoader));
            Ensure.Argument.IsNotNull(attachmentLoader, nameof(attachmentLoader));
            Ensure.Argument.IsNotNull(postLicenseLoader, nameof(postLicenseLoader));
            Ensure.Argument.IsNotNull(cachePost, nameof(cachePost));

            // Resolve dependencies.
            var userTask         = internalUserLoader.FetchAsync(cachePost.UserId, cancellationToken);
            var permissionsTask  = PostPermissions.FromCacheAsync(internalUserLoader, cachePost.Permissions, cancellationToken);
            var linksTasks       = cachePost.Links?.Select(r => PostReference.FromCacheAsync(internalUserLoader, r, cancellationToken)).ToList() ?? new List <Task <PostReference> >();
            var attachmentsTasks = cachePost.Attachments?.Select(a => PostAttachment.FromCacheAsync(attachmentLoader, a, cancellationToken)).ToList() ?? new List <Task <PostAttachment> >();
            var licensesTasks    = cachePost.Licenses?.Select(l => postLicenseLoader.LoadAsync(l, cancellationToken)).ToList() ?? new List <Task <PostLicense> >();

            await Task.WhenAll(
                userTask,
                permissionsTask,
                Task.WhenAll(linksTasks),
                Task.WhenAll(attachmentsTasks),
                Task.WhenAll(licensesTasks)
                );

            // Make sure all of our required dependencies are here.
            var user = userTask.Result;

            Ensure.Dependency.IsNotNull(user, nameof(user));

            var licenses = licensesTasks.Select(t => t.Result).ToList();

            Ensure.Dependency.IsNotNull(licenses, nameof(licenses));

            return(new Post(resourceCacheService)
            {
                Id = cachePost.Id,
                VersionId = cachePost.VersionId,

                CreatedAt = cachePost.CreatedAt,
                DeletedAt = cachePost.DeletedAt,
                OriginalCreatedAt = cachePost.OriginalCreatedAt,

                // User.
                User = user,
                OriginalEntity = cachePost.OriginalEntity,

                // Version.
                Type = PostType.FromString(cachePost.Type),
                Permissions = permissionsTask.Result,
                Links = linksTasks.Select(t => t.Result).ToList(),
                Attachments = attachmentsTasks.Select(t => t.Result).ToList(),
                Licenses = licenses,

                // Dates.
                PublishedAt = cachePost.PublishedAt,
                OriginalPublishedAt = cachePost.OriginalPublishedAt
            });
        }
Esempio n. 8
0
        public async Task <ActionResult> Upload(CreatePostViewModel viewModel)
        {
            var success = false;

            if (ModelState.IsValid)
            {
                var countOfAttachments = 0;

                var contentTypeArray = new string[]
                {
                    "video/mp4"
                    //"video/avi",
                    //"application/x-mpegURL",
                    //"video/MP2T",
                    //"video/3gpp",
                    //"video/quicktime",
                    //"video/x-msvideo",
                    //"video/x-ms-wmv"
                };

                //create new post entity
                var post = new Post
                {
                    PlateNumber  = viewModel.PlateNumber,
                    Description  = HttpUtility.HtmlDecode(viewModel.Description),
                    UserID       = User.Identity.GetUserId(),
                    DateUploaded = viewModel.DateUploaded,
                    BranchID     = CurrentUser.BranchID
                };

                // I removed the foreach loop
                // and use this instead since the posted file will always be one
                // and for performance reason
                var item = viewModel.Attachments.FirstOrDefault();

                //check if the item is null
                //or else throw an error
                if (item != null)
                {
                    //check if the content type is an MP4
                    if (!contentTypeArray.Contains(item.ContentType))
                    {
                        ModelState.AddModelError("", "video file must be an mp4 format");

                        return(Json(new { success = success, message = "Video file must be an mp4 format" }));
                    }

                    //increment the count of attachment
                    countOfAttachments++;

                    //get the fileName extension
                    var videoExt = Path.GetExtension(item.FileName);
                    //get the fileName
                    var videoFileName = Path.GetFileName(item.FileName);

                    //set the video path
                    var videoPath = Server.MapPath("~/Uploads/Videos");
                    //set the thumbnail path
                    var thumbnailPath = Server.MapPath("~/Uploads/Thumbnails");

                    //create new entity for each attachment
                    var attachment = new PostAttachment();

                    attachment.PostAttachmentID  = Guid.NewGuid().ToString();
                    attachment.FileName          = attachment.PostAttachmentID + videoExt;
                    attachment.MIMEType          = item.ContentType;
                    attachment.FileSize          = item.ContentLength;
                    attachment.FileUrl           = Path.Combine(videoPath, attachment.FileName);
                    attachment.DateCreated       = viewModel.DateUploaded;
                    attachment.AttachmentNo      = $"Attachment {countOfAttachments.ToString()}";
                    attachment.ThumbnailFileName = attachment.PostAttachmentID + ".jpeg";
                    attachment.ThumbnailUrl      = Path.Combine(thumbnailPath, attachment.ThumbnailFileName);

                    //concatenate the path and the filename
                    var videoToSaveBeforeConvertingPath = Path.Combine(videoPath, videoFileName);

                    //save the video
                    using (var fileStream = System.IO.File.Create(videoToSaveBeforeConvertingPath))
                    {
                        var stream = item.InputStream;
                        stream.CopyTo(fileStream);
                    }

                    //for conversion
                    var ffMpeg = new FFMpegConverter();


                    //Set the path of the exe of FFMpeg
                    ffMpeg.FFMpegToolPath = videoPath;

                    //create a file instance
                    var file = new FileInfo(videoToSaveBeforeConvertingPath);

                    //check if the file exists after saving the video
                    if (file.Exists)
                    {
                        //codec for mp4
                        var convertSettings = new ConvertSettings
                        {
                            AudioCodec = "aac",
                            VideoCodec = "h264"
                        };
                        //set the resolution
                        convertSettings.SetVideoFrameSize(1280, 720);

                        //convert the saved file
                        //attachment.FileUrl is the new output filename
                        ffMpeg.ConvertMedia(videoToSaveBeforeConvertingPath, Format.mp4, attachment.FileUrl, Format.mp4, convertSettings);

                        //get the thumbnail of the video for
                        ffMpeg.GetVideoThumbnail(attachment.FileUrl, attachment.ThumbnailUrl);

                        //Once the conversion is successful delete the original file
                        file.Delete();

                        //add the attachment to post entity
                        post.Attachments.Add(attachment);
                    }
                }


                //find the first attachment
                var attached = post.Attachments.FirstOrDefault();

                //if the attachment is not null save it else throw an error
                if (attached != null)
                {
                    //add the post entity and save
                    _uow.Posts.Add(post);
                    await _uow.SaveChangesAsync();


                    //fetch the end-users who have approval access
                    var claims = await _uow.UserClaims.GetAllByClaimTypeAndValueAsync("Approval", "CanApproveVideo");

                    if (claims.Count > 0)
                    {
                        StringBuilder recipients = new StringBuilder();

                        //loop through and create a semicolon separated values
                        //to be used in sending email notification to the supervisors
                        claims.ForEach(claim =>
                        {
                            recipients.Append(claim.User.Email)
                            .Append(";");
                        });

                        //get the url of the posted video
                        //to be included in the email
                        var url = Request.Url.Scheme + "://" + Request.Url.Authority +
                                  Url.Action("post", new
                        {
                            year    = post.DateUploaded.Year,
                            month   = post.DateUploaded.Month,
                            postID  = post.PostID,
                            plateNo = post.PlateNumber
                        });

                        //send email
                        try
                        {
                            await _mgr.CustomSendEmailAsync(
                                User.Identity.GetUserId(),
                                "New posted video",
                                EmailTemplate.GetTemplate(
                                    CurrentUser,
                                    "Supervisors",
                                    "I have posted a new video. Please see the details for approval.",
                                    url),
                                recipients.ToString());
                        }
                        catch (SmtpException ex)
                        {
                            _uow.AppLogs.Add(new AppLog
                            {
                                Message  = ex.Message,
                                Type     = ex.GetType().Name,
                                Url      = Request.Url.ToString(),
                                Source   = (ex.InnerException != null) ? ex.InnerException.Message : string.Empty,
                                UserName = User.Identity.Name,
                                LogDate  = DateTime.UtcNow
                            });
                            await _uow.SaveChangesAsync();

                            success = true;

                            return(Json(new { success = success, message = "Uploaded successfully" }));
                        }
                    }
                    success = true;

                    return(Json(new { success = success, message = "Uploaded successfully" }));
                }
                ModelState.AddModelError("", "Attached has not been succesfully uploaded");
            }
            return(Json(new { success = success, message = "Something went wrong. Please try again" }));
        }
Esempio n. 9
0
        private async void PublishButton_Clicked(object sender, EventArgs e)
        {
            if (_isTapped)
            {
                return;
            }

            _isTapped = true;

            if (CrossConnectivity.Current.IsConnected)
            {
                try
                {
                    if (entrySubject.SelectedIndex > -1)
                    {
                        spinOn();
                        published = false;
                        startTiming();

                        PostAttachment attach = null;
                        if (bytes != null)
                        {
                            try
                            {
                                attach = new PostAttachment(0, bytes);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }
                        string title = entrySubject.Items[entrySubject.SelectedIndex];
                        if (GPSFetcher.currentPosition != null && attach != null && attach.description.Length < 3000000)
                        {
                            title += GlobalFuncs.marker;
                        }
                        createPost pubPost = new createPost(title, entryBody.Text, GPSFetcher.currentPosition);
                        int        status  = -2;
                        status = await conn.testPublishPosts(pubPost);

                        // Sen skapa PostAttachment och publicera den
                        if (status >= 0 && bytes != null && attach != null)
                        {
                            attach.obsID = status;
                            bool success = await conn.publishAttachment(attach);

                            if (success)
                            {
                                imgCam.Source  = null;
                                entryBody.Text = "";

                                published = true;
                                spinOff();
                            }
                            else // Publication of attachment failed.
                            {
                                spinOff();
                                switch (Device.RuntimePlatform)
                                {
                                case Device.Android:
                                    DependencyService.Get <SnackInterface>().SnackbarShow("Publish failed");
                                    break;

                                case Device.iOS:
                                    CrossToastPopUp.Current.ShowToastMessage("Publish failed");
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        else // publish failed.
                        {
                            switch (Device.RuntimePlatform)
                            {
                            case Device.Android:
                                DependencyService.Get <SnackInterface>().SnackbarShow("Initial publish successful - no image attached therefore not displayed");
                                break;

                            case Device.iOS:
                                CrossToastPopUp.Current.ShowToastMessage("Initial publish successful - no image attached therefore not displayed");
                                break;

                            default:
                                break;
                            }
                            spinOff();
                        }
                    }
                    else // Please choose a category for your post.
                    {
                        switch (Device.RuntimePlatform)
                        {
                        case Device.Android:
                            DependencyService.Get <SnackInterface>().SnackbarShow("Please choose a category before publishing");
                            break;

                        case Device.iOS:
                            CrossToastPopUp.Current.ShowToastMessage("Please choose a category before publishing");
                            break;

                        default:
                            break;
                        }
                    }
                }
                catch (NullReferenceException error)
                {
                }



                if (published)
                {
                    await Navigation.PopModalAsync(true);

                    switch (Device.RuntimePlatform)
                    {
                    case Device.Android:
                        DependencyService.Get <SnackInterface>().SnackbarShow("The post was successfully published");
                        break;

                    case Device.iOS:
                        CrossToastPopUp.Current.ShowToastMessage("The post was successfully published");
                        break;

                    default:
                        break;
                    }
                }
            }
            else
            {
                switch (Device.RuntimePlatform)
                {
                case Device.Android:
                    DependencyService.Get <SnackInterface>().SnackbarShow("Internet is not available");
                    break;

                case Device.iOS:
                    CrossToastPopUp.Current.ShowToastMessage("Internet is not available");
                    break;

                default:
                    break;
                }
            }



            _isTapped = false;
        }