public async void PopulateMessagePage(string packetMessagePath)
        {
            if (string.IsNullOrEmpty(packetMessagePath))
            {
                return;
            }

            _packetMessage = PacketMessage.Open(packetMessagePath);

            _packetForm = CreateFormControlInstance(_packetMessage.PacFormName); // Should be PacketFormName, since there may be multiple files with same name
            if (_packetForm is null)
            {
                await ContentDialogs.ShowSingleButtonContentDialogAsync("Failed to find packet form.", "Close", "Packet Messaging Error");

                return;
            }
            PrintMsgTestViewModel.Instance.PacketForm = _packetForm;
            //_formsViewModel.PacketForm = _packetForm;

            _packetForm.FormPacketMessage = _packetMessage;

            StackPanel stackPanel = ContentArea;

            stackPanel.Margin = new Thickness(0, 0, 12, 0);

            stackPanel.Children.Clear();
            stackPanel.Children.Insert(0, _packetForm);

            if (_packetMessage.PacFormName == "SimpleMessage")
            {
                //_packetForm.MessageReceivedTime = DateTime.Now;
                switch (_packetMessage.MessageOrigin)
                {
                case MessageOrigin.Received:
                    (_packetForm.ViewModelBase as MessageFormControlViewModel).InBoxHeaderVisibility = true;
                    break;

                case MessageOrigin.Sent:
                    (_packetForm.ViewModelBase as MessageFormControlViewModel).SentHeaderVisibility = true;
                    break;

                default:
                    (_packetForm.ViewModelBase as MessageFormControlViewModel).NewHeaderVisibility = true;
                    break;
                }
            }
            FillFormFromPacketMessage();
            if (_packetMessage.MessageState == MessageState.Locked)
            {
                _packetForm.LockForm();
            }

            PrintMsgTestViewModel.Instance.PrintForm();
        }
Example #2
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (e.Parameter is null)
            {
                ViewModel.PopulateEmptyForm = true;
                return;
            }

            ViewModel.PopulateEmptyForm = false;

            string packetMessagePath = e.Parameter as string;
            //PacketMessage packetMessage = PacketMessage.OpenAsync(packetMessagePath);
            PacketMessage packetMessage = PacketMessage.Open(packetMessagePath);

            if (packetMessage != null)
            {
                packetMessage.MessageOpened = true;
                string directory = Path.GetDirectoryName(packetMessagePath);
                if (packetMessage.PacFormName.Contains("213RR"))
                {
                    webViewPivot.SelectedIndex = 1;
                }
                else if (packetMessage.PacFormName.Contains("213"))
                {
                    webViewPivot.SelectedIndex = 0;
                }
                else
                {
                    webViewPivot.SelectedIndex = 2;
                }

                FormControlBase formControl = FormsViewModel.CreateFormControlInstance(packetMessage.PacFormName);

                ConvertFromOutpost(ref packetMessage, ref formControl);
            }
        }
        public async Task BBSConnectAsync2()
        {
            (string bbsName, string tncName, string MessageFrom) = Utilities.GetProfileDataBBSStatusChecked();
            //BBSData bbs = PacketSettingsViewModel.Instance.BBSFromSelectedProfile;
            BBSData bbs = BBSDefinitions.Instance.BBSDataArray.Where(bBS => bBS.Name == bbsName).FirstOrDefault();
            //TNCDevice tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == tncName).FirstOrDefault();
            TNCDevice tncDevice = PacketSettingsViewModel.Instance.TNCFromSelectedProfile;

            //if (tncName.Contains(SharedData.EMail) && tncDevice is null)
            //{
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name.Contains(SharedData.EMail)).FirstOrDefault();
            //}

            _logHelper.Log(LogLevel.Info, "Start a new send/receive session");
            // Collect messages to be sent
            _packetMessagesToSend.Clear();
            List <string> fileTypeFilter = new List <string>()
            {
                ".xml"
            };
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

            // Get the files in the Outbox folder
            StorageFileQueryResult results = SharedData.UnsentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
            // Iterate over the results
            IReadOnlyList <StorageFile> unsentFiles = await results.GetFilesAsync();

            foreach (StorageFile file in unsentFiles)
            {
                // Add Outpost message format by Filling the MessageBody field in packetMessage.
                PacketMessage packetMessage = PacketMessage.Open(file.Path);
                if (packetMessage is null)
                {
                    _logHelper.Log(LogLevel.Error, $"Error opening message file {file.Path}");
                    continue;
                }

                // messages that are opened for editing will not be sent until editing is finished
                if (packetMessage.MessageState == MessageState.Edit)
                {
                    continue;
                }

                // Moved to send button processing
                //DateTime now = DateTime.Now;

                //var operatorDateField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorDate").FirstOrDefault();
                //if (operatorDateField != null)
                //{
                //    operatorDateField.ControlContent = $"{now.Month:d2}/{now.Day:d2}/{(now.Year):d4}";
                //}
                //var operatorTimeField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorTime").FirstOrDefault();
                //if (operatorTimeField != null)
                //    operatorTimeField.ControlContent = $"{now.Hour:d2}:{now.Minute:d2}";

                FormControlBase formControl = FormsViewModel.CreateFormControlInstance(packetMessage.PacFormName);
                if (formControl is null)
                {
                    _logHelper.Log(LogLevel.Error, $"Could not create an instance of {packetMessage.PacFormName}");
                    await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {packetMessage.PacFormName} not found");

                    continue;
                }
                packetMessage.MessageBody = formControl.CreateOutpostData(ref packetMessage);
                packetMessage.UpdateMessageSize();
                // Save updated message
                packetMessage.Save(SharedData.UnsentMessagesFolder.Path);

                _packetMessagesToSend.Add(packetMessage);
            }
            _logHelper.Log(LogLevel.Info, $"Send messages count: {_packetMessagesToSend.Count}");

            if (tncDevice.Name.Contains(PublicData.EMail) && _packetMessagesToSend.Count == 0)
            {
                return;
            }
            List <PacketMessage> messagesSentAsEMail = new List <PacketMessage>();

            // Send email messages
            foreach (PacketMessage packetMessage in _packetMessagesToSend)
            {
                //tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == packetMessage.TNCName).FirstOrDefault();
                //bbs = BBSDefinitions.Instance.BBSDataList.Where(bBS => bBS.Name == packetMessage.BBSName).FirstOrDefault();

                //TNCInterface tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                // Send as email if a TNC is not reachable, or if message is defined as an e-mail message
                if (tncDevice.Name.Contains(PublicData.EMail))
                {
                    try
                    {
                        // Mark message as sent by email
                        packetMessage.TNCName = tncDevice.Name;
                        //if (!tncDevice.Name.Contains(SharedData.EMail))
                        //{
                        //    packetMessage.TNCName = "E-Mail-" + PacketSettingsViewModel>.Instance.CurrentTNC.MailUserName;
                        //}

                        bool sendMailSuccess = await SendMessageViaEMailAsync(packetMessage);

                        if (sendMailSuccess)
                        {
                            packetMessage.MessageState = MessageState.Locked;
                            packetMessage.SentTime     = DateTime.Now;
                            packetMessage.MailUserName = SmtpClient.Instance.UserName;
                            _logHelper.Log(LogLevel.Info, $"Message sent via E-Mail: {packetMessage.MessageNumber}");

                            var file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMessage.FileName, CreationCollisionOption.OpenIfExists);

                            await file?.DeleteAsync();

                            // Do a save to ensure that updates are saved
                            packetMessage.Save(SharedData.SentMessagesFolder.Path);

                            //_packetMessagesToSend.Remove(packetMessage);
                            messagesSentAsEMail.Add(packetMessage);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logHelper.Log(LogLevel.Error, $"Error sending e-mail message {packetMessage.MessageNumber}");
                        string text = ex.Message;
                        continue;
                    }
                }
            }

            // Remove already processed E-Mail messages.
            foreach (PacketMessage packetMessage in messagesSentAsEMail)
            {
                _packetMessagesToSend.Remove(packetMessage);
            }

            // TODO check if TNC connected otherwise suggest send via email
            //if (_packetMessagesToSend.Count == 0)
            //{
            //    tncDevice = PacketSettingsViewModel>.Instance.CurrentTNC;

            //    (string bbsName, string tncName, string MessageFrom) = Utilities.GetProfileData();
            //    //string MessageFrom = from;
            //    BBSData MessageBBS = Singleton<PacketSettingsViewModel>.Instance.CurrentBBS;
            //    if (MessageBBS == null || !MessageBBS.Name.Contains("XSC") && !tncDevice.Name.Contains(SharedData.EMail))
            //    {
            //        //string bbsName = AddressBook.Instance.GetBBS(MessageFrom);
            //        bbs = BBSDefinitions.Instance.GetBBSFromName(bbsName);
            //    }
            //    else
            //    {
            //        bbs = Singleton<PacketSettingsViewModel>.Instance.CurrentBBS;
            //    }
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == tncName).FirstOrDefault();
            //}
            //else
            //{
            //    //tncDevice = Singleton<PacketSettingsViewModel>.Instance.CurrentTNC;
            //    tncDevice = TNCDeviceArray.Instance.TNCDeviceList.Where(tnc => tnc.Name == _packetMessagesToSend[0].TNCName).FirstOrDefault();
            //    bbs = BBSDefinitions.Instance.BBSDataList.Where(bBS => bBS.Name == _packetMessagesToSend[0].BBSName).FirstOrDefault();
            //    //Utilities.SetApplicationTitle(bbs.Name);
            //    //bbs = PacketSettingsViewModel>.Instance.CurrentBBS;
            //}

            //Utilities.SetApplicationTitle(bbs?.Name);

            if (!tncDevice.Name.Contains(PublicData.EMail))
            {
                ViewLifetimeControl viewLifetimeControl = await WindowManagerService.Current.TryShowAsStandaloneAsync("Connection Status", typeof(RxTxStatusPage));

                //RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.Height = RxTxStatusPage.rxtxStatusPage.RxTxStatusViewmodel.ViewControlHeight;
                //RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.Width = RxTxStatusPage.rxtxStatusPage.RxTxStatusViewmodel.ViewControlWidth;

                //bool success = RxTxStatusPage.rxtxStatusPage._viewLifetimeControl.ResizeView();


                //return;     //Test

                PacketSettingsViewModel packetSettingsViewModel = PacketSettingsViewModel.Instance;

                //_tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                _tncInterface = new TNCInterface(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaCommands, ref _packetMessagesToSend);

                // Collect remaining messages to be sent
                // Process files to be sent via BBS
                await _tncInterface.BBSConnectThreadProcAsync();

                // Close status window
                await RxTxStatusPage.Current._viewLifetimeControl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    //RxTxStatusPage.rxtxStatusPage.CloseStatusWindowAsync();
                    //RxTxStatusPage.Current.RxTxStatusViewmodel.CloseStatusWindowAsync();
                    RxTxStatViewModel.Instance.CloseStatusWindowAsync();
                });

                PacketSettingsViewModel.Instance.ForceReadBulletins = false;
                if (!string.IsNullOrEmpty(bbs?.Name))
                {
                    _logHelper.Log(LogLevel.Info, $"Disconnected from: {bbs?.ConnectName}. Connect time = {_tncInterface.BBSDisconnectTime - _tncInterface.BBSConnectTime}");
                }

                // Move sent messages from unsent folder to the Sent folder
                foreach (PacketMessage packetMsg in _tncInterface.PacketMessagesSent)
                {
                    try
                    {
                        _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} Sent");

                        StorageFile file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMsg.FileName, CreationCollisionOption.OpenIfExists);

                        await file.DeleteAsync();

                        // Do a save to ensure that updates from tncInterface.BBSConnect are saved
                        packetMsg.Save(SharedData.SentMessagesFolder.Path);
                    }
                    catch (FileNotFoundException)
                    {
                        _logHelper.Log(LogLevel.Error, $"File Not Found {packetMsg.FileName}");
                        continue;
                    }
                    catch (UnauthorizedAccessException)
                    {
                        _logHelper.Log(LogLevel.Error, $"Unauthorized Access {packetMsg.FileName}");
                        continue;
                    }
                    if (string.IsNullOrEmpty(packetMsg.Area) && SettingsViewModel.Instance.PrintSentMessages)
                    {
                        // Do printing if requested
                        _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} to be printed");

                        packetMsg.Save(SharedData.PrintMessagesFolder.Path);

                        SettingsViewModel settingsViewModel = SettingsViewModel.Instance;
                        PrintQueue.Instance.AddToPrintQueue(packetMsg.FileName, settingsViewModel.SentCopyNamesAsArray());
                    }
                }
                _packetMessagesReceived = _tncInterface.PacketMessagesReceived;
                await ProcessReceivedMessagesAsync();

                /*
                 * ApplicationTrigger trigger = new ApplicationTrigger();
                 * var task = RxTxBackgroundTask.RegisterBackgroundTask(RxTxBackgroundTask.RxTxBackgroundTaskEntryPoint,
                 *                                                     RxTxBackgroundTask.ApplicationTriggerTaskName,
                 *                                                     trigger,
                 *                                                     null);
                 * task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
                 * task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                 *
                 *
                 * // Register a ApplicationTriggerTask.
                 * RxTxBackgroundTask rxTxBackgroundTask = new RxTxBackgroundTask(bbs?.ConnectName, ref tncDevice, packetSettingsViewModel.ForceReadBulletins, packetSettingsViewModel.AreaString, ref _packetMessagesToSend);
                 *          rxTxBackgroundTask.Register();
                 * // Start backgroung task
                 * // Reset the completion status
                 * var settings = ApplicationData.Current.LocalSettings;
                 * settings.Values.Remove(BackgroundTaskSample.ApplicationTriggerTaskName);
                 *
                 * //Signal the ApplicationTrigger
                 * var result = await trigger.RequestAsync();
                 *
                 * ApplicationTriggerResult result = await rxTxBackgroundTask._applicationTrigger.RequestAsync();
                 * //            await Singleton<BackgroundTaskService>.Instance.HandleAsync(RxTxBackgroundTask);
                 * // RxTxBackgroundTask is finished
                 *
                 * if (_connectState == ConnectState.ConnectStateBBSConnect)
                 * {
                 *  await Utilities.ShowSingleButtonContentDialogAsync(_result, "Close", "BBS Connect Error");
                 *  //_result = "It appears that the radio is tuned to the wrong frequency,\nor the BBS was out of reach";
                 * }
                 *          else if (_connectState == ConnectState.ConnectStatePrepareTNCType)
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync("Unable to connect to the TNC.\nIs the TNC on?\nFor Kenwood; is the radio in \"packet12\" mode?", "Close", "BBS Connect Error");
                 *              //_result = "";
                 *          }
                 *          else if (_connectState == ConnectState.ConnectStateConverseMode)
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync($"Error sending FCC Identification - {Singleton<IdentityViewModel>.Instance.UserCallsign}.", "Close", "TNC Converse Error");
                 *              //_result = $"Error sending FCC Identification - { Singleton<IdentityViewModel>.Instance.UserCallsign}.";
                 *          }
                 *          //else if (e.Message.Contains("not exist"))
                 *          else if (e.GetType() == typeof(IOException))
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync("Looks like the USB or serial cable to the TNC is disconnected", "Close", "TNC Connect Error");
                 *              //_result = "Looks like the USB or serial cable to the TNC is disconnected";
                 *          }
                 *          else if (e.GetType() == typeof(UnauthorizedAccessException))
                 *          {
                 *              await Utilities.ShowSingleButtonContentDialogAsync($"The COM Port ({_TncDevice.CommPort.Comport}) is in use by another application. ", "Close", "TNC Connect Error");
                 *              //_result = $"The COM Port ({_TncDevice.CommPort.Comport}) is in use by another application.";
                 *          }
                 *
                 *          PacketSettingsViewModel>.Instance.ForceReadBulletins = false;
                 *          if (!string.IsNullOrEmpty(bbs?.Name))
                 *          {
                 *              _logHelper.Log(LogLevel.Info, $"Disconnected from: {bbs?.ConnectName}. Connect time = {rxTxBackgroundTask.BBSDisconnectTime - rxTxBackgroundTask.BBSConnectTime}");
                 *          }
                 *
                 *          // Move sent messages from unsent folder to the Sent folder
                 *          foreach (PacketMessage packetMsg in rxTxBackgroundTask.PacketMessagesSent)
                 *          {
                 *              try
                 *              {
                 *                  _logHelper.Log(LogLevel.Info, $"Message number {packetMsg.MessageNumber} Sent");
                 *
                 *                  StorageFile file = await SharedData.UnsentMessagesFolder.CreateFileAsync(packetMsg.FileName, CreationCollisionOption.OpenIfExists);
                 *                  await file.DeleteAsync();
                 *
                 *                  // Do a save to ensure that updates from tncInterface.BBSConnect are saved
                 *                  packetMsg.Save(SharedData.SentMessagesFolder.Path);
                 *              }
                 *              catch (Exception e)
                 *              {
                 *                  _logHelper.Log(LogLevel.Error, $"Exception {e.Message}");
                 *              }
                 *          }
                 *          _packetMessagesReceived = rxTxBackgroundTask.PacketMessagesReceived;
                 *          ProcessReceivedMessagesAsync();
                 *///_deviceFound = true;
                //try
                //{
                //    _serialPort = new SerialPort(Singleton<TNCSettingsViewModel>.Instance.CurrentTNCDevice.CommPort.Comport);
                //}
                //catch (IOException e)
                //{
                //    _deviceFound = false;
                //}
                //_serialPort.Close();
            }
        }
        /*
         *       Mail area: kz6dm
         *  1 message  -  1 new
         *
         *  St.  #  TO            FROM     DATE   SIZE SUBJECT
         *  > N   1 kz6dm         kz6dm    Sep 14  662 DELIVERED: 5DM-002_O/R_OAAlliedHeal
         *  (#1) >
         *  R 1
         *  Message #1
         *  Date: Fri, 14 Sep 2018 18:51:37 PDT
         *  From: [email protected]
         *  To: [email protected]
         *  Subject: DELIVERED: 5DM-002_O/R_OAAlliedHealth_Facility Type_Facility Name
         *
         *  !LMI!6DM-526P!DR!9/14/2018 6:51:22 PM
         *  Your Message
         *  To: KZ6DM
         *  Subject: 5DM-002_O/R_OAAlliedHealth_Facility Type_Facility Name
         *  was delivered on 9/14/2018 6:51:22 PM
         *  Recipient's Local Message ID: 6DM-526P
         *
         *  (#1) >
         *  K 1
         *  Msg 1 Killed.
         *
         *
         * Your message was delivered to:
         * [email protected] at 9/14/2018 6:51:22 PM
         * [email protected] assigned Msg ID: 6DM-526P
         */

        private async Task ProcessMessagesMarkedDeliveredAsync(PacketMessage pktMsg)
        {
            var formField = pktMsg.FormFieldArray.FirstOrDefault(x => x.ControlName == "messageBody");

            if (string.IsNullOrEmpty(formField.ControlContent))
            {
                formField = pktMsg.FormFieldArray.FirstOrDefault(x => x.ControlName == "richTextMessageBody");
            }
            if (formField.ControlContent.Contains("!LMI!"))
            {
                string[] searchStrings = new string[] { "Subject: ", "was delivered on ", "Recipient's Local Message ID: " };
                DateTime receiveTime = DateTime.Now;
                string   receiversMessageId = "", sendersMessageId = "", senderSubject = "";
                var      messageLines = formField.ControlContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string line in messageLines)
                {
                    if (line.Contains(searchStrings[0]))
                    {
                        senderSubject = line.Substring(searchStrings[0].Length);
                        int indexOfUnderscore = line.IndexOf('_');
                        int indexOfDelivered  = line.IndexOf(searchStrings[0]);
                        if (indexOfUnderscore >= 0)
                        {
                            sendersMessageId = line.Substring(indexOfDelivered + searchStrings[0].Length, indexOfUnderscore - (indexOfDelivered + searchStrings[0].Length));
                        }
                    }
                    else if (line.Contains(searchStrings[1]))
                    {
                        int indexOfDeliveryTime = line.IndexOf(searchStrings[1]);
                        if (indexOfDeliveryTime >= 0)
                        {
                            string s = line.Substring(indexOfDeliveryTime + searchStrings[1].Length);
                            receiveTime = DateTime.Parse(s);
                        }
                    }
                    else if (line.Contains(searchStrings[2]))
                    {
                        receiversMessageId = line.Substring(line.IndexOf(searchStrings[2]) + searchStrings[2].Length);
                    }
                }
                StringBuilder messageBody = new StringBuilder();
                messageBody.AppendLine("Your message was delivered to:");
                messageBody.AppendLine($"{pktMsg.MessageFrom} at {receiveTime}");
                messageBody.AppendLine($"{pktMsg.MessageFrom} assigned Msg ID: {receiversMessageId}");
                formField.ControlContent = messageBody.ToString();

                List <string> fileTypeFilter = new List <string>()
                {
                    ".xml"
                };
                QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

                // Get the files in the user's sent folder
                StorageFileQueryResult results = SharedData.SentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
                // Iterate over the results
                IReadOnlyList <StorageFile> files = await results.GetFilesAsync();

                foreach (StorageFile file in files)
                {
                    // Update sent form with receivers message number and receive time
                    if (file.Name.Contains(sendersMessageId))
                    {
                        PacketMessage packetMessage = PacketMessage.Open(file.Path);
                        if (packetMessage is null)
                        {
                            _logHelper.Log(LogLevel.Error, $"Failed to open {file.Path}");
                        }
                        else
                        {
                            if (packetMessage.MessageNumber == sendersMessageId && packetMessage.Subject == senderSubject)
                            {
                                formField = packetMessage.FormFieldArray.FirstOrDefault(x => x.ControlName == "receiverMsgNo");
                                if (formField != null)
                                {
                                    formField.ControlContent = receiversMessageId;
                                }
                                packetMessage.ReceiverMessageNumber = receiversMessageId;
                                packetMessage.ReceivedTime          = receiveTime;
                                packetMessage.Save(SharedData.SentMessagesFolder.Path);
                                break;
                            }
                        }
                    }
                }
            }
        }
Example #5
0
        public async void BBSConnectAsync()
        {
            FormControlBase formControl;

            //_listOfDevices = listOfDevices;

            ViewModels.SharedData sharedData = ViewModels.SharedData.SharedDataInstance;

            TNCDevice tncDevice = sharedData.CurrentTNCDevice;

            if (tncDevice != null)
            {
                // Try to connect to TNC
                _deviceFound = await TryOpenComportAsync();

                BBSData bbs = sharedData.CurrentBBS;
                if (bbs != null)
                {
                    // Do we use a bluetooth device?
                    if ((bool)sharedData.CurrentTNCDevice.CommPort?.IsBluetooth)
                    {
                        RfcommDeviceService service = null;
                        try
                        {
                            DeviceInformationCollection DeviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

                            foreach (var deviceInfo in DeviceInfoCollection)
                            {
                                if (deviceInfo.Id.Contains(sharedData.CurrentTNCDevice.CommPort.DeviceId))
                                {
                                    service = await RfcommDeviceService.FromIdAsync(deviceInfo.Id);

                                    _deviceFound = true;
                                    break;
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            LogHelper(LogLevel.Error, $"Error finding bluetooth device. { exp.Message }");
                        }
                        if (!_deviceFound)
                        {
                            await Utilities.ShowMessageDialogAsync($"TNC not found. Sending the message via e-mail");
                        }
                        else
                        {
                            if (_socket != null)
                            {
                                // Disposing the socket with close it and release all resources associated with the socket
                                _socket.Dispose();
                            }

                            _socket = new StreamSocket();
                            bool success = true;
                            try
                            {
                                // Note: If either parameter is null or empty, the call will throw an exception
                                await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
                            }
                            catch (Exception ex)
                            {
                                success = false;
                                LogHelper(LogLevel.Error, "Bluetootn Connect failed:" + ex.Message);
                            }
                            // If the connection was successful, the RemoteAddress field will be populated
                            try
                            {
                                if (success)
                                {
                                    //System.Diagnostics.Debug.WriteLine(msg);
                                    //await md.ShowAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper(LogLevel.Error, $"Overall Connect: { ex.Message}");
                                _socket.Dispose();
                                _socket = null;
                            }
                        }
                    }
                    // Collect messages to be sent
                    _packetMessagesToSend.Clear();
                    List <string> fileTypeFilter = new List <string>()
                    {
                        ".xml"
                    };
                    QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

                    // Get the files in the user's archive folder
                    StorageFileQueryResult results = MainPage._unsentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
                    // Iterate over the results
                    IReadOnlyList <StorageFile> files = await results.GetFilesAsync();

                    foreach (StorageFile file in files)
                    {
                        // Add Outpost message format by Filling the MessageBody field in packetMessage.
                        PacketMessage packetMessage = PacketMessage.Open(file);
                        if (packetMessage == null)
                        {
                            continue;
                        }

                        DateTime now = DateTime.Now;

                        var operatorDateField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorDate").FirstOrDefault();
                        if (operatorDateField != null)
                        {
                            operatorDateField.ControlContent = $"{now.Month:d2}/{now.Day:d2}/{now.Year:d2}";
                        }

                        var operatorTimeField = packetMessage.FormFieldArray.Where(formField => formField.ControlName == "operatorTime").FirstOrDefault();
                        if (operatorTimeField != null)
                        {
                            operatorTimeField.ControlContent = $"{now.Hour:d2}{now.Minute:d2}";
                        }

                        formControl = Views.FormsPage.CreateFormControlInstance(packetMessage.PacFormType);
                        if (formControl == null)
                        {
                            MessageDialog messageDialog = new MessageDialog($"Form {packetMessage.PacFormName} not found");
                            await messageDialog.ShowAsync();

                            continue;
                        }

                        packetMessage.MessageBody = formControl.CreateOutpostData(ref packetMessage);
                        packetMessage.MessageSize = packetMessage.Size;
                        // Save updated message
                        packetMessage.Save(MainPage._unsentMessagesFolder.Path);

                        _packetMessagesToSend.Add(packetMessage);
                    }
                    if (_packetMessagesToSend.Count == 0)
                    {
                        LogHelper(LogLevel.Info, $"No messages to send.");
                    }

                    TNCInterface tncInterface = new TNCInterface(bbs.ConnectName, ref tncDevice, ViewModels.SharedData._forceReadBulletins, ViewModels.SharedData._Areas, ref _packetMessagesToSend);

                    // Send as email if a TNC is not reachable, or if defined as e-mail message
                    if (!_deviceFound || tncDevice.Name == "E-Mail")
                    {
                        EmailMessage emailMessage;
                        try
                        {
                            foreach (PacketMessage packetMessage in _packetMessagesToSend)
                            {
                                // Mark message as sent by email
                                packetMessage.TNCName = "E-Mail";
                                emailMessage          = new EmailMessage();
                                // Create the to field.
                                var messageTo = packetMessage.MessageTo.Split(new char[] { ' ', ';' });
                                foreach (string address in messageTo)
                                {
                                    var index = address.IndexOf('@');
                                    if (index > 0)
                                    {
                                        index = address.ToLower().IndexOf("ampr.org");
                                        if (index < 0)
                                        {
                                            emailMessage.To.Add(new EmailRecipient(address + ".ampr.org"));
                                        }
                                        else
                                        {
                                            emailMessage.To.Add(new EmailRecipient(address));
                                        }
                                    }
                                    else
                                    {
                                        string to = $"{packetMessage.MessageTo}@{packetMessage.BBSName}.ampr.org";
                                        emailMessage.To.Add(new EmailRecipient(to));
                                    }
                                }
                                SmtpClient smtpClient = Services.SMTPClient.SmtpClient.Instance;
                                if (smtpClient.Server == "smtp-mail.outlook.com")
                                {
                                    if (!smtpClient.UserName.EndsWith("outlook.com") && !smtpClient.UserName.EndsWith("hotmail.com") && !smtpClient.UserName.EndsWith("live.com"))
                                    {
                                        throw new Exception("Mail from user must be a valid outlook.com address.");
                                    }
                                }
                                else if (smtpClient.Server == "smtp.gmail.com")
                                {
                                    if (!smtpClient.UserName.EndsWith("gmail.com"))
                                    {
                                        throw new Exception("Mail from user must be a valid gmail address.");
                                    }
                                }
                                else if (string.IsNullOrEmpty(smtpClient.Server))
                                {
                                    throw new Exception("Mail Server must be defined");
                                }

                                SmtpMessage message = new SmtpMessage(smtpClient.UserName, packetMessage.MessageTo, null, packetMessage.Subject, packetMessage.MessageBody);

                                // adding an other To receiver
                                //message.To.Add("*****@*****.**");

                                await smtpClient.SendMail(message);

//								emailMessage.Subject = packetMessage.Subject;
                                //// Insert \r\n
                                //string temp = packetMessage.MessageBody;
                                //string messageBody = temp.Replace("\r", "\r\n");
                                //var msgBody = temp.Split(new char[] { '\r' });
                                //messageBody = "";
                                //foreach (string s in msgBody)
                                //{
                                //	messageBody += (s + "\r\n");
                                //}
                                //emailMessage.Body = messageBody;
//								emailMessage.Body = packetMessage.MessageBody;

                                //IBuffer
                                //var memStream = new InMemoryRandomAccessStream();
                                //var randomAccessStreamReference = RandomAccessStreamReference.CreateFromStream(memStream);
                                //emailMessage.SetBodyStream(EmailMessageBodyKind.PlainText, randomAccessStreamReference);
                                //emailMessage.Body = await memStream.WriteAsync(packetMessage.MessageBody);

//								await EmailManager.ShowComposeNewEmailAsync(emailMessage);

                                DateTime dateTime = DateTime.Now;
                                packetMessage.SentTime        = dateTime;
                                packetMessage.SentTimeDisplay = $"{dateTime.Month:d2}/{dateTime.Day:d2}/{dateTime.Year - 2000:d2} {dateTime.Hour:d2}:{dateTime.Minute:d2}";
                                packetMessage.MailUserName    = smtpClient.UserName;
                                tncInterface.PacketMessagesSent.Add(packetMessage);

                                LogHelper(LogLevel.Info, $"Message sent via email {packetMessage.MessageNumber}");
                            }
                        }
                        catch (Exception ex)
                        {
                            string text = ex.Message;
                        }
                    }
                    else
                    {
                        //ref List<PacketMessage> packetMessagesReceived, ref List<PacketMessage> packetMessagesToSend, out DateTime bbsConnectTime, out DateTime bbsDisconnectTime
                        //string messageBBS, ref TNCDevice tncDevice, bool forceReadBulletins
                        LogHelper(LogLevel.Info, $"Connect to: {bbs.ConnectName}");

                        //tncInterface.BBSConnect(ref packetMessagesReceived, ref packetMessagesToSend);
                        //ConnectedDialog connectDlg = new ConnectedDialog();
                        //connectDlg.Owner = Window.GetWindow(this);
                        //tncInterface.ConnectDlg = connectDlg;

                        bool success = await tncInterface.BBSConnectThreadProcAsync();

                        EventHandlerForDevice.Current.CloseDevice();

                        if (!success)
                        {
                            return;
                        }

                        //var thread = new Thread(tncInterface.BBSConnectThreadProc);
                        //thread.SetApartmentState(ApartmentState.STA);
                        //connectDlg.ConnectThread = thread;
                        //connectDlg.ConnectError = tncInterface;
                        //thread.Start();

                        //// Blocks UI while connected to BBS
                        //connectDlg.ShowDialog();

                        ViewModels.SharedData._forceReadBulletins = false;
                        LogHelper(LogLevel.Info, $"Disconnected from: {bbs.ConnectName}. Connect time = {tncInterface.BBSDisconnectTime - tncInterface.BBSConnectTime}");
                    }
                    // Move sent messages from unsent folder to the Sent folder
                    foreach (PacketMessage packetMsg in tncInterface.PacketMessagesSent)
                    {
                        LogHelper(LogLevel.Info, $"Message number {packetMsg.MessageNumber} Sent");

                        var file = await MainPage._unsentMessagesFolder.CreateFileAsync(packetMsg.FileName, CreationCollisionOption.OpenIfExists);

                        await file.DeleteAsync();

                        // Do a save to ensure that updates from tncInterface.BBSConnect are saved
                        packetMsg.Save(Views.MainPage._sentMessagesFolder.Path);
                    }
                    _packetMessagesReceived = tncInterface.PacketMessagesReceived;
                    ProcessReceivedMessagesAsync();
                }
                else
                {
                    MessageDialog messageDialog = new MessageDialog($"Could not find the requested TNC ({ViewModels.SharedData.SharedDataInstance.CurrentProfile.TNC})");
                    await messageDialog.ShowAsync();

                    LogHelper(LogLevel.Error, $"Could not find the requested TNC ({ViewModels.SharedData.SharedDataInstance.CurrentProfile.TNC})");
                }
            }
            else
            {
                MessageDialog messageDialog = new MessageDialog($"Could not find the requested BBS ({ViewModels.SharedData.SharedDataInstance.CurrentProfile.BBS}). Check Packet Settings");
                await messageDialog.ShowAsync();

                LogHelper(LogLevel.Error, $"Could not find the requested BBS ({ViewModels.SharedData.SharedDataInstance.CurrentProfile.BBS}). Check Packet Settings");
            }
        }
Example #6
0
        public async void ProcessReceivedMessagesAsync()
        {
            if (_packetMessagesReceived.Count() > 0)
            {
                foreach (PacketMessage packetMessageOutpost in _packetMessagesReceived)
                {
                    FormControlBase formControl = new MessageControl();
                    // test for packet form!!
                    PacketMessage pktMsg = new PacketMessage()
                    {
                        //pktMsg.PacFormType = PacForms.Message;
                        PacFormName = "SimpleMessage",
                        BBSName     = packetMessageOutpost.BBSName,
                        TNCName     = packetMessageOutpost.TNCName,
                        MessageSize = packetMessageOutpost.MessageSize,
                        Area        = packetMessageOutpost.Area,
                        // Save the original message for post processing (tab characters are lost in the displayed message)
                        MessageBody = packetMessageOutpost.MessageBody,
                        //MessageReadOnly = true
                    };
                    string[] msgLines = packetMessageOutpost.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);

                    bool subjectFound = false;
                    for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
                    {
                        if (msgLines[i].StartsWith("Date:"))
                        {
                            pktMsg.JNOSDate        = DateTime.Parse(msgLines[i].Substring(10, 21));
                            pktMsg.JNOSDateDisplay = $"{pktMsg.JNOSDate.Month:d2}/{pktMsg.JNOSDate.Date:d2}/{pktMsg.JNOSDate.Year - 2000:d2} {pktMsg.JNOSDate.Hour:d2}:{pktMsg.JNOSDate.Minute:d2}";
                        }
                        else if (msgLines[i].StartsWith("From:"))
                        {
                            pktMsg.MessageFrom = msgLines[i].Substring(6);
                        }
                        else if (msgLines[i].StartsWith("To:"))
                        {
                            pktMsg.MessageTo = msgLines[i].Substring(4);
                        }
                        else if (msgLines[i].StartsWith("Cc:"))
                        {
                            pktMsg.MessageTo += (", " + msgLines[i].Substring(4));
                            while (msgLines[i + 1].Length == 0)
                            {
                                i++;
                            }
                            if (msgLines[i + 1][0] == ' ')
                            {
                                pktMsg.MessageTo += msgLines[i + 1].TrimStart(new char[] { ' ' });
                            }
                        }
                        else if (!subjectFound && msgLines[i].StartsWith("Subject:"))
                        {
                            pktMsg.Subject = msgLines[i].Substring(9);
                            //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                            subjectFound = true;
                        }
                        else if (msgLines[i].StartsWith("# FORMFILENAME:"))
                        {
                            string html     = ".html";
                            string formName = msgLines[i].Substring(16).TrimEnd(new char[] { ' ' });
                            formName           = formName.Substring(0, formName.Length - html.Length);
                            pktMsg.PacFormType = formName;

                            //formControl = Views.FormsPage.CreateFormControlInstanceFromFileName(pktMsg.PacFormName);
                            formControl = Views.FormsPage.CreateFormControlInstance(pktMsg.PacFormType);
                            if (formControl == null)
                            {
                                await Utilities.ShowMessageDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            break;
                        }
                    }

                    //pktMsg.MessageNumber = GetMessageNumberPacket();		// Filled in BBS connection
                    pktMsg.PacFormType    = formControl.PacFormType;
                    pktMsg.MessageNumber  = packetMessageOutpost.MessageNumber;
                    pktMsg.FormFieldArray = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines);
                    pktMsg.ReceivedTime   = packetMessageOutpost.ReceivedTime;
                    if (pktMsg.ReceivedTime != null)
                    {
                        DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                        pktMsg.ReceivedTimeDisplay = $"{dateTime.Month:d2}/{dateTime.Date:d2}/{dateTime.Year - 2000:d2} {dateTime.Hour:d2}:{dateTime.Minute:d2}";
                    }
                    if (pktMsg.ReceivedTime != null)
                    {
                        DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                        pktMsg.ReceivedTimeDisplay = $"{dateTime.Month:d2}/{dateTime.Date:d2}/{dateTime.Year - 2000:d2} {dateTime.Hour:d2}:{dateTime.Minute:d2}";
                    }
                    pktMsg.CreateFileName();
                    string fileFolder = Views.MainPage._receivedMessagesFolder.Path;
                    pktMsg.Save(fileFolder);

                    //log.Info($"Message number {pktMsg.MessageNumber} received");
                    LogHelper(LogLevel.Info, $"Message number {pktMsg.MessageNumber} received");

                    // If the received message is a delivery confirmation, update receivers message number in the original sent message
                    if (!string.IsNullOrEmpty(pktMsg.Subject) && pktMsg.Subject.Contains("DELIVERED:"))
                    {
                        var formField = pktMsg.FormFieldArray.FirstOrDefault(x => x.ControlName == "messageBody");
                        if (formField.ControlContent.Contains("!LMI!"))
                        {
                            string[] searchStrings = new string[] { "Subject: ", "was delivered on ", "Recipient's Local Message ID: " };
                            DateTime receiveTime = DateTime.Now;
                            string   receiversMessageId = "", sendersMessageId = "";
                            var      messageLines = formField.ControlContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string line in messageLines)
                            {
                                if (line.Contains(searchStrings[0]))
                                {
                                    int indexOfUnderscore = line.IndexOf('_');
                                    int indexOfDelivered  = line.IndexOf(searchStrings[0]);
                                    if (indexOfUnderscore >= 0)
                                    {
                                        sendersMessageId = line.Substring(indexOfDelivered + searchStrings[0].Length, indexOfUnderscore - (indexOfDelivered + searchStrings[0].Length));
                                    }
                                }
                                else if (line.Contains(searchStrings[1]))
                                {
                                    int indexOfDeliveryTime = line.IndexOf(searchStrings[1]);
                                    if (indexOfDeliveryTime >= 0)
                                    {
                                        string s = line.Substring(indexOfDeliveryTime + searchStrings[1].Length);
                                        receiveTime = DateTime.Parse(s);
                                    }
                                }
                                else if (line.Contains(searchStrings[2]))
                                {
                                    receiversMessageId = line.Substring(line.IndexOf(searchStrings[2]) + searchStrings[2].Length);
                                }
                            }

                            //DirectoryInfo diSentFolder = new DirectoryInfo(Views.MainPage._sentMessagesFolder.Path);
                            //foreach (FileInfo fi in diSentFolder.GetFiles())
                            List <string> fileTypeFilter = new List <string>()
                            {
                                ".xml"
                            };
                            //fileTypeFilter.Add(".xml");
                            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);

                            // Get the files in the user's archive folder
                            StorageFileQueryResult results = MainPage._sentMessagesFolder.CreateFileQueryWithOptions(queryOptions);
                            // Iterate over the results
                            IReadOnlyList <StorageFile> files = await results.GetFilesAsync();

                            foreach (StorageFile file in files)
                            {
                                // Update sent form with receivers message number and receive time
                                if (file.Name.Contains(sendersMessageId))
                                {
                                    PacketMessage packetMessage = PacketMessage.Open(file);
                                    if (packetMessage.MessageNumber == sendersMessageId)
                                    {
                                        formField = packetMessage.FormFieldArray.FirstOrDefault(x => x.ControlName == "receiverMsgNo");
                                        if (formField != null)
                                        {
                                            formField.ControlContent = receiversMessageId;
                                        }
                                        packetMessage.ReceivedTime = receiveTime;
                                        if (receiveTime != null)
                                        {
                                            packetMessage.ReceivedTimeDisplay = $"{receiveTime.Month:d2}/{receiveTime.Date:d2}/{receiveTime.Year - 2000:d2} {receiveTime.Hour:d2}:{receiveTime.Minute:d2}";
                                        }
                                        packetMessage.Save(MainPage._sentMessagesFolder.Path);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                //RefreshDataGrid();      // Display newly added messages
            }
        }