Exemple #1
0
        public HttpResponseMessage UploadPhoto([FromUri] int id)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }
            using (var db = new OnlineMusicEntities())
            {
                // Query artist in database and check artist is existed
                var user = (from u in db.UserInfoes
                            where u.Id == id
                            select u).FirstOrDefault();
                if (user == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Không tìm thấy user id=" + id));
                }

                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    using (var transaction = db.Database.BeginTransaction())
                    {
                        try
                        {
                            #region Upload file to drive
                            // Setup photo uploaded path
                            string ext      = Path.GetExtension(file.FileName).ToLower();
                            string fileName = user.FullName + ext;
                            string folderId = services.SearchFolder(user.User.Username, GoogleDriveServices.AVATARS) ??
                                              services.CreateFolder(user.User.Username, GoogleDriveServices.AVATARS);

                            Stream scaledImage = ImageFactory.Resize(file.InputStream);

                            // Photo will upload in Images/Avatars/{username}/{fileName}
                            string resourceId = services.UploadFile(scaledImage, fileName, Media.GetMediaTypeFromExtension(ext), folderId);
                            if (resourceId == null)
                            {
                                transaction.Rollback();
                                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Upload thất bại"));
                            }
                            else
                            {
                                // Add new resource
                                Resource resource = new Resource()
                                {
                                    Id   = resourceId,
                                    Name = fileName,
                                    Type = (int)ResourceTypeManager.Image
                                };
                                db.Resources.Add(resource);
                                db.SaveChanges();

                                // Update artist photo resource
                                user.Avatar = resourceId;
                                db.SaveChanges();
                                transaction.Commit();
                                return(Request.CreateResponse(HttpStatusCode.OK, String.Format("Upload avatar cho user {0} thành công", user.User.Username)));
                            }
                            #endregion Upload file to drive
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
                        }
                    }
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Dữ liệu upload không hợp lệ"));
                }
            }
        }
Exemple #2
0
        public HttpResponseMessage UploadSong([FromUri] long id)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }
            using (var db = new OnlineMusicEntities())
            {
                // Check if song existed in database
                var song = (from s in db.Songs
                            join u in db.Users on s.AuthorId equals u.Id
                            where s.Id == id
                            select s).FirstOrDefault();
                if (song == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Không tìm thấy media id=" + id));
                }

                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    using (var transaction = db.Database.BeginTransaction())
                    {
                        try
                        {
                            #region Upload file to drive
                            // Setup photo uploaded path
                            // Path.GetExtension return .{ext}
                            var ext      = Path.GetExtension(file.FileName).ToLower();
                            var fileName = song.Title + ext;
                            ResourceTypeManager resourceType = Media.GetResourceType(ext);
                            string folderId;
                            string message;

                            if (resourceType == ResourceTypeManager.Video)
                            {
                                folderId = services.SearchFolder(song.User.Username, GoogleDriveServices.VIDEOS) ??
                                           services.CreateFolder(song.User.Username, GoogleDriveServices.VIDEOS);
                                message = $"{song.User.Username} vừa upload video mới";
                            }
                            else
                            {
                                folderId = services.SearchFolder(song.User.Username, GoogleDriveServices.MUSICS) ??
                                           services.CreateFolder(song.User.Username, GoogleDriveServices.MUSICS);
                                message = $"{song.User.Username} vừa upload bài hát mới";
                            }

                            // Photo will upload in Musics/{username}/{fileName}
                            var resourceId = services.UploadFile(file.InputStream, fileName, Media.GetMediaTypeFromExtension(ext), folderId);
                            if (resourceId == null)
                            {
                                transaction.Rollback();
                                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Upload thất bại"));
                            }
                            else
                            {
                                // Add new resource
                                Resource resource = new Resource()
                                {
                                    Id   = resourceId,
                                    Name = fileName,
                                    Type = (int)resourceType
                                };
                                db.Resources.Add(resource);
                                db.SaveChanges();

                                // Update song resource
                                song.ResourceId = resourceId;
                                db.SaveChanges();
                                transaction.Commit();

                                try
                                {
                                    List <Notification> notifications = new List <Notification>();
                                    foreach (User user in song.User.User1)
                                    {
                                        Notification notification = new Notification()
                                        {
                                            Title     = "Thông báo từ người dùng",
                                            Message   = message,
                                            CreatedAt = DateTime.Now,
                                            UserId    = user.Id,
                                            IsMark    = false,
                                            Action    = NotificationAction.UPLOAD
                                        };
                                        notifications.Add(notification);
                                    }
                                    if (notifications.Count > 0)
                                    {
                                        db.Notifications.AddRange(notifications);
                                        db.SaveChanges();
                                        transaction.Commit();
                                    }
                                }
                                catch
                                {
                                }

                                return(Request.CreateResponse(HttpStatusCode.OK, String.Format("Upload media {0} thành công", song.Title)));
                            }
                            #endregion Upload file to drive
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
                        }
                    }
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Dữ liệu upload không hợp lệ"));
                }
            }
        }