コード例 #1
0
        public void TestArgumentExceptions()
        {
            var      uids = new UniqueIdRange(UniqueId.MinValue, UniqueId.MinValue);
            UniqueId uid;

            Assert.Throws <ArgumentNullException> (() => uids.CopyTo(null, 0));
            Assert.Throws <ArgumentOutOfRangeException> (() => uids.CopyTo(new UniqueId[1], -1));
            Assert.Throws <ArgumentOutOfRangeException> (() => uid = uids[-1]);
            Assert.Throws <ArgumentNullException> (() => UniqueIdRange.TryParse(null, 0, out uids));
        }
コード例 #2
0
		public void TestArgumentExceptions ()
		{
			var uids = new UniqueIdRange (UniqueId.MinValue, UniqueId.MinValue);
			UniqueId uid;

			Assert.Throws<ArgumentNullException> (() => uids.CopyTo (null, 0));
			Assert.Throws<ArgumentOutOfRangeException> (() => uids.CopyTo (new UniqueId[1], -1));
			Assert.Throws<ArgumentOutOfRangeException> (() => uid = uids[-1]);
			Assert.Throws<ArgumentNullException> (() => UniqueIdRange.TryParse (null, 0, out uids));
		}
コード例 #3
0
        public void TestNotSupported()
        {
            var range = new UniqueIdRange(UniqueId.MinValue, UniqueId.MaxValue);

            Assert.Throws <NotSupportedException> (() => range[5] = new UniqueId(5), "set");
            Assert.Throws <NotSupportedException> (() => range.Insert(0, new UniqueId(5)), "Insert");
            Assert.Throws <NotSupportedException> (() => range.Remove(new UniqueId(5)), "Remove");
            Assert.Throws <NotSupportedException> (() => range.RemoveAt(1), "RemoveAt");
            Assert.Throws <NotSupportedException> (() => range.Add(new UniqueId(5)), "Add");
            Assert.Throws <NotSupportedException> (() => range.Clear(), "Clear");
        }
コード例 #4
0
        public void TestMessagesVanishedEventArgs()
        {
            var uids = new UniqueIdRange(0, 5, 7);
            MessagesVanishedEventArgs args;

            args = new MessagesVanishedEventArgs(uids, true);

            Assert.AreEqual(uids, args.UniqueIds);
            Assert.IsTrue(args.Earlier);

            Assert.Throws <ArgumentNullException> (() => new MessagesVanishedEventArgs(null, false));
        }
コード例 #5
0
ファイル: Mail.cs プロジェクト: Bitz/OwO_Bot
        private static string CheckMail(long postId, IMailFolder inbox, UniqueIdRange range,
                                        BinarySearchQuery query)
        {
            string result = string.Empty;

            foreach (UniqueId uid in inbox.Search(range, query))
            {
                var message = inbox.GetMessage(uid);
                result = message.TextBody.Split('\r', '\n').FirstOrDefault();

                if (!string.IsNullOrEmpty(result))
                {
                    inbox.AddFlags(uid, MessageFlags.Seen, true);
                }

                if (result != null && result.ToLower().ToLower() == "cancel")
                {
                    C.WriteLine("We won't be proceeding with this post...");
                    DbBlackList dbBlackList = new DbBlackList();
                    Blacklist   item        = new Blacklist
                    {
                        Subreddit   = WorkingSub,
                        PostId      = postId,
                        CreatedDate = DateTime.Now
                    };
                    dbBlackList.AddToBlacklist(item);
                    Environment.Exit(0);
                }
                else if (result != null && result.ToLower().ToLower() == "next")
                {
                    C.WriteLine("We won't be proceeding with this post...");
                    DbBlackList dbBlackList = new DbBlackList();
                    Blacklist   item        = new Blacklist
                    {
                        Subreddit   = WorkingSub,
                        PostId      = postId,
                        CreatedDate = DateTime.Now
                    };

                    dbBlackList.AddToBlacklist(item);
                    Process.Start(Assembly.GetExecutingAssembly().Location, Args.FirstOrDefault());
                    Environment.Exit(0);
                }
                else
                {
                    C.WriteLineNoTime("We got a title!");
                }
                break;
            }

            return(result);
        }
コード例 #6
0
        public void TestParser()
        {
            UniqueIdRange range;

            Assert.IsFalse(UniqueIdRange.TryParse("xyz", out range));
            Assert.IsFalse(UniqueIdRange.TryParse("1:xyz", out range));
            Assert.IsFalse(UniqueIdRange.TryParse("1:*1", out range));
            Assert.IsFalse(UniqueIdRange.TryParse("1:1x", out range));

            Assert.IsTrue(UniqueIdRange.TryParse("1:*", out range));
            Assert.AreEqual(UniqueId.MinValue, range.Min);
            Assert.AreEqual(UniqueId.MaxValue, range.Max);
        }
コード例 #7
0
        public void TestAscending()
        {
            const string  example = "1:20";
            var           copy    = new UniqueId[20];
            UniqueIdRange uids;

            Assert.IsTrue(UniqueIdRange.TryParse(example, 20160117, out uids), "Failed to parse uids.");
            Assert.AreEqual(20160117, uids.Validity, "Validity");
            Assert.IsTrue(uids.IsReadOnly, "IsReadOnly");
            Assert.AreEqual(1, uids.Start.Id, "Start");
            Assert.AreEqual(20, uids.End.Id, "End");
            Assert.AreEqual(1, uids.Min.Id, "Min");
            Assert.AreEqual(20, uids.Max.Id, "Max");
            Assert.AreEqual(example, uids.ToString(), "ToString");
            Assert.AreEqual(20, uids.Count);

            Assert.False(uids.Contains(new UniqueId(500)));
            Assert.AreEqual(-1, uids.IndexOf(new UniqueId(500)));

            for (int i = 0; i < uids.Count; i++)
            {
                Assert.AreEqual(i, uids.IndexOf(uids[i]));
                Assert.AreEqual(20160117, uids[i].Validity);
                Assert.AreEqual(i + 1, uids[i].Id);
            }

            uids.CopyTo(copy, 0);

            for (int i = 0; i < copy.Length; i++)
            {
                Assert.AreEqual(20160117, copy[i].Validity);
                Assert.AreEqual(i + 1, copy[i].Id);
            }

            var list = new List <UniqueId> ();

            foreach (var uid in uids)
            {
                Assert.AreEqual(20160117, uid.Validity);
                list.Add(uid);
            }

            for (int i = 0; i < list.Count; i++)
            {
                Assert.AreEqual(i + 1, list[i].Id);
            }
        }
コード例 #8
0
        private void CopyMessages(IMailFolder folder, IMailFolder dest)
        {
            try
            {
                folder.Open(FolderAccess.ReadOnly);

                dest.Open(FolderAccess.ReadWrite);

                UniqueIdRange r = new UniqueIdRange(UniqueId.MinValue, UniqueId.MaxValue);

                var headers = new HashSet <HeaderId>();

                headers.Add(HeaderId.Received);
                headers.Add(HeaderId.Date);
                headers.Add(HeaderId.MessageId);
                headers.Add(HeaderId.Subject);
                headers.Add(HeaderId.From);
                headers.Add(HeaderId.To);
                headers.Add(HeaderId.Cc);
                headers.Add(HeaderId.ResentMessageId);


                var msgList = folder.Fetch(r,
                                           MessageSummaryItems.UniqueId
                                           | MessageSummaryItems.InternalDate
                                           | MessageSummaryItems.Flags, headers);

                int total = msgList.Count;
                int i     = 1;

                foreach (var msg in msgList)
                {
                    Console.WriteLine($"Copying {i++} of {total}");
                    CopyMessage(msg, folder, dest);
                    if (i % 100 == 0)
                    {
                        dest.Check();
                    }
                }
            }
            finally
            {
                folder.Close();
                dest.Close();
            }
        }
コード例 #9
0
        async Task FetchNewEmailsAsync(CancellationToken ct)
        {
            uint lastUid;

            if (await context.Email.CountAsync() == 0)
            {
                lastUid = 0;
            }
            else
            {
                lastUid = await context.Email.MaxAsync(e => e.EmailUID);
            }
            var uids = new UniqueIdRange(new UniqueId(lastUid + 1), UniqueId.MaxValue);

            foreach (var message in await client.Inbox.FetchAsync(uids, summaryItems, ct))
            {
                await ProcessNewEmailAsync(message, ct);
            }
        }
コード例 #10
0
		public void TestNotSupported ()
		{
			var range = new UniqueIdRange (UniqueId.MinValue, UniqueId.MaxValue);

			Assert.Throws<NotSupportedException> (() => range[5] = new UniqueId (5), "set");
			Assert.Throws<NotSupportedException> (() => range.Insert (0, new UniqueId (5)), "Insert");
			Assert.Throws<NotSupportedException> (() => range.Remove (new UniqueId (5)), "Remove");
			Assert.Throws<NotSupportedException> (() => range.RemoveAt (1), "RemoveAt");
			Assert.Throws<NotSupportedException> (() => range.Add (new UniqueId (5)), "Add");
			Assert.Throws<NotSupportedException> (() => range.Clear (), "Clear");
		}
コード例 #11
0
        public async Task GetDocFromStore(DateTime period)
        {
            // INFO
            PgModel.StopWatch.Start();

            using (ImapClient client = new ImapClient())
            {
                Cancellation = new CancellationTokenSource();
                int c = 0;
                try
                {
                    await client.ConnectAsync("outlook.office365.com", 993, true);
                    await ReportProgress(0, $"Authenticating on mail server... Please wait.");

                    await client.AuthenticateAsync(Properties.Settings.Default.User365, Properties.Settings.Default.Password365);

                    IList <IMailFolder> folders = await client.GetFoldersAsync(client.PersonalNamespaces[0]);

                    foreach (IMailFolder f in folders)
                    {
                        if (f == folders[1] || f == folders[8] || f == folders[13])
                        {
                            await f.OpenAsync(FolderAccess.ReadOnly);

                            UniqueIdRange     range = new UniqueIdRange(new UniqueId(Convert.ToUInt32(Properties.Settings.Default.UIDRange)), UniqueId.MaxValue);
                            BinarySearchQuery query = SearchQuery.DeliveredAfter(Properties.Settings.Default.DateTimeEmail).And(SearchQuery.ToContains(Properties.Settings.Default.User365));
                            IList <UniqueId>  listM = await f.SearchAsync(range, query, Cancellation.Token);

                            int total = listM.Count;
                            foreach (UniqueId uid in await f.SearchAsync(range, query, Cancellation.Token))
                            {
                                MimeMessage message = await f.GetMessageAsync(uid, Cancellation.Token);

                                if (message.Attachments != null)
                                {
                                    IEnumerable <MimeEntity> attachments = GetXmlAttachments(message.BodyParts);
                                    foreach (MimeEntity item in attachments)
                                    {
                                        using (MemoryStream memory = new MemoryStream())
                                        {
                                            if (item is MessagePart rfc822)
                                            {
                                                await rfc822.Message.WriteToAsync(memory, Cancellation.Token);
                                            }
                                            else
                                            {
                                                MimePart part = (MimePart)item;
                                                await part.Content.DecodeToAsync(memory, Cancellation.Token);
                                            }
                                            memory.Position = 0;
                                            XDocument xDocument = null;
                                            try
                                            {
                                                xDocument = XDocument.Load(memory);
                                            }
                                            catch (XmlException)
                                            {
                                                //throw;
                                            }

                                            if (xDocument != null && xDocument.Root.Name.LocalName == "EnvioDTE")
                                            {
                                                int res = SaveFiles(xDocument);
                                                if (res == 0)
                                                {
                                                    // ok
                                                }
                                                else if (res == 1)
                                                {
                                                    //MessageBox.Show("Error", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                    // ERROR SII.
                                                }
                                            }
                                        }
                                    }
                                }
                                if (f == folders[1])
                                {
                                    Properties.Settings.Default.DateTimeEmail = message.Date.DateTime;
                                    Properties.Settings.Default.UIDRange      = uid.ToString();
                                    c++;
                                    float porcent = (float)(100 * c) / total;
                                    PgModel.FchOutlook = Properties.Settings.Default.DateTimeEmail;
                                    SaveParam();
                                    await ReportProgress(porcent, $"Dowloading messages... [{string.Format(CultureInfo.InvariantCulture, "{0:d-MM-yyyy HH:mm}", message.Date.DateTime)}] ({c}/{total})  Subject: {message.Subject} ");
                                }
                            }
                        }
                    }
                }
                catch (Exception) when(Cancellation.Token.IsCancellationRequested)
                {
                    throw new TaskCanceledException();
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    await client.DisconnectAsync(true);
                }
            }
        }
コード例 #12
0
ファイル: Mail.cs プロジェクト: Bitz/OwO_Bot
        public string Recieve(string search, long postId)
        {
            string result = string.Empty;

            while (string.IsNullOrEmpty(result))
            {
                using (var client = new ImapClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect(Config.mail.incoming_server, Config.mail.incoming_port, true);

                    // Note: since we don't have an OAuth2 token, disable
                    client.Authenticate(Config.mail.username, Config.mail.password);
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // The Inbox folder is always available on all IMAP servers...
                    IMailFolder inbox = client.Inbox;

                    inbox.Open(FolderAccess.ReadWrite);

                    UniqueId nextUid = new UniqueId();
                    if (inbox.UidNext != null)
                    {
                        nextUid = inbox.UidNext.Value;
                    }
                    else
                    {
                        C.WriteLine("Could not connect to email.");
                        Environment.Exit(0);
                    }

                    var range = new UniqueIdRange(nextUid, UniqueId.MaxValue);
                    var query = SearchQuery.NotSeen
                                .And(SearchQuery.SubjectContains(postId.ToString()))
                                .And(SearchQuery.FromContains(EmailRecipient.address.ToLower()));

                    using (CancellationTokenSource done = new CancellationTokenSource())
                    {
                        Thread thread = new Thread(IdleLoop);

                        client.Inbox.CountChanged += (sender, e) =>
                        {
                            C.WriteLineNoTime("You got mail!");
                            done.Cancel();
                        };
                        //1 Hour and 30 mins.
                        var timer = new SysTimer.Timer {
                            Interval = 5400000
                        };
                        timer.Elapsed += (sender, e) =>
                        {
                            C.WriteLine("Time passed with no reply...");
                            Send(search, "Request Cancelled");
                            C.WriteLine("We won't be proceeding with this post...");
                            Environment.Exit(0);
                            done.Cancel();
                        };
                        timer.Start();
                        thread.Start(new IdleState(client, done.Token));
                        thread.Join();
                        result = CheckMail(postId, inbox, range, query);
                    }
                    client.Disconnect(true);
                }
            }
            return(result);
        }