예제 #1
0
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            SharedData sharedData = SharedData.SharedDataInstance;

            if (args.Kind == ActivationKind.Launch)
            {
                BackgroundTransfer backgroundTransfer = BackgroundTransfer.CreateBackgroundTransfer();
                await backgroundTransfer.DiscoverActiveDownloadsAsync();
            }

            //long-running startup tasks go here
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            Views.MainPage._unsentMessagesFolder = await localFolder.CreateFolderAsync("UnsentMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage._sentMessagesFolder = await localFolder.CreateFolderAsync("SentMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage._receivedMessagesFolder = await localFolder.CreateFolderAsync("ReceivedMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage._draftMessagesFolder = await localFolder.CreateFolderAsync("DraftMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage._archivedMessagesFolder = await localFolder.CreateFolderAsync("ArchivedMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage._deletedMessagesFolder = await localFolder.CreateFolderAsync("DeletedMessages", CreationCollisionOption.OpenIfExists);

            Views.MainPage.LogsFolder = await localFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);

            Views.MainPage._MetroLogsFolder = await localFolder.CreateFolderAsync("MetroLogs", CreationCollisionOption.OpenIfExists);

            SharedData.filesInInstalledLocation = await Package.Current.InstalledLocation.GetFilesAsync();

            sharedData.BbsArray = await BBSDefinitions.OpenAsync(localFolder);              //"ms-appx:///Assets/pdffile.pdf"

            sharedData.TncDeviceArray = await TNCDeviceArray.OpenAsync(localFolder);

            sharedData.ProfileArray = await ProfileArray.OpenAsync(localFolder);

            foreach (var tacticalCallsignType in _tacticalCallsignDataDictionary.Values)
            {
                tacticalCallsignType.TacticalCallsigns = await TacticalCallsigns.OpenAsync(tacticalCallsignType.FileName);
            }
            await AddressBook.Instance.OpenAsync();

            await DistributionListArray.Instance.OpenAsync();

            await ListViewParametersArray.Instance.OpenAsync();

            NavigationService.Navigate(typeof(Views.MainPage));
            await Task.CompletedTask;
        }
        public async Task ProcessReceivedMessagesAsync()
        {
            if (_packetMessagesReceived.Count() > 0)
            {
                bool updateBulletinList = false;
                foreach (PacketMessage packetMessageOutpost in _packetMessagesReceived)
                {
                    FormControlBase formControl = new MessageControl();
                    // test for packet form!!
                    PacketMessage pktMsg = new PacketMessage()
                    {
                        BBSName       = packetMessageOutpost.BBSName,
                        TNCName       = packetMessageOutpost.TNCName,
                        MessageSize   = packetMessageOutpost.MessageSize,
                        MessageNumber = packetMessageOutpost.MessageNumber,
                        ReceivedTime  = packetMessageOutpost.ReceivedTime,
                        CreateTime    = DateTime.Now,
                        Area          = packetMessageOutpost.Area,
                        // Save the original message for post processing (tab characters are lost in the displayed message)
                        MessageBody   = packetMessageOutpost.MessageBody,
                        MessageState  = MessageState.Locked,
                        MessageOpened = false,
                        MessageOrigin = MessageOriginHelper.MessageOrigin.Received,
                    };
                    string[] msgLines = packetMessageOutpost.MessageBody.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.None);
                    // Check if base64 encoded
                    int  startOfMessage  = 0;
                    int  startOfMessage1 = 0;
                    int  startOfMessage2 = 0;
                    int  endOfMessage    = 0;
                    bool dateFound       = false;
                    bool subjectFound    = false;
                    for (int k = 0; k < msgLines.Length; k++)
                    {
                        if (msgLines[k].StartsWith("Date:"))
                        {
                            dateFound       = true;
                            startOfMessage1 = k + 1;
                        }
                        if (msgLines[k].StartsWith("Subject:"))
                        {
                            subjectFound    = true;
                            startOfMessage2 = k + 1;
                        }
                        if (dateFound && subjectFound)
                        {
                            break;
                        }
                    }
                    startOfMessage = Math.Max(startOfMessage1, startOfMessage2);
                    endOfMessage   = msgLines.Length - 1;
                    try
                    {
                        // Process encoded message
                        string message = "";
                        for (int j = startOfMessage; j <= endOfMessage; j++)
                        {
                            message += msgLines[j];
                        }
                        const string outpostEncodedMarker = "!B64!";
                        if (message.StartsWith(outpostEncodedMarker))
                        {
                            message = message.Substring(outpostEncodedMarker.Length);
                        }
                        byte[] messageText   = Convert.FromBase64String(message);
                        string decodedString = Encoding.UTF8.GetString(messageText);

                        List <string> msgLinesList = msgLines.ToList();
                        msgLinesList.RemoveRange(startOfMessage, endOfMessage - startOfMessage + 1);
                        string[] decodedMsgLines = decodedString.Split(new string[] { "\r\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
                        msgLinesList.InsertRange(startOfMessage, decodedMsgLines);
                        msgLines = msgLinesList.ToArray();
                        _logHelper.Log(LogLevel.Info, "This message was an encoded message");
                    }
                    catch (FormatException)
                    {
                        // Not an encoded message
                        //_logHelper.Log(LogLevel.Info, "Not an encoded message");
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        _logHelper.Log(LogLevel.Error, "Argument out of range");
                    }
                    bool toFound = false;
                    subjectFound = false;
                    string prefix = "";
                    for (int i = 0; i < Math.Min(msgLines.Length, 20); i++)
                    {
                        if (msgLines[i].StartsWith("From:"))
                        {
                            pktMsg.MessageFrom = NormalizeEmailField(msgLines[i].Substring(6));
                        }
                        else if (!toFound && msgLines[i].StartsWith("To:"))
                        {
                            pktMsg.MessageTo = NormalizeEmailField(msgLines[i].Substring(4));
                            toFound          = true;
                        }
                        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);
                            if (pktMsg.Subject[3] == '-')
                            {
                                prefix = pktMsg.Subject.Substring(0, 3);
                            }
                            //pktMsg.MessageSubject = pktMsg.MessageSubject.Replace('\t', ' ');
                            subjectFound = true;
                        }
                        else if (msgLines[i].StartsWith("Date:"))
                        {
                            pktMsg.JNOSDate = DateTime.Parse(msgLines[i].Substring(10, 21));
                        }

                        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.PacFormName = formName;

                            formControl = FormsViewModel.CreateFormControlInstance(pktMsg.PacFormName);
                            if (formControl is null)
                            {
                                _logHelper.Log(LogLevel.Error, $"Form {pktMsg.PacFormName} not found");
                                await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            pktMsg.SenderMessageNumber = FormControlBase.GetOutpostValue(msgLines[i + 1]);
                            pktMsg.FormProvider        = FormProviders.PacForm; // TODO update with real provider
                            //pktMsg.FormProvider = formControl.FormProvider;    // TODO update with real provider
                            break;
                        }
                        else if (msgLines[i].StartsWith("#T:"))
                        {
                            string[] fileNameString = msgLines[i].Split(new char[] { ' ', '.' }, StringSplitOptions.RemoveEmptyEntries);
                            string   formName       = fileNameString[1];
                            formName.Trim();
                            pktMsg.PacFormName = formName;

                            formControl = FormsViewModel.CreateFormControlInstance(pktMsg.PacFormName);
                            if (formControl is null)
                            {
                                _logHelper.Log(LogLevel.Error, $"Form {pktMsg.PacFormName} not found");
                                await ContentDialogs.ShowSingleButtonContentDialogAsync($"Form {pktMsg.PacFormName} not found");

                                return;
                            }
                            pktMsg.SenderMessageNumber = FormControlBase.GetOutpostValue(msgLines[i + 2]);
                            pktMsg.FormProvider        = FormProviders.PacItForm;
                            break;
                        }
                    }

                    //pktMsg.MessageNumber = GetMessageNumberPacket();		// Filled in BBS connection
                    pktMsg.PacFormType = formControl.PacFormType;
                    //pktMsg.PacFormName = formControl.GetPacFormName();
                    pktMsg.PacFormName     = formControl.FormControlName;
                    pktMsg.FormControlType = formControl.FormControlType;
                    pktMsg.FormFieldArray  = formControl.ConvertFromOutpost(pktMsg.MessageNumber, ref msgLines, pktMsg.FormProvider);
                    //if (pktMsg.ReceivedTime != null)
                    //{
                    //	DateTime dateTime = (DateTime)pktMsg.ReceivedTime;
                    //}
                    if (!pktMsg.CreateFileName())
                    {
                        _logHelper.Log(LogLevel.Error, $"Error in Create FileName(), {pktMsg.MessageNumber}, {pktMsg.PacFormType}");
                        throw new Exception();
                    }

                    AddressBook.Instance.UpdateLastUsedBBS(pktMsg.MessageFrom, prefix);
                    _logHelper.Log(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:"))
                    {
                        await ProcessMessagesMarkedDeliveredAsync(pktMsg);
                    }
                    pktMsg.Save(SharedData.ReceivedMessagesFolder.Path);

                    if (!string.IsNullOrEmpty(pktMsg.Area))
                    {
                        updateBulletinList |= true;     // Does this work with xscevent

                        if (pktMsg.Area.ToLower() == "xscperm")
                        {
                            if (pktMsg.Subject.ToLower().Contains("scco packet frequencies"))
                            {
                                await BBSDefinitions.CreateFromBulletinAsync(pktMsg);
                            }
                            else if (pktMsg.Subject.ToLower().Contains("scco packet tactical calls"))
                            {
                                await TacticalCallsigns.CreatePacketTacticalCallsignsFromBulletinAsync(pktMsg);
                            }
                        }
                    }

                    // Do printing if requested
                    if (!string.IsNullOrEmpty(pktMsg.Subject) && !pktMsg.Subject.Contains("DELIVERED:") &&
                        string.IsNullOrEmpty(pktMsg.Area) && SettingsViewModel.Instance.PrintReceivedMessages)
                    {
                        _logHelper.Log(LogLevel.Info, $"Message number {pktMsg.MessageNumber} to be printed");

                        pktMsg.Save(SharedData.PrintMessagesFolder.Path);

                        SettingsViewModel settingsViewModel = SettingsViewModel.Instance;

                        PrintQueue.Instance.AddToPrintQueue(pktMsg.FileName, settingsViewModel.ReceivedCopyNamesAsArray());

                        // Test
                        await PrintQueue.Instance.PrintToDestinationsAsync();

                        //await Singleton<PrintQueue>.Instance.BackgroundPrintingTrigger.RequestAsync();
                    }
                }
                //RefreshDataGrid();      // Display newly added messages
                if (updateBulletinList)
                {
                    await MainViewModel.Instance.UpdateDownloadedBulletinsAsync();
                }
            }
        }