/* Constructor
         * Loads all DelegateCommand objects for button clicks.
         */
        public LoginPageViewModel()
        {
            loginCommand     = new DelegateCommand(LoginHelper.LoginOrRegisterAsync);
            LoadingIndicator = false;
            model            = new LoginPageModel();
            navService       = NavigationService.getNavigationServiceInstance();

            LoginHelper.LoginInitiated += (s, args) =>
            {
                LoadingIndicator = true;
            };

            LoginHelper.UserLoggedIn += async(s, user) =>
            {
                App.User = user;
                await App.notificationManager.InitNotificationsAsync(App.User.id);

                LoadingIndicator = false;
                navService.Navigate(typeof(MainPage));
            };

            LoginHelper.AuthError += async(s, errorMsg) =>
            {
                LoadingIndicator = false;
                ContentDialog loginFailDialog = new ContentDialog()
                {
                    Title             = "Could not Log in :(",
                    Content           = errorMsg,
                    PrimaryButtonText = "Ok"
                };

                await ContentDialogHelper.CreateContentDialogAsync(loginFailDialog, true);
            };
        }
Example #2
0
        private async Task <Tuple <Boolean, String> > createGroupNameInputDialog()
        {
            Boolean       cancelled            = false;
            String        groupName            = "";
            ContentDialog enterGroupNameDialog = new ContentDialog()
            {
                Title = "Rename Group"
            };
            var     panel        = new StackPanel();
            TextBox groupNameBox = setTextBox("Enter a group name", "");

            groupNameBox.MaxLength = maxCharacterLength;
            panel.Children.Add(groupNameBox);
            enterGroupNameDialog.Content = panel;

            enterGroupNameDialog.PrimaryButtonText   = "OK";
            enterGroupNameDialog.PrimaryButtonClick += delegate
            {
                groupName = groupNameBox.Text;
            };
            enterGroupNameDialog.SecondaryButtonText   = "Cancel";
            enterGroupNameDialog.SecondaryButtonClick += delegate
            {
                cancelled = true;
            };
            await ContentDialogHelper.CreateContentDialogAsync(enterGroupNameDialog, true);

            return(Tuple.Create(cancelled, groupName));
        }
Example #3
0
        /// <summary>
        /// Logs in or registers a user whose email has not already been registered.
        /// If successful, calls the UserLoggedIn event handler and sets the user in ApiHelper
        /// </summary>
        /// <param name="info">Information needed by the api to log a user in</param>
        /// <returns></returns>
        public static async void LoginOrRegisterAsync()
        {
            AuthenticationResult result = null;

            try
            {
                PublicClientApplication pca = App.AuthClient;
                result = await pca.AcquireTokenAsync(Globals.DefaultScopes);

                ApiHelper.setToken(result.AccessToken);

                LoginInitiated?.Invoke(DateTime.Now, null);

                Models.User user = await ApiHelper.GetAsync <Models.User>("User");

                if (user == null || user.Email == null)
                {
                    user = await ApiHelper.PostAsync <Models.User>("User");
                }



                if (user != null && !String.IsNullOrWhiteSpace(user.Email))
                {
                    UserLoggedIn?.Invoke(DateTime.Now, user);
                }
                else
                {
                    AuthError?.Invoke(DateTime.Now, "No connection to server.");
                }
            }
            catch (MsalException ex)
            {
                if (ex.ErrorCode != "authentication_canceled")
                {
                    string message = ex.Message;
                    if (ex.InnerException != null)
                    {
                        message += "\nInner Exception: " + ex.InnerException.Message;
                    }

                    AuthError?.Invoke(DateTime.Now, message);
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                // Launch warning popup
                ContentDialog notLoggedInDialog = new ContentDialog()
                {
                    Title             = "Could not login",
                    Content           = "Please check your wifi signal.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);
            }
        }
Example #4
0
        /// <summary>
        /// Creates a popup box to allow the user to change the group name and then sends the
        /// updated groupname to the server
        /// </summary>
        public async Task changeGroupNameAsync(GroupsContent groupContent)
        {
            if (App.User != null)
            {
                string currentGroupName     = groupContent.group.Name;
                Tuple <Boolean, String> tup = await createGroupNameInputDialog();

                // User inputs
                Boolean cancelled    = tup.Item1;
                string  newGroupName = tup.Item2;
                if (!cancelled && newGroupName != "")
                {
                    GroupChat updatedGroup = await renameGroupChat(groupContent.group, newGroupName);

                    // Display message to user if the name change failed (no server)
                    if (updatedGroup == null)
                    {
                        ContentDialog noServerDialog = new ContentDialog()
                        {
                            Title             = "Cannot change groupname",
                            Content           = "Is your wifi down?",
                            PrimaryButtonText = "Ok"
                        };
                        await ContentDialogHelper.CreateContentDialogAsync(noServerDialog, true);
                    }
                    else
                    {
                        string members = await getGroupMemberNames(updatedGroup);

                        GroupsContent updatedContent = new GroupsContent(updatedGroup, members);
                        updatedContent.updateCanvasFrom(groupContent);

                        // Preserve ordering
                        int originalIndex = getGroupsContentIndex(groupContent.group.id);
                        GroupsList.Remove(groupContent);
                        GroupsList.Insert(originalIndex, updatedContent);

                        // if the user is currently looking at the group, update the group content message history
                        if (RightFrameNavigator.GetLastContext() != null &&
                            RightFrameNavigator.GetLastContext().Equals(groupContent.messageHistoryViewModel))
                        {
                            RightFrameNavigator.Navigate(typeof(MessageHistoryView), updatedContent.messageHistoryViewModel);
                        }
                    }
                }
            }
        }
Example #5
0
        private async Task <Boolean> createLeaveGroupWarningDialog()
        {
            Boolean       leave = false;
            ContentDialog leaveGroupWarningDialog = new ContentDialog()
            {
                Title   = "You are about to leave this group.",
                Content = "Are you sure you would like to proceed?"
            };

            leaveGroupWarningDialog.PrimaryButtonText   = "Yes";
            leaveGroupWarningDialog.PrimaryButtonClick += delegate
            {
                leave = true;
            };
            leaveGroupWarningDialog.SecondaryButtonText   = "No";
            leaveGroupWarningDialog.SecondaryButtonClick += delegate
            {
                leave = false;
            };
            await ContentDialogHelper.CreateContentDialogAsync(leaveGroupWarningDialog, true);

            return(leave);
        }
Example #6
0
        /**
         * Method for dispatching a particular dialog depending on the contentDialogType parameter.
         * The user is the user name which is required for the dialog message content.
         */
        public virtual async void displayContentDialogDispatch(contentDialogType type, String user)
        {
            switch (type)
            {
            case contentDialogType.DNE:
                ContentDialog userInGroupDialog = new ContentDialog()
                {
                    Title             = "User Not Added",
                    Content           = user + " does not exist.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(userInGroupDialog, true);

                break;

            case contentDialogType.InvalidEmail:
                ContentDialog invalidUserEmailDialog = new ContentDialog()
                {
                    Title             = "User Not Added",
                    Content           = user + " is not a valid email address form.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(invalidUserEmailDialog, true);

                break;

            case contentDialogType.RepeatMember:
                ContentDialog repeatMemberDialog = new ContentDialog()
                {
                    Title             = "User Not Added",
                    Content           = user + " already in group.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(repeatMemberDialog, true);

                break;

            case contentDialogType.NoServer:
                ContentDialog noServerDialog = new ContentDialog()
                {
                    Title             = "User Not Added",
                    Content           = "Could not sync group with server.",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(noServerDialog, true);

                break;

            case contentDialogType.SuccessfulAdd:
                ContentDialog successDialog = new ContentDialog()
                {
                    Title             = user + " Successfully Added!",
                    Content           = "You will now be able to chat with " + user,
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(successDialog, true);

                break;

            case contentDialogType.NoEmail:
                ContentDialog noEmailDialog = new ContentDialog()
                {
                    Title             = "No User Added",
                    Content           = "Please enter an email address",
                    PrimaryButtonText = "Ok"
                };
                await ContentDialogHelper.CreateContentDialogAsync(noEmailDialog, true);

                break;
            }
        }
        private async void addGroup()
        {
            GroupsContent group;

            // Groups can only be retrieved if user is logged in
            if (App.User != null)
            {
                Boolean cancelled    = false;
                String  groupName    = "";
                String  groupMembers = "";
                //enterGroupNameDialog reference:
                // https://www.reflectionit.nl/blog/2015/windows-10-xaml-tips-messagedialog-and-contentdialog

                ContentDialog enterGroupNameDialog = new ContentDialog()
                {
                    Title = "Create a new group"
                };
                var panel = new StackPanel();

                // create the text box for user to set a group name
                TextBox groupNameBox = setTextBox("Enter a group name (max 20 characters)", "");
                // create the text box for user to add initial group members
                TextBox groupMemberBox = setTextBox("Enter user emails", "Separate multiple emails with a space...");

                // add the textboxes to the stackpanel
                panel.Children.Add(groupNameBox);
                panel.Children.Add(groupMemberBox);

                enterGroupNameDialog.Content = panel;

                enterGroupNameDialog.PrimaryButtonText   = "Create";
                enterGroupNameDialog.PrimaryButtonClick += delegate
                {
                    groupName    = groupNameBox.Text;
                    groupMembers = groupMemberBox.Text;
                };
                enterGroupNameDialog.SecondaryButtonText   = "Cancel";
                enterGroupNameDialog.SecondaryButtonClick += delegate
                {
                    cancelled = true;
                };
                await ContentDialogHelper.CreateContentDialogAsync(enterGroupNameDialog, true);

                if (!cancelled)
                {
                    if (groupName != "")
                    {
                        // initial list of users in group includes the logged in user and the groupMembers specified in groupMemberBox
                        List <string> users = await setInitialUserList(groupMembers);

                        GroupChat newGroup = new PenscribCommon.Models.GroupChat
                        {
                            GroupMembers = users,
                            CreationDate = DateTime.Now,
                            Name         = groupName
                        };

                        GroupChatApi api          = GroupChatApi.getInstance();
                        GroupChat    createdGroup = await api.postGroupChat(newGroup);

                        // Show error if group was unable to be posted to the server
                        if (createdGroup == null)
                        {
                            ContentDialog errorDialog = new ContentDialog()
                            {
                                Title             = "Unable to sync group with server",
                                Content           = "You are not connected to the server and so the group could not be pushed",
                                PrimaryButtonText = "Ok"
                            };

                            await ContentDialogHelper.CreateContentDialogAsync(errorDialog, true);

                            group = new GroupsContent(defaultGroup, "");
                        }
                        else
                        {
                            string members = await getGroupMemberNames(createdGroup);

                            group = new GroupsContent(createdGroup, members);
                        }

                        // update the content in the view
                        //displayNewGroup(group);
                        LeftFrameNavigator.Navigate(typeof(GroupsView), group);
                    }
                    else
                    {
                        ContentDialog invalidGroupNameDialog = new ContentDialog()
                        {
                            Title             = "Invalid group name",
                            Content           = "Please enter a group name",
                            PrimaryButtonText = "Ok"
                        };
                        await ContentDialogHelper.CreateContentDialogAsync(invalidGroupNameDialog, true);

                        addGroup();
                    }
                }
            }
            else
            {
                ContentDialog notLoggedInDialog = new ContentDialog()
                {
                    Title             = "Not logged in",
                    Content           = "You are not logged in and cannot sync with the server",
                    PrimaryButtonText = "Ok"
                };

                await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);

                group = new GroupsContent(defaultGroup, "");

                // update the content in the view
                //displayNewGroup(group);
                LeftFrameNavigator.Navigate(typeof(GroupsView), defaultGroup);
            }
        }
Example #8
0
        public async void sendText()
        {
            Message msgResponse = null;

            if (TextMsg != null && TextMsg != "")
            {
                LoadingIndicator = true;

                if (App.User == null)
                {
                    ContentDialog notLoggedInDialog = new ContentDialog()
                    {
                        Title             = "Not logged in",
                        Content           = "You are not logged in and cannot sync with the server",
                        PrimaryButtonText = "Ok"
                    };

                    await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);

                    return;
                }

                MessageApi api = MessageApi.getInstance();

                Message sentMsg = new Message
                {
                    SenderId    = App.User.id,
                    GroupChatID = group.group.id,
                    Content     = TextMsg
                };

                msgResponse = await api.sendMessageData(sentMsg);

                // If message was not sent to the server, initialize empty message with group id
                if (msgResponse == null)
                {
                    msgResponse = new PenscribCommon.Models.Message
                    {
                        id          = "---",
                        GroupChatID = group.group.id,
                        Content     = TextMsg
                    };
                    MessageContent badmsg = new MessageContent(msgResponse, App.User, null, MessageContent.errorImage);
                    History.Add(badmsg);
                    // Launch warning popup
                    ContentDialog notLoggedInDialog = new ContentDialog()
                    {
                        Title             = "No Wifi",
                        Content           = "Your message did not send. Please check your wifi signal.",
                        PrimaryButtonText = "Ok"
                    };
                    await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);
                }
                else
                {
                    MessageContent msg = new MessageContent(msgResponse, App.User, null);
                    History.Add(msg);
                }

                TextMsg          = "";
                LoadingIndicator = false;
            }
        }
        private async void send()
        {
            if (App.User == null)
            {
                ContentDialog notLoggedInDialog = new ContentDialog()
                {
                    Title             = "Not logged in",
                    Content           = "You are not logged in and cannot sync with the server",
                    PrimaryButtonText = "Ok"
                };

                await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);

                return;
            }

            try
            {
                LoadingIndicator = true;
                // Create a file for storing the drawing
                string        filename      = DateTime.Now.ToString("yyyy-MM-ddTHHmmssffff") + ".png";
                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                StorageFile   targetFile    = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                System.Diagnostics.Debug.WriteLine("Saving message as " + targetFile.Path);

                // Used to pass message back to MessagesHistory
                BitmapImage bitmapImage = new BitmapImage();

                Message msgResponse = null;

                if (targetFile != null)
                {
                    CanvasDevice       device       = CanvasDevice.GetSharedDevice();
                    CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)canvasElements.canvas.ActualWidth,
                                                                             (int)canvasElements.canvas.ActualHeight, BITMAP_DPI_RESOLUTION);

                    using (var drawSession = renderTarget.CreateDrawingSession())
                    {
                        // Set the background color of the image
                        drawSession.Clear(Colors.White);
                        //Transfer the background image to the bitmap image if there is a background image
                        if (BackgroundImagePath != null && BackgroundImagePath.Length > 0)
                        {
                            CanvasBitmap background = await CanvasBitmap.LoadAsync(device,
                                                                                   formatBackgroundFilePath(BackgroundImagePath));

                            drawSession.DrawImage(background);
                        }
                        if (imageFilePath != null)
                        {
                            System.Diagnostics.Debug.WriteLine(" SENDING IMAGE FILE ");
                            CanvasBitmap image = await CanvasBitmap.LoadAsync(device, imageFilePath);

                            drawSession.DrawImage(image, new Windows.Foundation.Rect(xOffset, yOffset, newWidth, newHeight));
                        }
                        // Transfer all the strokes to the bitmap image
                        drawSession.DrawInk(canvasElements.canvas.InkPresenter.StrokeContainer.GetStrokes());
                    }

                    using (IRandomAccessStream stream = await targetFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png, 1f);
                    }


                    MessageApi api = MessageApi.getInstance();

                    Message sentMsg = new Message
                    {
                        SenderId    = App.User.id,
                        GroupChatID = group.group.id
                    };

                    msgResponse = await api.sendMessageData(sentMsg);

                    if (msgResponse != null)
                    {
                        using (Stream stream = await targetFile.OpenStreamForReadAsync())
                        {
                            // Send the image file. If successful rename the local file to the id
                            if (await api.sendMessageFile(stream, msgResponse.id))
                            {
                                // rename the locally saved file to incorporate the server generated id
                                await targetFile.RenameAsync(msgResponse.id + ".png");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("File failed to send");
                                // Launch warning popup
                                ContentDialog notLoggedInDialog = new ContentDialog()
                                {
                                    Title             = "File failed to send",
                                    Content           = "Your message did not send. Please check your wifi signal.",
                                    PrimaryButtonText = "Ok"
                                };
                                await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);
                            }
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Message failed to send");
                        // Launch warning popup
                        ContentDialog notLoggedInDialog = new ContentDialog()
                        {
                            Title             = "File failed to send",
                            Content           = "Your message did not send. Please check your wifi signal.",
                            PrimaryButtonText = "Ok"
                        };
                        await ContentDialogHelper.CreateContentDialogAsync(notLoggedInDialog, true);
                    }
                }
                MessageContent msg      = null;
                Uri            imageUri = new Uri(targetFile.Path, UriKind.Absolute);

                // If message was not sent to the server, initialize empty message with group id
                if (msgResponse == null)
                {
                    msgResponse = new PenscribCommon.Models.Message
                    {
                        id          = "---",
                        GroupChatID = group.group.id,
                    };
                    msg = new MessageContent(msgResponse, App.User, imageUri, MessageContent.errorImage);
                }
                else
                {
                    msg = new MessageContent(msgResponse, App.User, imageUri);
                }

                //Uri imageUri = new Uri(targetFile.Path, UriKind.Absolute);
                //MessageContent msg = new MessageContent(msgResponse, App.User, imageUri);

                LeftFrameNavigator.NavigateSubFrame(typeof(MessageHistoryView), msg);

                // Clear the canvas
                canvasElements.canvas.InkPresenter.StrokeContainer.Clear();

                // Clear any background image
                BackgroundImagePath  = null;
                group.backgroundPath = null;

                // Clear any loaded image
                imageFilePath        = null;
                sourceImage          = null;
                ImageBitmap          = sourceImage;
                group.imageContainer = null;
            }
            finally
            {
                LoadingIndicator = false;
            }
        }