示例#1
0
 public LoggerEventArgs(Int64 time, String tag, MessageFlags flag, String message)
 {
     this.TimeStamp = time;
     this.Tag = tag;
     this.Message = message;
     this.Flags = flag;
 }
 public LogMessageAttributes(Stream stream)
 {
     Classification = (MessageClass)stream.ReadByte();
     Level = (MessageLevel)stream.ReadByte();
     MessageSuppression = (MessageSuppression)stream.ReadByte();
     Flags = (MessageFlags)stream.ReadByte();
 }
 public LogMessageAttributes(MessageClass classification, MessageLevel level, MessageSuppression messageSuppression, MessageFlags flags)
 {
     Classification = classification;
     Level = level;
     MessageSuppression = messageSuppression;
     Flags = flags;
 }
示例#4
0
        /// <summary>
        /// Formats a flags list suitable for use with the APPEND command.
        /// </summary>
        /// <returns>The flags list string.</returns>
        /// <param name="flags">The message flags.</param>
        /// <param name="numUserFlags">The number of user-defined flags.</param>
        public static string FormatFlagsList(MessageFlags flags, int numUserFlags)
        {
            var builder = new StringBuilder ();

            builder.Append ('(');

            if ((flags & MessageFlags.Answered) != 0)
                builder.Append ("\\Answered ");
            if ((flags & MessageFlags.Deleted) != 0)
                builder.Append ("\\Deleted ");
            if ((flags & MessageFlags.Draft) != 0)
                builder.Append ("\\Draft ");
            if ((flags & MessageFlags.Flagged) != 0)
                builder.Append ("\\Flagged ");
            if ((flags & MessageFlags.Seen) != 0)
                builder.Append ("\\Seen ");

            for (int i = 0; i < numUserFlags; i++)
                builder.Append ("%S ");

            if (builder.Length > 1)
                builder.Length--;

            builder.Append (')');

            return builder.ToString ();
        }
示例#5
0
		public MessageInfo (IMessageSummary summary)
		{
			Summary = summary;

			if (summary.Flags.HasValue)
				Flags = summary.Flags.Value;
		}
        /// <summary>
        /// Sends a message to a specific tile to the connected Band device with the provided tile ID, title, body, 
        /// timestamp and with message flags to control how the message is provided.
        /// </summary>
        /// <param name="tileId">The tile identifier.</param>
        /// <param name="title">The message title.</param>
        /// <param name="body">The message body.</param>
        /// <param name="timestamp">The message timestamp.</param>
        /// <param name="messageFlags">The message flags to control how the message is provided to the Band device.</param>
        public async Task SendMessageAsync(Guid tileId, string title, string body, DateTime timestamp, MessageFlags messageFlags)
        {
#if __ANDROID__ || __IOS__
            await Native.SendMessageTaskAsync(tileId.ToNative(), title, body, timestamp, messageFlags.ToNative());
#elif WINDOWS_PHONE_APP
            await Native.SendMessageAsync(tileId.ToNative(), title, body, timestamp, messageFlags.ToNative());
#endif
        }
示例#7
0
 public Message(RemotingPeer peer, RemotingManager remotingManager, Serializer serializer)
 {
     Serializer = serializer;
     Peer = peer;
     RemotingManager = remotingManager;
     Header = new DataHeader(Serializer);
     Flags = MessageFlags.None;
 }
示例#8
0
 /// <summary>
 /// Sends a log message to all attached loggers
 /// </summary>
 /// <param name="tag">Tag associated with the message</param>
 /// <param name="format">Format string of the message</param>
 /// <param name="args">Message format arguments</param>
 public static void SendLogMessage(String tag, MessageFlags flags, String format, params Object[] args)
 {
     if (_onLogMessage != null)
     {
         LoggerEventArgs e = new LoggerEventArgs(tag, flags, format, args);
         _onLogMessage(null, e);
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.MessageFlagsChangedEventArgs"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MessageFlagsChangedEventArgs"/>.
		/// </remarks>
		/// <param name="index">The message index.</param>
		/// <param name="flags">The message flags.</param>
		/// <param name="userFlags">The user-defined message flags.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="userFlags"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		public MessageFlagsChangedEventArgs (int index, MessageFlags flags, HashSet<string> userFlags) : base (index)
		{
			if (userFlags == null)
				throw new ArgumentNullException (nameof (userFlags));

			UserFlags = userFlags;
			Flags = flags;
		}
示例#10
0
 public Message(RemotingPeer peer, RemotingManager remotingManager, int localId, int remoteId, MessageType type, MessageFlags flags = MessageFlags.None)
     : this(peer, remotingManager)
 {
     Flags = flags;
     Header.CallType = type;
     Header.RemoteId = remoteId;
     Header.LocalId = localId;
     Header.Write();
 }
示例#11
0
 private static PacketFlags ConvertFlags(MessageFlags flags)
 {
     switch (flags)
     {
         case MessageFlags.None:
             return 0;
         case MessageFlags.Encrypted:
             return PacketFlags.Encrypted;
         case MessageFlags.Signed:
             return PacketFlags.Signed;
         case MessageFlags.Compressed:
             return PacketFlags.Compressed;
         default:
             throw new NotImplementedException();
     }
 }
示例#12
0
        protected string FormatBody(object o)
        {
            DataRowView row = (DataRowView)o;
            string html = FormatMsg.FormatMessage(this,row["Message"].ToString(),new MessageFlags(Convert.ToInt32(row["Flags"])));

            if(row["user_Signature"].ToString().Length>0)
            {
                string sig = row["user_signature"].ToString();

                // don't allow any HTML on signatures
                MessageFlags tFlags = new MessageFlags();
                tFlags.IsHTML = false;

                sig = FormatMsg.FormatMessage(this,sig,tFlags);
                html += "<br/><hr noshade/>" + sig;
            }

            return html;
        }
        public async Task SendMessageAsync(Guid tileId, string title, string body, DateTimeOffset timestamp, MessageFlags flags, CancellationToken token)
        {
            if (tileId == Guid.Empty)
            {
                throw new ArgumentException(BandResource.NotificationInvalidTileId, "tileId");
            }
            if (string.IsNullOrWhiteSpace(title) && string.IsNullOrWhiteSpace(body))
            {
                throw new ArgumentException(BandResource.NotificationFieldsEmpty);
            }

            await Task.Delay(500);

            var appId = _appIdProvider.GetAppId();
            TileData installedTile = _tiles.GetTile(appId, tileId);

            if (installedTile == null || installedTile.OwnerId != appId)
                throw new Exception("Ownership or Tile invalid");

            return;
        }
示例#14
0
		/// <summary>
		/// Asynchronously set the flags of the specified message.
		/// </summary>
		/// <remarks>
		/// Asynchronously sets the flags of the specified message.
		/// </remarks>
		/// <returns>An asynchronous task context.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="userFlags">A set of user-defined flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public Task SetFlagsAsync (UniqueId uid, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			return SetFlagsAsync (new [] { uid }, flags, userFlags, silent, cancellationToken);
		}
示例#15
0
 /// <inheritdoc />
 /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
 /// <exception cref="ArgumentException">The only valid <see cref="MessageFlags"/> are <see cref="MessageFlags.SuppressEmbeds"/> and <see cref="MessageFlags.None"/>.</exception>
 public virtual Task <RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false,
                                                     Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null,
                                                     MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null,
                                                     Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
 => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions,
                                messageReference, components, stickers, options, isSpoiler, embeds, flags);
示例#16
0
 /// <inheritdoc />
 /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
 /// <exception cref="ArgumentException">The only valid <see cref="MessageFlags"/> are <see cref="MessageFlags.SuppressEmbeds"/> and <see cref="MessageFlags.None"/>.</exception>
 public Task <RestUserMessage> SendMessageAsync(string text                 = null, bool isTTS = false, Embed embed = null,
                                                RequestOptions options      = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null,
                                                MessageComponent components = null, ISticker[] stickers             = null, Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
 => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference,
                                   components, stickers, options, embeds, flags);
        /// <summary>
        /// Send Private Message
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            var replyTo = this.Get <HttpRequestBase>().QueryString.Exists("p")
                              ? this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").ToType <int>()
                              : -1;

            // Check if quoted message is Reply
            if (this.Get <HttpRequestBase>().QueryString.Exists("p"))
            {
                var replyId = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").ToType <int>();
                var reply   = this.GetRepository <PMessage>().GetSingle(
                    m => m.ID == replyId);

                if (reply.ReplyTo.HasValue)
                {
                    replyTo = reply.ReplyTo.Value;
                }
            }

            // recipient was set in dropdown
            if (this.ToList.Visible)
            {
                this.To.Text = this.ToList.SelectedItem.Text;
            }

            if (this.To.Text.Length <= 0)
            {
                // recipient is required field
                this.PageContext.AddLoadMessage(this.GetText("need_to"), MessageTypes.warning);
                return;
            }

            // subject is required
            if (this.PmSubjectTextBox.Text.Trim().Length <= 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("need_subject"), MessageTypes.warning);
                return;
            }

            // message is required
            if (this.editor.Text.Trim().Length <= 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("need_message"), MessageTypes.warning);
                return;
            }

            if (this.ToList.SelectedItem != null && this.ToList.SelectedItem.Value == "0")
            {
                // administrator is sending PMs to all users
                var body         = this.editor.Text;
                var messageFlags = new MessageFlags
                {
                    IsHtml   = this.editor.UsesHTML,
                    IsBBCode = this.editor.UsesBBCode
                };

                // test user's PM count
                if (!this.VerifyMessageAllowed(1, body))
                {
                    return;
                }

                this.GetRepository <PMessage>().SendMessage(
                    this.PageContext.PageUserID,
                    0,
                    this.PmSubjectTextBox.Text,
                    body,
                    messageFlags.BitValue,
                    replyTo);

                // redirect to outbox (sent items), not control panel
                BuildLink.Redirect(ForumPages.MyMessages, "v={0}", "out");
            }
            else
            {
                // remove all abundant whitespaces and separators
                var rx = new Regex(@";(\s|;)*;");
                this.To.Text = rx.Replace(this.To.Text, ";");

                if (this.To.Text.StartsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(1);
                }

                if (this.To.Text.EndsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(0, this.To.Text.Length - 1);
                }

                rx           = new Regex(@"\s*;\s*");
                this.To.Text = rx.Replace(this.To.Text, ";");

                // list of recipients
                var recipients = new List <string>(this.To.Text.Trim().Split(';'));

                if (recipients.Count > this.Get <BoardSettings>().PrivateMessageMaxRecipients &&
                    !this.PageContext.IsAdmin && this.Get <BoardSettings>().PrivateMessageMaxRecipients != 0)
                {
                    // to many recipients
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted(
                            "TOO_MANY_RECIPIENTS",
                            this.Get <BoardSettings>().PrivateMessageMaxRecipients),
                        MessageTypes.warning);

                    return;
                }

                if (!this.VerifyMessageAllowed(recipients.Count, this.editor.Text))
                {
                    return;
                }

                // list of recipient's ids
                var recipientIds = new List <int>();

                // get recipients' IDs
                foreach (var recipient in recipients)
                {
                    var user = this.Get <IUserDisplayName>().FindUserByName(recipient);

                    if (user == null)
                    {
                        this.PageContext.AddLoadMessage(
                            this.GetTextFormatted("NO_SUCH_USER", recipient),
                            MessageTypes.warning);
                        return;
                    }

                    if (user.IsGuest.Value)
                    {
                        this.PageContext.AddLoadMessage(this.GetText("NOT_GUEST"), MessageTypes.danger);
                        return;
                    }

                    // get recipient's ID from the database
                    if (!recipientIds.Contains(user.ID))
                    {
                        recipientIds.Add(user.ID);
                    }

                    var receivingPMInfo = this.GetRepository <PMessage>().UserMessageCount(user.ID).Rows[0];

                    // test receiving user's PM count
                    if (receivingPMInfo["NumberTotal"].ToType <int>() + 1
                        < receivingPMInfo["NumberAllowed"].ToType <int>() || this.PageContext.IsAdmin ||
                        (bool)
                        Convert.ChangeType(
                            this.PageContext.GetRepository <User>().ListAsDataTable(this.PageContext.PageBoardID, user.ID, true).GetFirstRow()["IsAdmin"],
                            typeof(bool)))
                    {
                        continue;
                    }

                    // recipient has full PM box
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient),
                        MessageTypes.danger);
                    return;
                }

                // send PM to all recipients
                recipientIds.ForEach(
                    userId =>

                {
                    var body = this.editor.Text;

                    var messageFlags = new MessageFlags
                    {
                        IsHtml   = this.editor.UsesHTML,
                        IsBBCode = this.editor.UsesBBCode
                    };

                    this.GetRepository <PMessage>().SendMessage(
                        this.PageContext.PageUserID,
                        userId,
                        this.PmSubjectTextBox.Text,
                        body,
                        messageFlags.BitValue,
                        replyTo);

                    // reset lazy data as he should be informed at once
                    this.Get <IDataCache>().Remove(string.Format(Constants.Cache.ActiveUserLazyData, userId));

                    if (this.Get <BoardSettings>().AllowPMEmailNotification)
                    {
                        this.Get <ISendNotification>().ToPrivateMessageRecipient(
                            userId,
                            this.PmSubjectTextBox.Text.Trim());
                    }
                });

                // redirect to outbox (sent items), not control panel
                BuildLink.Redirect(ForumPages.MyMessages, "v={0}", "out");
            }
        }
示例#18
0
        /// <summary>
        /// The post reply handle new post.
        /// </summary>
        /// <param name="topicId">
        /// The topic Id.
        /// </param>
        /// <returns>
        /// Returns the Message Id.
        /// </returns>
        protected long PostReplyHandleNewPost(out long topicId)
        {
            long messageId = 0;

            if (!this.PageContext.ForumPostAccess)
            {
                BuildLink.AccessDenied();
            }

            // Check if Forum is Moderated
            var isForumModerated = false;

            var forumInfo = this.GetRepository <Forum>()
                            .List(this.PageContext.PageBoardID, this.PageContext.PageForumID).FirstOrDefault();

            if (forumInfo != null)
            {
                isForumModerated = this.CheckForumModerateStatus(forumInfo, true);
            }

            // If Forum is Moderated
            if (isForumModerated)
            {
                this.spamApproved = false;
            }

            // Bypass Approval if Admin or Moderator
            if (this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess)
            {
                this.spamApproved = true;
            }

            // make message flags
            var messageFlags = new MessageFlags
            {
                IsHtml       = this.forumEditor.UsesHTML,
                IsBBCode     = this.forumEditor.UsesBBCode,
                IsPersistent = this.PostOptions1.PersistentChecked,
                IsApproved   = this.spamApproved
            };

            // Save to Db
            topicId = this.GetRepository <Topic>().Save(
                this.PageContext.PageForumID,
                this.TopicSubjectTextBox.Text.Trim(),
                string.Empty,
                this.TopicStylesTextBox.Text.Trim(),
                this.TopicDescriptionTextBox.Text.Trim(),
                this.forumEditor.Text,
                this.PageContext.PageUserID,
                this.Priority.SelectedValue.ToType <int>(),
                this.User != null ? null : this.From.Text,
                this.Get <HttpRequestBase>().GetUserRealIPAddress(),
                DateTime.UtcNow,
                string.Empty,
                messageFlags.BitValue,
                this.Tags.Text,
                ref messageId);

            this.UpdateWatchTopic(this.PageContext.PageUserID, (int)topicId);

            // clear caches as stats changed
            if (!messageFlags.IsApproved)
            {
                return(messageId);
            }

            this.Get <IDataCache>().Remove(Constants.Cache.BoardStats);
            this.Get <IDataCache>().Remove(Constants.Cache.BoardUserStats);

            return(messageId);
        }
示例#19
0
		internal void UpdatePermanentFlags (MessageFlags flags)
		{
			PermanentFlags = flags;
		}
示例#20
0
		/// <summary>
		/// Sets the flags of the specified messages.
		/// </summary>
		/// <remarks>
		/// Sets the flags of the specified messages.
		/// </remarks>
		/// <param name="indexes">The indexes of the messages.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="userFlags">A set of user-defined flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MailFolder.MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="indexes"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override void SetFlags (IList<int> indexes, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			ModifyFlags (indexes, null, flags, userFlags, silent ? "FLAGS.SILENT" : "FLAGS", cancellationToken);
		}
示例#21
0
		ImapCommand QueueAppend (FormatOptions options, MimeMessage message, MessageFlags flags, DateTimeOffset? date, CancellationToken cancellationToken, ITransferProgress progress)
		{
			string format = "APPEND %F";

			if ((flags & SettableFlags) != 0)
				format += " " + ImapUtils.FormatFlagsList (flags, 0);

			if (date.HasValue)
				format += " \"" + ImapUtils.FormatInternalDate (date.Value) + "\"";

			format += " %L\r\n";

			var ic = new ImapCommand (Engine, cancellationToken, null, options, format, this, message);
			ic.Progress = progress;

			Engine.QueueCommand (ic);

			return ic;
		}
示例#22
0
 bool HasFlag(MessageFlags f)
 {
     return((flags & f) == f);
 }
 /// <summary>
 /// Sets the specified <see cref="MessageFlags"/> on the header.
 /// </summary>
 /// <param name="header">The message header.</param>
 /// <param name="messageFlag">The ETP message flag to set.</param>
 private static void SetFlag(this IMessageHeader header, MessageFlags messageFlag)
 {
     header.MessageFlags |= (int)messageFlag;
 }
 /// <summary>
 /// Checks if the header has the specified <see cref="MessageFlags"/> set.
 /// </summary>
 /// <param name="header">The message header.</param>
 /// <param name="messageFlag">The ETP message flag.</param>
 /// <returns><c>true</c> if the header has the specified flag set; <c>false</c> otherwise.</returns>
 private static bool HasFlag(this IMessageHeader header, MessageFlags messageFlag)
 {
     return(((MessageFlags)header.MessageFlags).HasFlag(messageFlag));
 }
示例#25
0
		/// <summary>
		/// Removes a set of flags from the specified messages.
		/// </summary>
		/// <remarks>
		/// Removes a set of flags from the specified messages.
		/// </remarks>
		/// <param name="uids">The UIDs of the messages.</param>
		/// <param name="flags">The message flags to remove.</param>
		/// <param name="userFlags">A set of user-defined flags to remove.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MailFolder.MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>No flags were specified.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override void RemoveFlags (IList<UniqueId> uids, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			if ((flags & SettableFlags) == 0 && (userFlags == null || userFlags.Count == 0))
				throw new ArgumentException ("No flags were specified.", "flags");

			ModifyFlags (uids, null, flags, userFlags, silent ? "-FLAGS.SILENT" : "-FLAGS", cancellationToken);
		}
示例#26
0
		/// <summary>
		/// Set the flags of the specified messages.
		/// </summary>
		/// <remarks>
		/// Sets the flags of the specified messages.
		/// </remarks>
		/// <param name="uids">The UIDs of the messages.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual void SetFlags (IList<UniqueId> uids, MessageFlags flags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			SetFlags (uids, flags, null, silent, cancellationToken);
		}
示例#27
0
		/// <summary>
		/// Sets the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </summary>
		/// <remarks>
		/// Sets the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </remarks>
		/// <returns>The indexes of the messages that were not updated.</returns>
		/// <param name="indexes">The indexes of the messages.</param>
		/// <param name="modseq">The mod-sequence value.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="userFlags">A set of user-defined flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MailFolder.MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="indexes"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <see cref="ImapFolder"/> does not support mod-sequences.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override IList<int> SetFlags (IList<int> indexes, ulong modseq, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			return ModifyFlags (indexes, modseq, flags, userFlags, silent ? "FLAGS.SILENT" : "FLAGS", cancellationToken);
		}
示例#28
0
		/// <summary>
		/// Set the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </summary>
		/// <remarks>
		/// Sets the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </remarks>
		/// <returns>The unique IDs of the messages that were not updated.</returns>
		/// <param name="uids">The UIDs of the messages.</param>
		/// <param name="modseq">The mod-sequence value.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <see cref="MailFolder"/> does not support mod-sequences.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual IList<UniqueId> SetFlags (IList<UniqueId> uids, ulong modseq, MessageFlags flags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			return SetFlags (uids, modseq, flags, null, silent, cancellationToken);
		}
 IAsyncAction IBandNotificationManager.SendMessageAsync(Guid tileId, string title, string body, DateTimeOffset timestamp, MessageFlags flags)
 {
     return(AsyncInfo.Run(cancellationToken => this.bandClient.NotificationManager.SendMessageAsync(tileId, title, body, timestamp, ToMessageFlags(flags), cancellationToken)));
 }
示例#30
0
		/// <summary>
		/// Asynchronously set the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </summary>
		/// <remarks>
		/// Asynchronously sets the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </remarks>
		/// <returns>The unique IDs of the messages that were not updated.</returns>
		/// <param name="uids">The UIDs of the messages.</param>
		/// <param name="modseq">The mod-sequence value.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <see cref="MailFolder"/> does not support mod-sequences.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task<IList<UniqueId>> SetFlagsAsync (IList<UniqueId> uids, ulong modseq, MessageFlags flags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (uids == null)
				throw new ArgumentNullException ("uids");

			if (uids.Count == 0)
				throw new ArgumentException ("No uids were specified.", "uids");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					return SetFlags (uids, modseq, flags, silent, cancellationToken);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
示例#31
0
 /// <inheritdoc cref="IForumChannel.CreatePostWithFilesAsync(string, IEnumerable{FileAttachment}, ThreadArchiveDuration, int?, string, Embed, RequestOptions, AllowedMentions, MessageComponent, ISticker[], Embed[], MessageFlags)"/>
 public Task <RestThreadChannel> CreatePostWithFilesAsync(string title, IEnumerable <FileAttachment> attachments, ThreadArchiveDuration archiveDuration = ThreadArchiveDuration.OneDay,
                                                          int?slowmode = null, string text = null, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null,
                                                          MessageComponent components = null, ISticker[] stickers = null, Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
 => ThreadHelper.CreatePostAsync(this, Discord, title, attachments, archiveDuration, slowmode, text, embed, options, allowedMentions, components, stickers, embeds, flags);
示例#32
0
		/// <summary>
		/// Set the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </summary>
		/// <remarks>
		/// Sets the flags of the specified messages only if their mod-sequence value is less than the specified value.
		/// </remarks>
		/// <returns>The unique IDs of the messages that were not updated.</returns>
		/// <param name="uids">The UIDs of the messages.</param>
		/// <param name="modseq">The mod-sequence value.</param>
		/// <param name="flags">The message flags to set.</param>
		/// <param name="userFlags">A set of user-defined flags to set.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="uids"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <see cref="MailFolder"/> does not support mod-sequences.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public abstract IList<UniqueId> SetFlags (IList<UniqueId> uids, ulong modseq, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken));
示例#33
0
        /// <summary>
        /// Send Private Message
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            var replyTo = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").IsSet()
                              ? this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("p").ToType <int>()
                              : -1;

            // recipient was set in dropdown
            if (this.ToList.Visible)
            {
                this.To.Text = this.ToList.SelectedItem.Text;
            }

            if (this.To.Text.Length <= 0)
            {
                // recipient is required field
                YafContext.Current.AddLoadMessage(this.GetText("need_to"), MessageTypes.Warning);
                return;
            }

            // subject is required
            if (this.PmSubjectTextBox.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(this.GetText("need_subject"), MessageTypes.Warning);
                return;
            }

            // message is required
            if (this._editor.Text.Trim().Length <= 0)
            {
                YafContext.Current.AddLoadMessage(this.GetText("need_message"), MessageTypes.Warning);
                return;
            }

            if (this.ToList.SelectedItem != null && this.ToList.SelectedItem.Value == "0")
            {
                // administrator is sending PMs tp all users
                string body         = this._editor.Text;
                var    messageFlags = new MessageFlags
                {
                    IsHtml   = this._editor.UsesHTML,
                    IsBBCode = this._editor.UsesBBCode
                };

                // test user's PM count
                if (!this.VerifyMessageAllowed(1))
                {
                    return;
                }

                var receivingPMInfo = LegacyDb.user_pmcount(replyTo).Rows[0];

                // test receiving user's PM count
                if (!YafContext.Current.IsAdmin ||
                    !(bool)
                    Convert.ChangeType(UserMembershipHelper.GetUserRowForID(replyTo, true)["IsAdmin"], typeof(bool)))
                {
                    if (receivingPMInfo["NumberTotal"].ToType <int>() + 1
                        <= receivingPMInfo["NumberAllowed"].ToType <int>())
                    {
                        return;
                    }

                    // recipient has full PM box
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", this.To.Text),
                        MessageTypes.Error);
                    return;
                }

                LegacyDb.pmessage_save(
                    YafContext.Current.PageUserID,
                    0,
                    this.PmSubjectTextBox.Text,
                    body,
                    messageFlags.BitValue,
                    replyTo);

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
            else
            {
                // remove all abundant whitespaces and separators
                var rx = new Regex(@";(\s|;)*;");
                this.To.Text = rx.Replace(this.To.Text, ";");

                if (this.To.Text.StartsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(1);
                }

                if (this.To.Text.EndsWith(";"))
                {
                    this.To.Text = this.To.Text.Substring(0, this.To.Text.Length - 1);
                }

                rx           = new Regex(@"\s*;\s*");
                this.To.Text = rx.Replace(this.To.Text, ";");

                // list of recipients
                var recipients = new List <string>(this.To.Text.Trim().Split(';'));

                if (recipients.Count > this.Get <YafBoardSettings>().PrivateMessageMaxRecipients &&
                    !YafContext.Current.IsAdmin && this.Get <YafBoardSettings>().PrivateMessageMaxRecipients != 0)
                {
                    // to many recipients
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted(
                            "TOO_MANY_RECIPIENTS",
                            this.Get <YafBoardSettings>().PrivateMessageMaxRecipients),
                        MessageTypes.Warning);

                    return;
                }

                if (!this.VerifyMessageAllowed(recipients.Count))
                {
                    return;
                }

                // list of recipient's ids
                var recipientIds = new List <int>();

                // get recipients' IDs
                foreach (string recipient in recipients)
                {
                    int?userId = this.Get <IUserDisplayName>().GetId(recipient);

                    if (!userId.HasValue)
                    {
                        YafContext.Current.AddLoadMessage(
                            this.GetTextFormatted("NO_SUCH_USER", recipient),
                            MessageTypes.Warning);
                        return;
                    }

                    if (UserMembershipHelper.IsGuestUser(userId.Value))
                    {
                        YafContext.Current.AddLoadMessage(this.GetText("NOT_GUEST"), MessageTypes.Error);
                        return;
                    }

                    // get recipient's ID from the database
                    if (!recipientIds.Contains(userId.Value))
                    {
                        recipientIds.Add(userId.Value);
                    }

                    var receivingPMInfo = LegacyDb.user_pmcount(userId.Value).Rows[0];

                    // test receiving user's PM count
                    if ((receivingPMInfo["NumberTotal"].ToType <int>() + 1
                         < receivingPMInfo["NumberAllowed"].ToType <int>()) || YafContext.Current.IsAdmin ||
                        (bool)
                        Convert.ChangeType(
                            UserMembershipHelper.GetUserRowForID(userId.Value, true)["IsAdmin"],
                            typeof(bool)))
                    {
                        continue;
                    }

                    // recipient has full PM box
                    YafContext.Current.AddLoadMessage(
                        this.GetTextFormatted("RECIPIENTS_PMBOX_FULL", recipient),
                        MessageTypes.Error);
                    return;
                }

                // send PM to all recipients
                foreach (var userId in recipientIds)
                {
                    string body = this._editor.Text;

                    var messageFlags = new MessageFlags
                    {
                        IsHtml   = this._editor.UsesHTML,
                        IsBBCode = this._editor.UsesBBCode
                    };

                    LegacyDb.pmessage_save(
                        YafContext.Current.PageUserID,
                        userId,
                        this.PmSubjectTextBox.Text,
                        body,
                        messageFlags.BitValue,
                        replyTo);

                    // reset reciever's lazy data as he should be informed at once
                    this.Get <IDataCache>().Remove(Constants.Cache.ActiveUserLazyData.FormatWith(userId));

                    if (this.Get <YafBoardSettings>().AllowPMEmailNotification)
                    {
                        this.Get <ISendNotification>()
                        .ToPrivateMessageRecipient(userId, this.PmSubjectTextBox.Text.Trim());
                    }
                }

                // redirect to outbox (sent items), not control panel
                YafBuildLink.Redirect(ForumPages.cp_pm, "v={0}", "out");
            }
        }
示例#34
0
 /// <inheritdoc />
 async Task <IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options,
                                                            AllowedMentions allowedMentions, MessageReference messageReference, MessageComponent components,
                                                            ISticker[] stickers, Embed[] embeds, MessageFlags flags)
 => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags).ConfigureAwait(false);
示例#35
0
        /// <summary>
        /// The quick reply_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void QuickReply_Click([NotNull] object sender, [NotNull] EventArgs e)
        {
            if (!this.PageContext.ForumReplyAccess || (this._topicFlags.IsLocked && !this.PageContext.ForumModeratorAccess))
            {
                YafBuildLink.AccessDenied();
            }

            if (this._quickReplyEditor.Text.Length <= 0)
            {
                this.PageContext.AddLoadMessage(this.GetText("EMPTY_MESSAGE"));
                return;
            }

            if (((this.PageContext.IsGuest && this.PageContext.BoardSettings.EnableCaptchaForGuests) ||
                 (this.PageContext.BoardSettings.EnableCaptchaForPost && !this.PageContext.IsCaptchaExcluded)) &&
                !CaptchaHelper.IsValid(this.tbCaptcha.Text.Trim()))
            {
                this.PageContext.AddLoadMessage(this.GetText("BAD_CAPTCHA"));
                return;
            }

            if (!(this.PageContext.IsAdmin || this.PageContext.IsModerator) &&
                this.PageContext.BoardSettings.PostFloodDelay > 0)
            {
                if (YafContext.Current.Get <YafSession>().LastPost > DateTime.UtcNow.AddSeconds(-this.PageContext.BoardSettings.PostFloodDelay))
                {
                    this.PageContext.AddLoadMessage(
                        this.GetTextFormatted(
                            "wait",
                            (YafContext.Current.Get <YafSession>().LastPost - DateTime.UtcNow.AddSeconds(-this.PageContext.BoardSettings.PostFloodDelay)).Seconds));
                    return;
                }
            }

            YafContext.Current.Get <YafSession>().LastPost = DateTime.UtcNow;

            // post message...
            long   nMessageId = 0;
            object replyTo    = -1;
            string msg        = this._quickReplyEditor.Text;
            long   topicID    = this.PageContext.PageTopicID;

            var tFlags = new MessageFlags
            {
                IsHtml     = this._quickReplyEditor.UsesHTML,
                IsBBCode   = this._quickReplyEditor.UsesBBCode,
                IsApproved = this.PageContext.IsAdmin || this.PageContext.IsModerator
            };

            // Bypass Approval if Admin or Moderator.
            if (
                !DB.message_save(
                    topicID,
                    this.PageContext.PageUserID,
                    msg,
                    null,
                    this.Request.UserHostAddress,
                    null,
                    replyTo,
                    tFlags.BitValue,
                    ref nMessageId))
            {
                topicID = 0;
            }

            // Check to see if the user has enabled "auto watch topic" option in his/her profile.
            if (this.PageContext.CurrentUserData.AutoWatchTopics)
            {
                using (DataTable dt = DB.watchtopic_check(this.PageContext.PageUserID, this.PageContext.PageTopicID))
                {
                    if (dt.Rows.Count == 0)
                    {
                        // subscribe to this forum
                        DB.watchtopic_add(this.PageContext.PageUserID, this.PageContext.PageTopicID);
                    }
                }
            }

            bool bApproved = false;

            using (DataTable dt = DB.message_list(nMessageId))
            {
                foreach (DataRow row in dt.Rows)
                {
                    bApproved = ((int)row["Flags"] & 16) == 16;
                }
            }

            if (bApproved)
            {
                // send new post notification to users watching this topic/forum
                this.Get <YafSendNotification>().ToWatchingUsers(nMessageId.ToType <int>());

                // redirect to newly posted message
                YafBuildLink.Redirect(ForumPages.posts, "m={0}&#post{0}", nMessageId);
            }
            else
            {
                if (this.PageContext.BoardSettings.EmailModeratorsOnModeratedPost)
                {
                    // not approved, notifiy moderators
                    this.Get <YafSendNotification>().ToModeratorsThatMessageNeedsApproval(
                        this.PageContext.PageForumID, (int)nMessageId);
                }

                string url = YafBuildLink.GetLink(ForumPages.topics, "f={0}", this.PageContext.PageForumID);
                if (Config.IsRainbow)
                {
                    YafBuildLink.Redirect(ForumPages.info, "i=1");
                }
                else
                {
                    YafBuildLink.Redirect(ForumPages.info, "i=1&url={0}", this.Server.UrlEncode(url));
                }
            }
        }
示例#36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.MessageFlagsChangedEventArgs"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="MessageFlagsChangedEventArgs"/>.
 /// </remarks>
 /// <param name="index">The message index.</param>
 /// <param name="flags">The message flags.</param>
 /// <param name="modseq">The modification sequence value.</param>
 public MessageFlagsChangedEventArgs(int index, MessageFlags flags, ulong modseq) : base(index)
 {
     UserFlags = new HashSet <string> ();
     ModSeq    = modseq;
     Flags     = flags;
 }
示例#37
0
        protected virtual void HandleChannelMessage(object sender, IChannelMessageEventArgs args, MessageFlags flags)
        {
            if (flags.HasFlag(MessageFlags.UserBanned))
            {
                return;
            }

            if (args.SenderNickname == ConnectionManager.MyNickname)
            {
                return;
            }

            var originalBody = args.Message;
            var channel      = args.Channel;

            if (Config.ChannelBlacklist.Contains(channel))
            {
                return;
            }

            if (!CooldownsPerChannel.ContainsKey(channel))
            {
                CooldownsPerChannel[channel] = new List <int>(Enumerable.Repeat(0, Config.Replacements.Count));
            }

            var lookups = new Dictionary <string, string>
            {
                ["username"] = args.SenderNickname
            };

            var chunks       = ConnectionManager.SplitMessageToChunks(args.Message);
            var newBody      = new StringBuilder();
            var newCooldowns = new List <int>(CooldownsPerChannel[channel]);

            foreach (var chunk in chunks)
            {
                var textChunk = chunk as TextMessageChunk;
                if (textChunk == null)
                {
                    // don't touch this
                    newBody.Append(chunk);
                    continue;
                }

                bool somethingHit    = false;
                bool fullReplacement = false;
                int  i = -1;

                var newChunk = textChunk.Text;
                foreach (var repl in Config.Replacements)
                {
                    ++i;

                    if (repl.OnlyIfPrecedingHit && !somethingHit)
                    {
                        // no preceding rule hit; don't apply this one
                        continue;
                    }

                    if (repl.AdditionalProbabilityPercent > 0.0)
                    {
                        var replProbabilityValue = Random.NextDouble() * 100.0;
                        if (replProbabilityValue >= repl.AdditionalProbabilityPercent)
                        {
                            // next!
                            continue;
                        }
                    }

                    // perform the replacement
                    string nextNewChunk = ReplacerRegexes[i].Replace(newChunk, lookups);

                    if (Config.CooldownIncreasePerHit >= 0 || repl.CustomCooldownIncreasePerHit >= 0)
                    {
                        if (!string.Equals(newChunk, nextNewChunk, StringComparison.Ordinal))
                        {
                            // this rule changed something!
                            if (newCooldowns[i] == 0)
                            {
                                // warm, apply it!
                                newChunk     = nextNewChunk;
                                somethingHit = true;
                            }

                            // cool down
                            newCooldowns[i] += (repl.CustomCooldownIncreasePerHit >= 0)
                                ? repl.CustomCooldownIncreasePerHit
                                : Config.CooldownIncreasePerHit;

                            if (repl.ReplaceFullMessage)
                            {
                                // the replacement shall become the whole new body
                                newBody.Clear();
                                newBody.Append(newChunk);

                                // stop looping here
                                fullReplacement = true;
                                break;
                            }
                        }
                        else if (newCooldowns[i] > 0)
                        {
                            // this rule didn't change anything; warm up!
                            --newCooldowns[i];
                        }
                    }
                    else
                    {
                        // no cooldowns
                        newChunk = nextNewChunk;

                        if (repl.ReplaceFullMessage && !string.Equals(newChunk, nextNewChunk, StringComparison.Ordinal))
                        {
                            // the replacement shall become the whole new body
                            newBody.Clear();
                            newBody.Append(newChunk);

                            // stop looping here
                            fullReplacement = true;
                            break;
                        }
                    }
                }

                if (Config.CooldownIncreasePerHit >= 0)
                {
                    // update cooldowns
                    CooldownsPerChannel[channel].Clear();
                    CooldownsPerChannel[channel].AddRange(newCooldowns);

                    Logger.LogDebug("cooldowns are now: {Cooldowns}", newCooldowns.Select(c => c.ToString()).StringJoin(", "));
                }

                if (fullReplacement)
                {
                    // the body has been fully replaced
                    break;
                }

                newBody.Append(newChunk);
            }

            if (string.Equals(newBody.ToString(), originalBody, StringComparison.Ordinal))
            {
                return;
            }

            var thisProbabilityValue = Random.NextDouble() * 100.0;

            if (thisProbabilityValue < Config.ProbabilityPercent)
            {
                Logger.LogDebug("{RandomProbability} < {ConfigProbability}; posting {Body}", thisProbabilityValue, Config.ProbabilityPercent, newBody);
                ConnectionManager.SendChannelMessage(args.Channel, newBody.ToString());
            }
            else
            {
                Logger.LogDebug("{RandomProbability} >= {ConfigProbability}; not posting {Body}", thisProbabilityValue, Config.ProbabilityPercent, newBody);
            }
        }
示例#38
0
 /// <summary>
 /// Calculates whether these message flags contain a specific flag.
 /// </summary>
 /// <param name="baseFlags">The existing flags.</param>
 /// <param name="flag">The flags to search for.</param>
 /// <returns></returns>
 public static bool HasMessageFlag(this MessageFlags baseFlags, MessageFlags flag) => (baseFlags & flag) == flag;
示例#39
0
 /// <inheritdoc />
 /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
 /// <exception cref="ArgumentException">The only valid <see cref="MessageFlags"/> are <see cref="MessageFlags.SuppressEmbeds"/> and <see cref="MessageFlags.None"/>.</exception>
 public virtual Task <RestUserMessage> SendFilesAsync(IEnumerable <FileAttachment> attachments, string text, bool isTTS = false,
                                                      Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null,
                                                      MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null,
                                                      Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
 => ChannelHelper.SendFilesAsync(this, Discord, attachments, text, isTTS, embed, allowedMentions,
                                 messageReference, components, stickers, options, embeds, flags);
示例#40
0
		/// <summary>
		/// Handles preview button click event.
		/// </summary>
		protected void Preview_Click( object sender, EventArgs e )
		{
			// make preview row visible
			PreviewRow.Visible = true;

			PreviewMessagePost.MessageFlags.IsHtml = _editor.UsesHTML;
			PreviewMessagePost.MessageFlags.IsBBCode = _editor.UsesBBCode;
			PreviewMessagePost.Message = _editor.Text;

			// set message flags
			MessageFlags tFlags = new MessageFlags();
			tFlags.IsHtml = _editor.UsesHTML;
			tFlags.IsBBCode = _editor.UsesBBCode;

			if ( PageContext.BoardSettings.AllowSignatures )
			{
				using ( DataTable userDT = DB.user_list( PageContext.PageBoardID, PageContext.PageUserID, true ) )
				{
					if ( !userDT.Rows [0].IsNull( "Signature" ) )
					{
						PreviewMessagePost.Signature = userDT.Rows [0] ["Signature"].ToString();
					}
				}
			}
		}
示例#41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.MessageFlagsChangedEventArgs"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="MessageFlagsChangedEventArgs"/>.
 /// </remarks>
 /// <param name="index">The message index.</param>
 /// <param name="flags">The message flags.</param>
 public MessageFlagsChangedEventArgs(int index, MessageFlags flags) : base(index)
 {
     UserFlags = new HashSet <string> ();
     Flags     = flags;
 }
 public void UpdateAndMarkUnacknowledged(Guid messageId, Guid recipientId, object payload, MessagePriority priority, MessageFlags messageFlags)
 {
     this.RecipientId  = recipientId;
     this.MessageId    = messageId;
     this.Payload      = payload;
     this.Priority     = priority;
     this.Flags        = messageFlags;
     this.Acknowledged = false;
 }
示例#43
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            DataRow currentRow = null;

            if (QuotedTopicID != null)
            {
                using (DataTable dt = DB.message_list(QuotedTopicID))
                    currentRow = dt.Rows[0];

                if (Convert.ToInt32(currentRow["TopicID"]) != PageContext.PageTopicID)
                {
                    YafBuildLink.AccessDenied();
                }

                if (!CanQuotePostCheck(currentRow))
                {
                    YafBuildLink.AccessDenied();
                }
            }
            else if (EditTopicID != null)
            {
                using (DataTable dt = DB.message_list(EditTopicID))
                    currentRow = dt.Rows[0];
                _ownerUserId = Convert.ToInt32(currentRow["UserId"]);
                if (!CanEditPostCheck(currentRow))
                {
                    YafBuildLink.AccessDenied();
                }
            }

            if (PageContext.PageForumID == 0)
            {
                YafBuildLink.AccessDenied();
            }
            if (Request["t"] == null && Request["m"] == null && !PageContext.ForumPostAccess)
            {
                YafBuildLink.AccessDenied();
            }
            if (Request["t"] != null && !PageContext.ForumReplyAccess)
            {
                YafBuildLink.AccessDenied();
            }

            //Message.EnableRTE = PageContext.BoardSettings.AllowRichEdit;
            _forumEditor.StyleSheet = YafBuildLink.ThemeFile("theme.css");
            _forumEditor.BaseDir    = YafForumInfo.ForumRoot + "editors";

            Title.Text = GetText("NEWTOPIC");
            PollExpire.Attributes.Add("style", "width:50px");

            if (!IsPostBack)
            {
                // helper bool -- true if this is a completely new topic...
                bool isNewTopic = (TopicID == null) && (QuotedTopicID == null) && (EditTopicID == null);

                Priority.Items.Add(new ListItem(GetText("normal"), "0"));
                Priority.Items.Add(new ListItem(GetText("sticky"), "1"));
                Priority.Items.Add(new ListItem(GetText("announcement"), "2"));
                Priority.SelectedIndex = 0;

                EditReasonRow.Visible = false;
                Preview.Text          = GetText("preview");
                PostReply.Text        = GetText("Save");
                Cancel.Text           = GetText("Cancel");
                CreatePoll.Text       = GetText("createpoll");
                RemovePoll.Text       = GetText("removepoll");

                PersistencyRow.Visible = PageContext.ForumPriorityAccess;
                PriorityRow.Visible    = PageContext.ForumPriorityAccess;
                CreatePollRow.Visible  = !HasPoll(currentRow) && CanHavePoll(currentRow) && PageContext.ForumPollAccess;
                RemovePollRow.Visible  = HasPoll(currentRow) && CanHavePoll(currentRow) && PageContext.ForumPollAccess && PageContext.ForumModeratorAccess;

                if (RemovePollRow.Visible)
                {
                    InitPollUI(currentRow);
                }

                // Show post to blog option only to a new post
                BlogRow.Visible = (PageContext.BoardSettings.AllowPostToBlog && isNewTopic && !PageContext.IsGuest);

                // handle new topic options...
                NewTopicOptionsRow.Visible = isNewTopic && !PageContext.IsGuest;
                if (isNewTopic && PageContext.ForumUploadAccess)
                {
                    TopicAttach.Visible      = true;
                    TopicAttachLabel.Visible = true;
                }

                if ((PageContext.IsGuest && PageContext.BoardSettings.EnableCaptchaForGuests) ||
                    (PageContext.BoardSettings.EnableCaptchaForPost && !PageContext.IsCaptchaExcluded))
                {
                    Session ["CaptchaImageText"] = General.GetCaptchaString();
                    imgCaptcha.ImageUrl          = String.Format("{0}resource.ashx?c=1", YafForumInfo.ForumRoot);
                    tr_captcha1.Visible          = true;
                    tr_captcha2.Visible          = true;
                }

                if (PageContext.Settings.LockedForum == 0)
                {
                    PageLinks.AddLink(PageContext.BoardSettings.Name, YAF.Classes.Utils.YafBuildLink.GetLink(YAF.Classes.Utils.ForumPages.forum));
                    PageLinks.AddLink(PageContext.PageCategoryName, YAF.Classes.Utils.YafBuildLink.GetLink(YAF.Classes.Utils.ForumPages.forum, "c={0}", PageContext.PageCategoryID));
                }
                PageLinks.AddForumLinks(PageContext.PageForumID);

                // check if it's a reply to a topic...
                if (TopicID != null)
                {
                    InitReplyToTopic();
                }

                // If currentRow != null, we are quoting a post in a new reply, or editing an existing post
                if (currentRow != null)
                {
                    MessageFlags messageFlags = new MessageFlags(currentRow["Flags"]);
                    string       message      = currentRow["Message"].ToString();

                    if (QuotedTopicID != null)
                    {
                        // quoting a reply to a topic...
                        InitQuotedReply(currentRow, message, messageFlags);
                    }
                    else if (EditTopicID != null)
                    {
                        // editing a message...
                        InitEditedPost(currentRow, message, messageFlags);
                    }
                }

                // add the "New Topic" page link last...
                if (isNewTopic)
                {
                    PageLinks.AddLink(GetText("NEWTOPIC"));
                }

                // form user is only for "Guest"
                From.Text = PageContext.PageUserName;
                if (User != null)
                {
                    FromRow.Visible = false;
                }
            }
        }
示例#44
0
        /// <summary>
        /// Maps the search document to data.
        /// </summary>
        /// <param name="highlighter">The highlighter.</param>
        /// <param name="analyzer">The analyzer.</param>
        /// <param name="doc">The document.</param>
        /// <param name="userAccessList">The user access list.</param>
        /// <returns>
        /// Returns the Search Message
        /// </returns>
        private SearchMessage MapSearchDocumentToData(
            Highlighter highlighter,
            Analyzer analyzer,
            Document doc,
            List <vaccess> userAccessList)
        {
            var forumId = doc.Get("ForumId").ToType <int>();

            if (!userAccessList.Any() || !userAccessList.Exists(v => v.ForumID == forumId && v.ReadAccess))
            {
                return(null);
            }

            var flags        = doc.Get("Flags").ToType <int>();
            var messageFlags = new MessageFlags(flags);

            var formattedMessage = this.Get <IFormatMessage>().FormatMessage(doc.Get("Message"), messageFlags);

            formattedMessage = this.Get <IBBCode>().FormatMessageWithCustomBBCode(
                formattedMessage,
                new MessageFlags(flags),
                doc.Get("UserId").ToType <int>(),
                doc.Get("MessageId").ToType <int>());

            var message = formattedMessage;

            try
            {
                message = GetHighlight(highlighter, analyzer, "Message", message);
            }
            catch (Exception)
            {
                // Ignore
                message = formattedMessage;
            }
            finally
            {
                if (message.IsNotSet())
                {
                    message = formattedMessage;
                }
            }

            string topic;

            try
            {
                topic = GetHighlight(highlighter, analyzer, "Topic", doc.Get("Topic"));
            }
            catch (Exception)
            {
                topic = doc.Get("Topic");
            }

            return(new SearchMessage
            {
                MessageId = doc.Get("MessageId").ToType <int>(),
                Message = message,
                Flags = flags,
                Posted =
                    doc.Get("Posted").ToType <DateTime>().ToString(
                        "yyyy-MM-ddTHH:mm:ssZ",
                        CultureInfo.InvariantCulture),
                UserName = doc.Get("Author"),
                UserId = doc.Get("UserId").ToType <int>(),
                TopicId = doc.Get("TopicId").ToType <int>(),
                Topic = topic.IsSet() ? topic : doc.Get("Topic"),
                ForumId = doc.Get("ForumId").ToType <int>(),
                Description = doc.Get("Description"),
                TopicUrl = BuildLink.GetLink(ForumPages.posts, "t={0}", doc.Get("TopicId").ToType <int>()),
                MessageUrl =
                    BuildLink.GetLink(
                        ForumPages.posts,
                        "m={0}#post{0}",
                        doc.Get("MessageId").ToType <int>()),
                ForumUrl = BuildLink.GetLink(ForumPages.forum, "f={0}", doc.Get("ForumId").ToType <int>()),
                UserDisplayName = doc.Get("AuthorDisplay"),
                ForumName = doc.Get("ForumName"),
                UserStyle = doc.Get("AuthorStyle")
            });
        }
示例#45
0
		/// <summary>
		/// Handles save button click event. 
		/// </summary>
		protected void Save_Click( object sender, EventArgs e )
		{
			// recipient was set in dropdown
			if ( ToList.Visible ) To.Text = ToList.SelectedItem.Text;
			if ( To.Text.Length <= 0 )
			{
				// recipient is required field
				PageContext.AddLoadMessage( GetText( "need_to" ) );
				return;
			}

			// subject is required
			if ( Subject.Text.Trim().Length <= 0 )
			{
				PageContext.AddLoadMessage( GetText( "need_subject" ) );
				return;
			}
			// message is required
			if ( _editor.Text.Trim().Length <= 0 )
			{
				PageContext.AddLoadMessage( GetText( "need_message" ) );
				return;
			}

			if ( ToList.SelectedItem != null && ToList.SelectedItem.Value == "0" )
			{
				// administrator is sending PMs tp all users

				string body = _editor.Text;
				MessageFlags messageFlags = new MessageFlags();

				messageFlags.IsHtml = _editor.UsesHTML;
				messageFlags.IsBBCode = _editor.UsesBBCode;

				DB.pmessage_save( PageContext.PageUserID, 0, Subject.Text, body, messageFlags.BitValue );

				// redirect to outbox (sent items), not control panel
				YafBuildLink.Redirect( ForumPages.cp_pm, "v={0}", "out" );
			}
			else
			{
				// remove all abundant whitespaces and separators
				To.Text.Trim();
				Regex rx = new Regex( @";(\s|;)*;" );
				To.Text = rx.Replace( To.Text, ";" );
				if ( To.Text.StartsWith( ";" ) ) To.Text = To.Text.Substring( 1 );
				if ( To.Text.EndsWith( ";" ) ) To.Text = To.Text.Substring( 0, To.Text.Length - 1 );
				rx = new Regex( @"\s*;\s*" );
				To.Text = rx.Replace( To.Text, ";" );

				// list of recipients
				List<string> recipients = new List<string>( To.Text.Split( ';' ) );
				// list of recipient's ids
				int [] recipientID = new int [recipients.Count];

				if ( recipients.Count > PageContext.BoardSettings.PrivateMessageMaxRecipients && !PageContext.IsAdmin )
				{
					// to many recipients
					PageContext.AddLoadMessage( String.Format( GetText( "TOO_MANY_RECIPIENTS" ), PageContext.BoardSettings.PrivateMessageMaxRecipients ) );
					return;
				}

				// test sending user's PM count
				if ( PageContext.BoardSettings.MaxPrivateMessagesPerUser != 0 &&
					( DB.user_pmcount( PageContext.PageUserID ) + recipients.Count ) > PageContext.BoardSettings.MaxPrivateMessagesPerUser &&
					!PageContext.IsAdmin )
				{
					// user has full PM box
					PageContext.AddLoadMessage( String.Format( GetText( "OWN_PMBOX_FULL" ), PageContext.BoardSettings.MaxPrivateMessagesPerUser ) );
					return;
				}

				// get recipients' IDs
				for ( int i = 0; i < recipients.Count; i++ )
				{
					using ( DataTable dt = DB.user_find( PageContext.PageBoardID, false, recipients [i], null ) )
					{
						if ( dt.Rows.Count != 1 )
						{
							PageContext.AddLoadMessage( String.Format( GetText( "NO_SUCH_USER" ), recipients [i] ) );
							return;
						}
                        else if (SqlDataLayerConverter.VerifyInt32(dt.Rows [0] ["IsGuest"]) > 0 )						
						{
							PageContext.AddLoadMessage( GetText( "NOT_GUEST" ) );
							return;
						}

						// get recipient's ID from the database
						recipientID [i] = Convert.ToInt32( dt.Rows [0] ["UserID"] );

						// test receiving user's PM count
						if ( PageContext.BoardSettings.MaxPrivateMessagesPerUser != 0 &&
							DB.user_pmcount( recipientID [i] ) >= PageContext.BoardSettings.MaxPrivateMessagesPerUser &&
							!PageContext.IsAdmin )
						{
							// recipient has full PM box
							PageContext.AddLoadMessage( String.Format( GetText( "RECIPIENTS_PMBOX_FULL" ), recipients [i] ) );
							return;
						}
					}
				}

				// send PM to all recipients
				for ( int i = 0; i < recipients.Count; i++ )
				{
					string body = _editor.Text;

					MessageFlags messageFlags = new MessageFlags();

					messageFlags.IsHtml = _editor.UsesHTML;
					messageFlags.IsBBCode = _editor.UsesBBCode;

					DB.pmessage_save( PageContext.PageUserID, recipientID [i], Subject.Text, body, messageFlags.BitValue );

					if ( PageContext.BoardSettings.AllowPMEmailNotification )
						SendPMNotification( recipientID [i], Subject.Text );
				}

				// redirect to outbox (sent items), not control panel
				YafBuildLink.Redirect( ForumPages.cp_pm, "v={0}", "out" );
			}
		}
        /// <summary>
        /// Sends a OpenChannelResponse message to a store.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="channels">The channels.</param>
        /// <param name="errors">The errors.</param>
        /// <param name="messageFlag">The message flag.</param>
        /// <returns>The message identifier.</returns>
        public virtual long OpenChannelResponse(IMessageHeader request, IList <OpenChannelInfo> channels, IList <ErrorInfo> errors, MessageFlags messageFlag = MessageFlags.MultiPartAndFinalPart)
        {
            var header = CreateMessageHeader(Protocols.ChannelDataLoad, MessageTypes.ChannelDataLoad.OpenChannelResponse, request.MessageId, messageFlag);

            var message = new OpenChannelResponse
            {
                Channels = channels ?? new List <OpenChannelInfo>(),
                Errors   = errors ?? new List <ErrorInfo>()
            };

            return(Session.SendMessage(header, message));
        }
示例#47
0
 public LogMessageAttributes(MessageClass classification, MessageLevel level, MessageSuppression messageSuppression, MessageFlags flags)
 {
     Classification     = classification;
     Level              = level;
     MessageSuppression = messageSuppression;
     Flags              = flags;
 }
        /// <summary>
        /// Parse the RopTransportNewMailRequest structure.
        /// </summary>
        /// <param name="s">An stream containing RopTransportNewMailRequest structure.</param>
        public override void Parse(Stream s)
        {
            base.Parse(s);

            this.RopId = (RopIdType)ReadByte();
            this.LogonId = ReadByte();
            this.InputHandleIndex = ReadByte();
            this.MessageId = new MessageID();
            this.MessageId.Parse(s);
            this.FolderId = new FolderID();
            this.FolderId.Parse(s);
            this.MessageClass = new MAPIString(Encoding.ASCII);
            this.MessageClass.Parse(s);
            this.MessageFlags = (MessageFlags)ReadUint();
        }
示例#49
0
		/// <summary>
		/// Appends the specified message to the folder.
		/// </summary>
		/// <remarks>
		/// Appends the specified message to the folder and returns the UniqueId assigned to the message.
		/// </remarks>
		/// <returns>The UID of the appended message, if available; otherwise, <c>null</c>.</returns>
		/// <param name="options">The formatting options.</param>
		/// <param name="message">The message.</param>
		/// <param name="flags">The message flags.</param>
		/// <param name="date">The received date of the message.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="options"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="message"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// Internationalized formatting was requested but has not been enabled.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="ImapFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// Internationalized formatting was requested but is not supported by the server.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override UniqueId? Append (FormatOptions options, MimeMessage message, MessageFlags flags, DateTimeOffset date, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (message == null)
				throw new ArgumentNullException ("message");

			CheckState (false, false);

			if (options.International && (Engine.Capabilities & ImapCapabilities.UTF8Accept) == 0)
				throw new NotSupportedException ("The IMAP server does not support the UTF8 extension.");

			var format = options.Clone ();
			format.NewLineFormat = NewLineFormat.Dos;

			if ((Engine.Capabilities & ImapCapabilities.UTF8Only) == ImapCapabilities.UTF8Only)
				format.International = true;

			if (format.International && !Engine.UTF8Enabled)
				throw new InvalidOperationException ("The UTF8 extension has not been enabled.");

			var ic = QueueAppend (format, message, flags, date, cancellationToken, progress);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, this);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("APPEND", ic);

			var append = ic.RespCodes.OfType<AppendUidResponseCode> ().FirstOrDefault ();

			if (append != null)
				return append.UidSet[0];

			return null;
		}
        /// <summary>
        /// Sends a single list item as a response for GetPart and GetPartsByRange.
        /// </summary>
        /// <param name="uri">The URI of the parent object.</param>
        /// <param name="uid">The ID of the element within the list.</param>
        /// <param name="contentType">The content type string.</param>
        /// <param name="data">The data.</param>
        /// <param name="correlationId">The correlation identifier.</param>
        /// <param name="messageFlag">The message flag.</param>
        /// <returns>The message identifier.</returns>
        public long ObjectPart(string uri, string uid, string contentType, byte[] data, long correlationId, MessageFlags messageFlag = MessageFlags.MultiPartAndFinalPart)
        {
            var header = CreateMessageHeader(Protocols.GrowingObject, MessageTypes.GrowingObject.ObjectPart, correlationId, messageFlag);

            var message = new ObjectPart
            {
                Uri         = uri,
                Uid         = uid,
                ContentType = contentType,
                Data        = data
            };

            return(Session.SendMessage(header, message));
        }
示例#51
0
		IList<int> ModifyFlags (IList<int> indexes, ulong? modseq, MessageFlags flags, HashSet<string> userFlags, string action, CancellationToken cancellationToken)
		{
			var flaglist = ImapUtils.FormatFlagsList (flags & PermanentFlags, userFlags != null ? userFlags.Count : 0);
			var userFlagList = userFlags != null ? userFlags.ToArray () : new object[0];
			var set = ImapUtils.FormatIndexSet (indexes);

			if (modseq.HasValue && !SupportsModSeq)
				throw new NotSupportedException ("The ImapFolder does not support mod-sequences.");

			CheckState (true, true);

			if (indexes.Count == 0)
				return new int[0];

			string @params = string.Empty;
			if (modseq.HasValue)
				@params = string.Format (" (UNCHANGEDSINCE {0})", modseq.Value);

			var format = string.Format ("STORE {0}{1} {2} {3}\r\n", set, @params, action, flaglist);
			var ic = Engine.QueueCommand (cancellationToken, this, format, userFlagList);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, null);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("STORE", ic);

			if (modseq.HasValue) {
				var modified = ic.RespCodes.OfType<ModifiedResponseCode> ().FirstOrDefault ();

				if (modified != null) {
					var unmodified = new int[modified.UidSet.Count];
					for (int i = 0; i < unmodified.Length; i++)
						unmodified[i] = (int) (modified.UidSet[i].Id - 1);

					return unmodified;
				}
			}

			return new int[0];
		}
示例#52
0
        /// <summary>
        /// Raises the <see cref="StatusMessage"/> event and sends this data to the <see cref="Logger"/>.
        /// </summary>
        /// <param name="level">The <see cref="MessageLevel"/> to assign to this message</param>
        /// <param name="status">New status message.</param>
        /// <param name="eventName">A fixed string to classify this event; defaults to <c>null</c>.</param>
        /// <param name="flags"><see cref="MessageFlags"/> to use, if any; defaults to <see cref="MessageFlags.None"/>.</param>
        /// <remarks>
        /// <see pref="eventName"/> should be a constant string value associated with what type of message is being
        /// generated. In general, there should only be a few dozen distinct event names per class. Exceeding this
        /// threshold will cause the EventName to be replaced with a general warning that a usage issue has occurred.
        /// </remarks>
        protected virtual void OnStatusMessage(MessageLevel level, string status, string eventName = null, MessageFlags flags = MessageFlags.None)
        {
            try
            {
                Log.Publish(level, flags, eventName ?? "DataGapRecovery", status);

                using (Logger.SuppressLogMessages())
                    StatusMessage?.Invoke(this, new EventArgs <string>(AdapterBase.GetStatusWithMessageLevelPrefix(status, level)));
            }
            catch (Exception ex)
            {
                // We protect our code from consumer thrown exceptions
                OnProcessException(MessageLevel.Info, new InvalidOperationException($"Exception in consumer handler for StatusMessage event: {ex.Message}", ex), "ConsumerEventException");
            }
        }
示例#53
0
		/// <summary>
		/// Removes a set of flags from the specified messages only if their mod-sequence value is less than the specified value.
		/// </summary>
		/// <remarks>
		/// Removes a set of flags from the specified messages only if their mod-sequence value is less than the specified value.
		/// </remarks>
		/// <returns>The indexes of the messages that were not updated.</returns>
		/// <param name="indexes">The indexes of the messages.</param>
		/// <param name="modseq">The mod-sequence value.</param>
		/// <param name="flags">The message flags to remove.</param>
		/// <param name="userFlags">A set of user-defined flags to remove.</param>
		/// <param name="silent">If set to <c>true</c>, no <see cref="MailFolder.MessageFlagsChanged"/> events will be emitted.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="indexes"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>No flags were specified.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <see cref="ImapFolder"/> does not support mod-sequences.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override IList<int> RemoveFlags (IList<int> indexes, ulong modseq, MessageFlags flags, HashSet<string> userFlags, bool silent, CancellationToken cancellationToken = default (CancellationToken))
		{
			if ((flags & SettableFlags) == 0 && (userFlags == null || userFlags.Count == 0))
				throw new ArgumentException ("No flags were specified.", "flags");

			return ModifyFlags (indexes, modseq, flags, userFlags, silent ? "-FLAGS.SILENT" : "-FLAGS", cancellationToken);
		}
示例#54
0
        /// <summary>
        /// Raises the <see cref="ProcessException"/> event.
        /// </summary>
        /// <param name="level">The <see cref="MessageLevel"/> to assign to this message</param>
        /// <param name="exception">Processing <see cref="Exception"/>.</param>
        /// <param name="eventName">A fixed string to classify this event; defaults to <c>null</c>.</param>
        /// <param name="flags"><see cref="MessageFlags"/> to use, if any; defaults to <see cref="MessageFlags.None"/>.</param>
        /// <remarks>
        /// <see pref="eventName"/> should be a constant string value associated with what type of message is being
        /// generated. In general, there should only be a few dozen distinct event names per class. Exceeding this
        /// threshold will cause the EventName to be replaced with a general warning that a usage issue has occurred.
        /// </remarks>
        protected virtual void OnProcessException(MessageLevel level, Exception exception, string eventName = null, MessageFlags flags = MessageFlags.None)
        {
            try
            {
                Log.Publish(level, flags, eventName ?? "DataGapRecovery", exception?.Message, null, exception);

                using (Logger.SuppressLogMessages())
                    ProcessException?.Invoke(this, new EventArgs <Exception>(exception));
            }
            catch (Exception ex)
            {
                // We protect our code from consumer thrown exceptions
                Log.Publish(MessageLevel.Info, "ConsumerEventException", $"Exception in consumer handler for ProcessException event: {ex.Message}", null, ex);
            }
        }
示例#55
0
		internal void UpdateAcceptedFlags (MessageFlags flags)
		{
			AcceptedFlags = flags;
		}
示例#56
0
 async Task <IThreadChannel> IForumChannel.CreatePostWithFileAsync(string title, Stream stream, string filename, ThreadArchiveDuration archiveDuration, int?slowmode, string text, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageComponent components, ISticker[] stickers, Embed[] embeds, MessageFlags flags)
 => await CreatePostWithFileAsync(title, stream, filename, archiveDuration, slowmode, text, embed, options, isSpoiler, allowedMentions, components, stickers, embeds, flags).ConfigureAwait(false);
示例#57
0
 /// <summary>
 /// The format message.
 /// </summary>
 /// <param name="formatMessage">
 /// The format Message.
 /// </param>
 /// <param name="message">
 /// The message.
 /// </param>
 /// <param name="messageFlags">
 /// The message flags.
 /// </param>
 /// <returns>
 /// The formatted message.
 /// </returns>
 public static string FormatMessage([NotNull] this IFormatMessage formatMessage, [NotNull] string message, [NotNull] MessageFlags messageFlags)
 {
     return(formatMessage.FormatMessage(message, messageFlags, false, DateTime.UtcNow));
 }
示例#58
0
 async Task <IThreadChannel> IForumChannel.CreatePostWithFilesAsync(string title, IEnumerable <FileAttachment> attachments, ThreadArchiveDuration archiveDuration, int?slowmode, string text, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageComponent components, ISticker[] stickers, Embed[] embeds, MessageFlags flags)
 => await CreatePostWithFilesAsync(title, attachments, archiveDuration, slowmode, text, embed, options, allowedMentions, components, stickers, embeds, flags);
示例#59
0
        /// <summary>
        /// The post reply handle edit post.
        /// </summary>
        /// <returns>
        /// Returns the Message Id
        /// </returns>
        protected Message PostReplyHandleEditPost()
        {
            if (!this.PageContext.ForumEditAccess)
            {
                BuildLink.AccessDenied();
            }

            var subjectSave     = string.Empty;
            var descriptionSave = string.Empty;
            var stylesSave      = string.Empty;

            if (this.TopicSubjectTextBox.Enabled)
            {
                subjectSave = this.TopicSubjectTextBox.Text;
            }

            if (this.TopicDescriptionTextBox.Enabled)
            {
                descriptionSave = this.TopicDescriptionTextBox.Text;
            }

            if (this.TopicStylesTextBox.Enabled)
            {
                stylesSave = this.TopicStylesTextBox.Text;
            }

            // Mek Suggestion: This should be removed, resetting flags on edit is a bit lame.
            // Ederon : now it should be better, but all this code around forum/topic/message flags needs revamp
            // retrieve message flags
            var messageFlags = new MessageFlags(this.editedMessage.Item2.Flags)
            {
                IsHtml =
                    this
                    .forumEditor
                    .UsesHTML,
                IsBBCode
                    =
                        this
                        .forumEditor
                        .UsesBBCode,
                IsPersistent
                    =
                        this
                        .PostOptions1
                        .PersistentChecked
            };

            this.editedMessage.Item2.Flags = messageFlags.BitValue;

            var isModeratorChanged = this.PageContext.PageUserID != this.ownerUserId;

            this.GetRepository <Message>().Update(
                this.Priority.SelectedValue.ToType <short>(),
                this.forumEditor.Text.Trim(),
                descriptionSave.Trim(),
                string.Empty,
                stylesSave.Trim(),
                subjectSave.Trim(),
                this.HtmlEncode(this.ReasonEditor.Text),
                isModeratorChanged,
                this.PageContext.IsAdmin || this.PageContext.ForumModeratorAccess,
                this.editedMessage,
                this.PageContext.PageUserID);

            this.UpdateWatchTopic(this.PageContext.PageUserID, this.PageContext.PageTopicID);

            // remove cache if it exists...
            this.Get <IDataCache>()
            .Remove(string.Format(Constants.Cache.FirstPostCleaned, this.PageContext.PageBoardID, this.PageContext.PageTopicID));

            return(this.editedMessage.Item2);
        }
示例#60
0
 /// <inheritdoc cref="IForumChannel.CreatePostWithFileAsync(string, Stream, string, ThreadArchiveDuration, int?, string, Embed, RequestOptions, bool, AllowedMentions, MessageComponent, ISticker[], Embed[], MessageFlags)"/>
 public async Task <RestThreadChannel> CreatePostWithFileAsync(string title, Stream stream, string filename, ThreadArchiveDuration archiveDuration = ThreadArchiveDuration.OneDay,
                                                               int?slowmode = null, string text = null, Embed embed = null, RequestOptions options = null, bool isSpoiler = false,
                                                               AllowedMentions allowedMentions = null, MessageComponent components = null,
                                                               ISticker[] stickers             = null, Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
 {
     using var file = new FileAttachment(stream, filename, isSpoiler: isSpoiler);
     return(await ThreadHelper.CreatePostAsync(this, Discord, title, new FileAttachment[] { file }, archiveDuration, slowmode, text, embed, options, allowedMentions, components, stickers, embeds, flags).ConfigureAwait(false));
 }