public bool AddResource(int albumID, string resourceID)
        {
            bool success = false;

            //throw new Exception("forced error");
            Repository.ResourceRepository rr = new Repository.ResourceRepository();

            AlbumResource albumResource = rr.GetOrCreateAlbumResource(albumID, resourceID, User.Identity.Name);

            //DigitalResource resource = null;
            if (albumResource.Album != null && albumResource.Resource != null)
            {
                if (albumResource.ID == 0)//needs to be saved to the database
                {
                    if (albumResource.IsValid)
                    {
                        rr.SaveAlbumResource(albumResource);
                    }
                }
            }
            else
            {
                success = false;
                throw new System.Exception("Unable to add resource to Album. Check that you own both resource and album and that they exist");
            }

            return(true);
        }
        public IHttpActionResult UploadResource()
        {
            //throw new Exception("forced error");
            HttpResponseMessage response = new HttpResponseMessage();
            var             httpRequest  = HttpContext.Current.Request;
            DigitalResource myResource   = null;

            //DigitalResource resource = null;
            //if (albumID != null)
            {
                System.Web.HttpFileCollection files         = System.Web.HttpContext.Current.Request.Files;
                Repository.ResourceRepository repository    = new Repository.ResourceRepository();
                ReferenceRepository           refRepository = new ReferenceRepository();
                UserRepository ur          = new UserRepository();
                string         currentUser = User.Identity.Name;
                User           user        = ur.Get(currentUser);
                //Album album = repository.GetAlbums(x => x.Name == albumID).FirstOrDefault();

                //for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[0];

                    string name = file.FileName;
                    using (Stream fileStream = file.InputStream)
                    {
                        myResource = repository.SaveOrGet(refRepository, user, fileStream, name);
                    }
                }
            }

            return(Ok(myResource));
        }
        public ResourceListViewModel AlbumResources(int AlbumID, int PageNumber)
        {
            IResourceRepository repository = new Repository.ResourceRepository();

            try
            {
                string userName = this.User.Identity.Name;

                Album album = repository.GetAlbum(AlbumID, userName);

                ResourceListViewModel resourceVM = new ResourceListViewModel
                {
                    Resources = album.Resources.Skip((PageNumber - 1) * 20).Take(20).ToList(),
                    Total     = album.Resources.Count
                };

                //Clear the album's resources to prevent circular reference converting to json
                album.Resources.Clear();

                return(resourceVM);
            }
            catch (Exception e)
            {
                throw new System.Exception("No such album called " + AlbumID);
            }
        }
        public bool DoesMd5Exist(string id)
        {
            UserRepository ur          = new UserRepository();
            string         currentUser = User.Identity.Name;
            User           user        = ur.Get(currentUser);

            Repository.ResourceRepository repository = new Repository.ResourceRepository();
            return(repository.ResourceExists(id, user));
        }
        public AlbumListViewModel Get()//GetAllAlbums()
        {
            string userName = User.Identity.Name;
            AlbumListViewModelFactory albumListFactory = new AlbumListViewModelFactory();
            IResourceRepository       repository       = new Repository.ResourceRepository();
            AlbumListViewModel        vm = albumListFactory.GetAlbumListViewModel(repository, userName);

            return(vm);
        }
        public List <DigitalResource> OrphanResources()
        {
            IResourceRepository repository = new Repository.ResourceRepository();

            string userName = this.User.Identity.Name;

            List <DigitalResource> resources = repository.GetOrphanResourcesForUser(userName);

            return(resources);
        }
        public async Task <Album> PostAlbum(Album album)
        {
            //add to the database
            string         userName = this.User.Identity.Name;
            UserRepository ur       = new UserRepository();
            User           user     = ur.Get(userName);

            album.Owner = user;

            IResourceRepository repository = new Repository.ResourceRepository();

            repository.AddAlbum(album);
            return(album);
        }
        public void AddTag(string resourceID, string tag)
        {
            UserRepository ur       = new UserRepository();
            string         username = User.Identity.Name;
            User           user     = ur.Get(username);

            Repository.ResourceRepository repository = new Repository.ResourceRepository();
            TagRepository tagRepository = new TagRepository();

            DigitalResource resource = repository.Get(resourceID, user);

            ResourceModel.Tag tagToAdd = tagRepository.GetOrAdd(tag);

            resource.AddTag(tagToAdd);
        }
        public async Task <string> CompletePartialAndSaveResource(PartialUpload partialUploadDetails)
        {
            ReferenceRepository refRepository = new ReferenceRepository();
            UserRepository      ur            = new UserRepository();
            string currentUser = User.Identity.Name;
            User   user        = ur.Get(currentUser);

            Repository.ResourceRepository repository = new Repository.ResourceRepository();
            string resourceTagID = repository.CompletePartialAndSaveResource(refRepository,
                                                                             user,
                                                                             partialUploadDetails.uploadID, partialUploadDetails.originalName,
                                                                             partialUploadDetails.md5OfResource,
                                                                             partialUploadDetails.partTags,
                                                                             partialUploadDetails.totalSize);

            return(resourceTagID);
        }
        public Album GetAlbum(int id)
        {
            IResourceRepository repository = new Repository.ResourceRepository();

            string userName = this.User.Identity.Name;

            try
            {
                Album album = repository.GetAlbum(id, userName);
                //reset the resources list because it causes circular reference
                album.Resources = new List <ResourceModel.DigitalResource>();

                return(album);
            }
            catch (Exception e)
            {
                throw new System.Exception("No such album called " + id);
            }
        }
        public IHttpActionResult Upload(string albumID)
        {
            //throw new Exception("forced error");
            HttpResponseMessage response = new HttpResponseMessage();
            var             httpRequest  = HttpContext.Current.Request;
            DigitalResource myResource   = null;

            //DigitalResource resource = null;
            if (albumID != null)
            {
                System.Web.HttpFileCollection files         = System.Web.HttpContext.Current.Request.Files;
                Repository.ResourceRepository repository    = new Repository.ResourceRepository();
                ReferenceRepository           refRepository = new ReferenceRepository();
                UserRepository ur       = new UserRepository();
                string         username = User.Identity.Name;
                User           user     = ur.Get(username);
                Album          album    = repository.GetAlbums(x => x.Name == albumID).FirstOrDefault();

                //for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[0];

                    string name = file.FileName;
                    using (Stream fileStream = file.InputStream)
                    {
                        myResource = repository.SaveOrGet(refRepository, user, fileStream, name);
                        if (myResource != null)
                        {
                            album.AddResource(myResource);
                            repository.SaveAlbum(album);
                        }
                        //resource = myResource;
                        //response.Content = new StringContent("{\"Md5\": \""+ "12345" + "\"");
                        //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    }
                }
            }

            return(Ok(myResource));
        }
        public async Task <string> UploadPartial()
        {
            //assemble parameters
            var streamProvider = new CustomMultipartFileStreamProvider();
            await Request.Content.ReadAsMultipartAsync(streamProvider);

            string md5OfResource    = streamProvider.FormData["md5OfResource"];
            string uploadIdentifier = streamProvider.FormData["uploadIdentifier"];
            int    partNumber       = int.Parse(streamProvider.FormData["partNumber"]);
            int    numberOfParts    = int.Parse(streamProvider.FormData["numberOfParts"]);

            string id = String.Empty;
            HttpResponseMessage response = new HttpResponseMessage();
            var httpRequest = HttpContext.Current.Request;

            //DigitalResource resource = null;
            //if (albumID != null)
            foreach (KeyValuePair <string, Stream> file in streamProvider.FileStreams)
            {
                string fileName = file.Key;
                Stream stream   = file.Value;
                //System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                Repository.ResourceRepository repository    = new Repository.ResourceRepository();
                ReferenceRepository           refRepository = new ReferenceRepository();
                UserRepository ur          = new UserRepository();
                string         currentUser = User.Identity.Name;
                User           user        = ur.Get(currentUser);
                //Album album = repository.GetAlbums(x => x.Name == albumID).FirstOrDefault();

                //string name = file.FileName;

                id = await repository.UploadPartial(user, md5OfResource, uploadIdentifier, stream, partNumber, numberOfParts);
            }

            return(id);
        }
        public async Task <HttpResponseMessage> Get(string id)
        {
            bool isPartial = false;

            UserRepository ur       = new UserRepository();
            string         username = User.Identity.Name;
            User           user     = ur.Get(username);

            Repository.ResourceRepository repository = new Repository.ResourceRepository();
            DigitalResource resource = repository.Get(id, user);
            //await stream.CopyToAsync(stream2,);
            // Create a client
            AmazonS3Client client = new AmazonS3Client();

            long from = 0;
            long to   = 0;

            GetObjectRequest request = null;

            if (Request.Headers.Range != null)
            {
                isPartial = true;
                //If the last-byte-pos value is absent, or if the value is greater than or equal to the current length of the entity-body,
                //last -byte-pos is taken to be equal to one less than the current length of the entity- body in bytes.
                //*-The final 500 bytes(byte offsets 9500 - 9999, inclusive):
                //    bytes = -500
                //  - Or bytes = 9500 -
                if (Request.Headers.Range.Ranges.First().From == null)
                {
                    from = (resource.Size - 1) - (long)Request.Headers.Range.Ranges.First().To;
                }
                else //From byte is specified
                {
                    from = (long)Request.Headers.Range.Ranges.First().From;
                }

                to = resource.Size - 1;
                if (Request.Headers.Range.Ranges.First().To != null)
                {
                    to = (long)Request.Headers.Range.Ranges.First().To;
                }
                else//Chrome often sends out a 0- request. Instead of passing back a massive file, just pass back the first 500 bytes
                {
                    if (from == 0)
                    {
                        to = 499;
                    }
                }
                request = new GetObjectRequest
                {
                    BucketName = "piccoli",
                    Key        = id,
                    ByteRange  = new ByteRange(from, to)
                };
            }
            else
            {
                request = new GetObjectRequest
                {
                    BucketName = "piccoli",
                    Key        = id
                };
            }
            // Issue request and remember to dispose of the response
            //using
            GetObjectResponse   response = client.GetObject(request);
            HttpStatusCode      status   = isPartial ? HttpStatusCode.PartialContent : HttpStatusCode.OK;
            HttpResponseMessage result   = new HttpResponseMessage(status);

            result.Content = new StreamContent(response.ResponseStream);
            string contentType = response.Headers["Content-Type"];

            result.Content.Headers.ContentLength = resource.Size;
            if (isPartial)
            {
                result.Content.Headers.ContentLength = to - from + 1;//resource.Size;
                result.Content.Headers.ContentRange  = new ContentRangeHeaderValue(from, to, resource.Size);
            }
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue(contentType);//contentType);
            return(result);
        }
        public HttpResponseMessage GetThumbnailRepresentation(string id)
        {
            UserRepository ur       = new UserRepository();
            string         username = User.Identity.Name;
            User           user     = ur.Get(username);

            int thumbnailHeight = 120;

            Repository.ResourceRepository repository = new Repository.ResourceRepository();
            DigitalResource resource = repository.Get(id, user);
            string          mimeType = String.Empty;

            if (resource.OriginalFileName.IndexOf(".") > 0)
            {
                string extension = resource.OriginalFileName.Substring(resource.OriginalFileName.LastIndexOf(".") + 1);
                mimeType = MimeTypeHelper.GetMimeType(resource.OriginalFileName.Substring(resource.OriginalFileName.LastIndexOf(".") + 1));
            }

            //await stream.CopyToAsync(stream2,);
            // Create a client
            AmazonS3Client client = new AmazonS3Client();

            GetObjectRequest request = null;

            request = new GetObjectRequest
            {
                BucketName = "piccoli",
                Key        = id
            };

            // Issue request and remember to dispose of the response
            //using
            GetObjectResponse   response = client.GetObject(request);
            HttpResponseMessage result   = new HttpResponseMessage(HttpStatusCode.OK);


            if (mimeType.Contains("image"))
            {
                Image myImage = Image.FromStream(response.ResponseStream);

                float        multiplicationRatio = (float)thumbnailHeight / (float)myImage.Height;
                int          thumbnailWidth      = (int)(multiplicationRatio * myImage.Width);
                Bitmap       bmp          = ResizeImage(myImage, thumbnailWidth, thumbnailHeight);
                MemoryStream memoryStream = new MemoryStream();
                bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                memoryStream.Position = 0;
                result.Content        = new StreamContent(memoryStream);
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
            }
            //else if (mimeType.Contains("video"))
            //{
            //    VideoFileReader reader = new VideoFileReader();
            //    reader.
            //    Bitmap bmp = reader.ReadVideoFrame();
            //    MemoryStream memoryStream = new MemoryStream();
            //    bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //    memoryStream.Position = 0;
            //    result.Content = new StreamContent(memoryStream);
            //    result.Content.Headers.ContentType =
            //        new MediaTypeHeaderValue("application/octet-stream");
            //}
            else
            {
                MemoryStream memoryStream = TextToImage(200, 120, "Non image resource");
                result.Content = new StreamContent(memoryStream);
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
            }

            return(result);
        }