public async Task Execute()
        {
            // hack for testing from a project file
            //var videoFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(this.filePath));
            var videoFile = await StorageFile.GetFileFromPathAsync(this.filePath);
            var videoFileProperties = await videoFile.GetBasicPropertiesAsync();

            // determine number of chunks
            var fileSize = videoFileProperties.Size;
            var totalChunks = (long)((fileSize + CHUNK_SIZE) / CHUNK_SIZE);

            // send chunked upload request
            var chunkedUploadRequest = new ApiRequest("video/uploadchunked/request");
            chunkedUploadRequest.Authenticated = true;
            chunkedUploadRequest.AddJsonContent(new { VideoId = this.videoId, TotalChunks = totalChunks });
            var chunkedUploadRequestResponse = await chunkedUploadRequest.ExecuteAsync();

            // check response
            if (!chunkedUploadRequestResponse)
            {
                if (this.UploadFailed != null)
                    this.UploadFailed.Invoke(this, new EventArgs());

                return;
            }

            // open file for reading
            var newFileStream = await videoFile.OpenReadAsync();
            var videoFileStream = newFileStream.AsStream();
            byte[] buffer = new byte[CHUNK_SIZE];

            // iterate
            if (this.MissingChunks != null)
            {
                foreach (var chunk in this.MissingChunks)
                {
                    videoFileStream.Seek(chunk * CHUNK_SIZE, SeekOrigin.Begin);
                    int readCount = await videoFileStream.ReadAsync(buffer, 0, CHUNK_SIZE);

                    if (readCount > 0)
                    {
                        var uploadChunkRequest = new ApiRequest("video/uploadchunked/upload");
                        uploadChunkRequest.Authenticated = true;
                        uploadChunkRequest.Parameters.Add("VideoId", videoId.ToString());
                        uploadChunkRequest.Parameters.Add("ChunkId", chunk.ToString());
                        uploadChunkRequest.AddByteContent(buffer, 0, readCount);
                        var uploadChunkRequestResponse = await uploadChunkRequest.ExecuteAsync();

                        if (this.Progess != null)
                            this.Progess.Invoke(this, new ApiChunkedVideoUploadProgressEventArgs(chunk + 1, (int)totalChunks));
                    }
                }
            }
            else
            {
                //Parallel.For(0, totalChunks, async i =>
                //{
                //	int readCount = await videoFileStream.ReadAsync(buffer, 0, CHUNK_SIZE);

                //	if (readCount > 0)
                //	{
                //		var uploadChunkRequest = new ApiRequest("video/uploadchunked/upload");
                //		uploadChunkRequest.Authenticated = true;
                //		uploadChunkRequest.Parameters.Add("VideoId", videoId.ToString());
                //		uploadChunkRequest.Parameters.Add("ChunkId", i.ToString());
                //		uploadChunkRequest.AddByteContent(buffer, 0, readCount);
                //		var uploadChunkRequestResponse = await uploadChunkRequest.ExecuteAsync();

                //		if (this.Progess != null)
                //			this.Progess.Invoke(this, new ApiChunkedVideoUploadProgressEventArgs((int)i + 1, (int)totalChunks));
                //	}
                //});

                for (int i = 0; i < totalChunks; i++)
                {
                    int readCount = await videoFileStream.ReadAsync(buffer, 0, CHUNK_SIZE);

                    if (readCount > 0)
                    {
                        var uploadChunkRequest = new ApiRequest("video/uploadchunked/upload");
                        uploadChunkRequest.Authenticated = true;
                        uploadChunkRequest.Parameters.Add("VideoId", videoId.ToString());
                        uploadChunkRequest.Parameters.Add("ChunkId", i.ToString());
                        uploadChunkRequest.AddByteContent(buffer, 0, readCount);
                        var uploadChunkRequestResponse = await uploadChunkRequest.ExecuteAsync();

                        if (this.Progess != null)
                            this.Progess.Invoke(this, new ApiChunkedVideoUploadProgressEventArgs(i + 1, (int)totalChunks));
                    }
                }
            }

            // fire upload complete event
            if (this.UploadComplete != null)
                this.UploadComplete.Invoke(this, new EventArgs());
        }
        public async void Authenticate_User(string username, string password)
        {
            greetingsBanner.Visibility = Visibility.Collapsed;

            if (!App.HasNetworkConnection)
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("An network connection is needed to login.");
                await dialog.ShowAsync();
                return;
            }

            
            #region Adjust UI controls
            loginPopUp.Visibility = Visibility.Collapsed;
            loginBtn.Visibility = Visibility.Collapsed;
            signUpBtn.Visibility = Visibility.Collapsed;
            progressRing.Visibility = Visibility.Visible;
            progressRing.IsActive = true;
            usernameTxtBlock.Focus(Windows.UI.Xaml.FocusState.Pointer);
            #endregion

            try
            {
                var loginRequest = new ApiRequest("login");
                loginRequest.Authenticated = true;
                loginRequest.AddJsonContent(new { Username = username, Password = password});
                App.LoggedInUser = await loginRequest.ExecuteAsync<User>();

    
                appSettings[usernameKey] = username;
                appSettings[passwordKey] = password;
                appSettings[User] = JsonConvert.SerializeObject(App.LoggedInUser);

               

                
                await App.LoadUsersVideos();
                IEnumerable<VideoDataGroup> ArchiveGroup = App.ArchiveVideos.AllGroups;
                if (ArchiveGroup != null)
                    this.DefaultViewModel["Groups"] = ArchiveGroup;

                progressRing.Visibility = Visibility.Collapsed;
                progressRing.IsActive = false;
                logoutBtn.Visibility = Visibility.Visible;
                profileBtn.Visibility = Visibility.Visible;
                
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("Welcome back " + username + "!");
                await dialog.ShowAsync();
                lowerButtonsStackPanel.Visibility = Visibility.Visible;
                itemGridView.Visibility = Visibility.Visible; 
                 
            }
            catch (ApiException ex)
            {
                // api returned something other than 200 
                InvalidLoginCredentials();
                progressRing.Visibility = Visibility.Collapsed;
                greetingsBanner.Visibility = Visibility.Visible;
                progressRing.IsActive = false;
            }
            catch (Exception ex)
            {
                // If user credentials are invalid, we will catch it here 
                InvalidLoginCredentials();
            }

            

        }
示例#3
0
        private async Task UploadVideo(VideoUploadInBackgroundModel model)
        {
            int savedVideoId;


            // try to create the video in the system
            try
            {
                var createVideoRequest = new ApiRequest("createvideo");
                createVideoRequest.Authenticated = true;
                await createVideoRequest.AddJsonContentAsync(new { UserId = model.LoggedInUserId });
                var videoId = await createVideoRequest.ExecuteAsync<VideoIdModel>();
                savedVideoId = videoId.VideoId;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                this.UploadFailed(model);
                return;
            }

            // upload metadata, don't take no for an answer
            var metadataUploaded = false;
            while (!metadataUploaded)
            {
                try
                {
                    var videoMetadataRequest = new ApiRequest("uploadvideometadata");
                    videoMetadataRequest.Authenticated = true;
                    videoMetadataRequest.Parameters.Add("VideoId", savedVideoId.ToString());
                    videoMetadataRequest.AddJsonContent(JsonConvert.SerializeObject(model.Metadata));
                    metadataUploaded = await videoMetadataRequest.ExecuteAsync();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            // upload thumbnail, don't take no for an answer
            var thumbnailUploaded = false;
            while (!thumbnailUploaded)
            {
                try
                {
                    var thumbnailUploadRequest = new ApiRequest("uploadvideoimage");
                    thumbnailUploadRequest.Authenticated = true;
                    thumbnailUploadRequest.Parameters.Add("VideoId", savedVideoId.ToString());
                    await thumbnailUploadRequest.AddFileContentAsync(model.ImagePath);

                    thumbnailUploaded = await thumbnailUploadRequest.ExecuteAsync();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            var videoUploaded = false;
            int[] missingChunks = null;
            while (!videoUploaded)
            {
                try
                {
                    var videoUpload = new ApiChunkedVideoUpload(savedVideoId, model.VideoPath);
                    videoUpload.MissingChunks = missingChunks;
                    await videoUpload.Execute();

                    var videoCompleteRequest = new ApiRequest("video/uploadchunked/iscomplete");
                    videoCompleteRequest.Authenticated = true;
                    videoCompleteRequest.Parameters.Add("VideoId", savedVideoId.ToString());
                    missingChunks = await videoCompleteRequest.ExecuteAsync<int[]>();

                    if (missingChunks.Length == 0)
                        videoUploaded = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            this.deferral.Complete();
        }
示例#4
0
        private async void submitInfoBtn_Click_1(object sender, RoutedEventArgs e)
        {
            User responseUser = null;                     // The user which is returned if successful 
            int userID = -1;                             // userID of returned User

            // Get all of the information from the text fields
            var emailAddress = emailAddressTxtBox.Text;
            var username = usernameTxtBox.Text;
            var password = passwordTxtBox.Password;
            var confirmPassword = confirmPasswordTxtBox.Password;

            if (emailAddress == "" || username == "" || password == "" || confirmPassword == "")
            {
                var output = string.Format("Please fill out all fields.");
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(output);
                await dialog.ShowAsync();
                return; 
            }

            // Make sure the passwords match 
            if (password != confirmPassword)
            {
                var output = string.Format("Passwords must match.");
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(output);
                await dialog.ShowAsync();
                return; 
            }


            try
            {
                var signupRequest = new ApiRequest("signup");
                signupRequest.Authenticated = true;
                signupRequest.AddJsonContent(new { Email = emailAddress, Username = username, Password = password });
                responseUser = await signupRequest.ExecuteAsync<User>();

                if (responseUser != null)
                    userID = responseUser.UserId;
            }
            catch
            {
            }

            string successOutput;
            if (userID > 0)
            {
                successOutput = string.Format("Welcome to Archive, " + responseUser.Username + ".");
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(successOutput);
                await dialog.ShowAsync();
                App.LoggedInUser = responseUser;
                appSettings[usernameKey] = responseUser.Username;
                appSettings[passwordKey] = password;
                appSettings[User] = JsonConvert.SerializeObject(responseUser);
                this.Frame.Navigate(typeof(GroupedItemsPage)); 
            }
            else
            {
                successOutput = string.Format("Failed to create account. Please try again.");
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(successOutput);
                await dialog.ShowAsync();
            }


        }
        private async void submit_videoBtn_Click_1(object sender, RoutedEventArgs e)
        {
            #region Variable declarations
            WebResponse response;                   // Response from createvideo URL 
            Stream responseStream;                  // Stream data from responding URL
            StreamReader reader;                    // Read data in stream 
            string responseJSON;                    // The JSON string returned to us by the Archive API 
            CreateVideoResponse API_response;       // A simple object with only one attribute: VideoId 
            HttpClient httpClient = new HttpClient();
            HttpMessageHandler handler = new HttpClientHandler();
            int SavedVideoId = -1;
            VideoMetadata md = null;
            #endregion 

            this.Frame.Navigate(typeof(GroupedItemsPage)); 


            #region Adjust some controls while the video is being uploaded
            //// Close the metadata popup 
            video_metadataPopup.IsOpen = false;
            //uploadingPopUp.Visibility = Visibility.Visible;
            //uploadingPopUp.IsOpen = true;
            //backButton.Visibility = Visibility.Collapsed;
            //ButtonsPanel.Visibility = Visibility.Collapsed;
            #endregion 

            #region Make sure the user is logged in
            // Serialize a simple UserId object and send it to the Archive API
            if (App.LoggedInUser == null)
            {
                var error_output = string.Format("You are not currently logged in.");
                Windows.UI.Popups.MessageDialog error_dialog = new Windows.UI.Popups.MessageDialog(error_output);
                await error_dialog.ShowAsync();
                return;
            }
            #endregion

            #region Upload video
            string UserID_JSON = JsonConvert.SerializeObject(new { UserId = App.LoggedInUser.UserId });

            progressTxtBlock.Text = "Uploading video..."; 

            try
            {

                var createVideoRequest = new ApiRequest("createvideo");
                createVideoRequest.Authenticated = true;
                await createVideoRequest.AddJsonContentAsync(new { UserId = App.LoggedInUser.UserId });
                var videoId = await createVideoRequest.ExecuteAsync<VideoIdModel>();
                SavedVideoId = videoId.VideoId;

                var videoUpload = new ApiChunkedVideoUpload(SavedVideoId, videoFile.Path);
                await videoUpload.Execute();

                var isVideoComplete = new ApiRequest("video/uploadchunked/iscomplete");
                isVideoComplete.Parameters.Add("videoId", SavedVideoId.ToString());
                var array = await isVideoComplete.ExecuteAsync(); 

                
            }
            catch (ApiException ex)
            {
                // api returned something other than 200
            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion


            #region Extract video metadata from metadata pop up 
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    string videoName = "Untitled";
                    string archive_videoName = videoName;
                    string videoDescription = descriptionTxtBox.Text;
                    DateTime dateCreated = DateTime.Now;
                    bool isPublic = false;

                    if (privacyComboBox.SelectedIndex == 0)
                        isPublic = false;
                    else if (privacyComboBox.SelectedIndex == 1)
                        isPublic = true;

                    if (titleTxtBox.Text != "")
                    {
                        archive_videoName = titleTxtBox.Text;
                        videoName = titleTxtBox.Text + ".mp4";
                    }

                    tags = new string[tagsList.Count];
                    int i = 0;

                    foreach (string t in tagsList)
                    {
                        tags[i] = t;
                        i++; 
                    }
            // Create a VideoMetadata object 
            md = new VideoMetadata(SavedVideoId, archive_videoName, videoDescription, location_string, dateCreated.ToUniversalTime(), isPublic, tags);

            // Serialize the VideoMetadata object into JSON string
            string video_metadata_JSON = JsonConvert.SerializeObject(md);
                });
            #endregion  

            #region Send metadata
            progressTxtBlock.Text = "Uploading video metadata..."; 
            try
            {
                var videoMetadataRequest = new ApiRequest("uploadvideometadata");
                videoMetadataRequest.Authenticated = true;
                videoMetadataRequest.Parameters.Add("VideoId", SavedVideoId.ToString());
                videoMetadataRequest.AddJsonContent(md);

                var result = await videoMetadataRequest.ExecuteAsync(); 

            }
            catch (ApiException ex)
            {
                // api returned something other than 200
            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion
            
            #region Get a thumbnail image from the video file and upload it
            // Get thumbnail of the video file 
            var thumb = await videoFile.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView, 1000, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

            // Create a Buffer object to hold raw picture data
            var buffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumb.Size));

            // Read the raw picture data into the Buffer object 
            await thumb.ReadAsync(buffer, Convert.ToUInt32(thumb.Size), InputStreamOptions.None);

            // Open LocalFolder
            var folder = ApplicationData.Current.LocalFolder;

            // Create (or open if one exists) a folder called temp images
            folder = await folder.CreateFolderAsync("temp images", CreationCollisionOption.OpenIfExists);

            // Create a StorageFile 
            var thumbFile = await folder.CreateFileAsync(PHOTO_FILE_NAME, CreationCollisionOption.ReplaceExisting);

            // Write picture data to the file 
            await FileIO.WriteBufferAsync(thumbFile, buffer);

            // Preview the image
            var bmpimg = new BitmapImage();
            bmpimg.SetSource(thumb);
            PreviewImage.Source = bmpimg;

            try
            {

                var thumbnailUploadRequest = new ApiRequest("uploadvideoimage");
                thumbnailUploadRequest.Authenticated = true;
                thumbnailUploadRequest.Parameters.Add("VideoId", SavedVideoId.ToString());
                await thumbnailUploadRequest.AddFileContentAsync(thumbFile.Path);

                var result = await thumbnailUploadRequest.ExecuteAsync();

            }
            catch (ApiException ex)
            {
                // api returned something other than 200

            }
            catch (Exception ex)
            {
                // something bad happened, hopefully not api related
            }
            #endregion

            #region Upload complete, put the controls to normal
            uploadingPopUp.Visibility = Visibility.Collapsed;
            uploadingPopUp.IsOpen = false;
            //backButton.Visibility = Visibility.Visible; ;
            //ButtonsPanel.Visibility = Visibility.Visible;
            #endregion 

            #region Show success toast notification 
            //var notifier = ToastNotificationManager.CreateToastNotifier();
            //if (notifier.Setting == NotificationSetting.Enabled)
            //{
                
            //    var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

            //    var title = template.GetElementsByTagName("text")[0];
            //    title.AppendChild(template.CreateTextNode("Upload successful.")); 
            //    var message = template.GetElementsByTagName("text")[1];
            //    message.AppendChild(template.CreateTextNode("Your video " + archive_videoName + " has been uploaded successfully."));
                

            //    var toast = new ToastNotification(template);
            //    notifier.Show(toast);
            //}
            #endregion

            // Background task stuff
            //var VideoUploadObject = new VideoUploadInBackgroundModel(App.LoggedInUser.UserId, md, thumbFile.Path, videoFile.Path);

            //VideoUploadTask.RegisterVideoUpload(VideoUploadObject); 
            

            
        }