Ejemplo n.º 1
0
 public IEnumerable <IIrcChannel> GetUserSubscriptionsToChannel(IBotUser botUser)
 {
     return(this.channelConfiguration.Items
            .Where(channel => channel.Users.Select(y => y.Mask).Contains(botUser.Mask))
            .Where(channel => channel.Users.First(x => x.Mask.Equals(botUser.Mask)).Subscribed)
            .ToList());
 }
Ejemplo n.º 2
0
        private void SendIndividualEmail(IList <IStalk> stalks, IRecentChange rc, IBotUser botUser)
        {
            if (!botUser.EmailAddressConfirmed)
            {
                return;
            }

            var stalkList = string.Join(", ", stalks.Select(x => x.Identifier));

            try
            {
                var extraHeaders = new Dictionary <string, string>
                {
                    { "StalkList", stalkList }
                };

                this.emailHelper.SendEmail(
                    this.emailTemplateFormatter.FormatRecentChangeStalksForEmail(stalks, rc, botUser),
                    string.Format(this.templates.EmailRcSubject, stalkList, rc.Page),
                    null,
                    botUser,
                    extraHeaders);
            }
            catch (Exception ex)
            {
                this.logger.ErrorFormat(ex, "Failed to send notification email for RC {0}", rc);
            }
        }
Ejemplo n.º 3
0
        public bool Equals(IBotUser other)
        {
            if(ReferenceEquals(other, null))
                return false;

            return
                EqualityComparer<String>.Default.Equals(this.Username, other.Username);
             ;
        }
Ejemplo n.º 4
0
        public int CompareTo(IBotUser other)
        {
            if(ReferenceEquals(other, null))
                return 1;

            int result = 0;
            result = this.Username.CompareTo(other.Username);
            return result;
        }
Ejemplo n.º 5
0
        public XmlElement ToXmlElement(IBotUser item, XmlDocument doc)
        {
            var e = doc.CreateElement("user");

            e.SetAttribute("mask", item.Identifier);

            e.SetAttribute("webguid", item.WebGuid.ToString());

            if (item.WebPassword != null)
            {
                e.SetAttribute("webpassword", item.WebPassword);
            }

            if (item.GlobalFlags != null)
            {
                e.SetAttribute("globalflags", item.GlobalFlags);
            }

            if (item.EmailAddress != null)
            {
                e.SetAttribute("mail", item.EmailAddress);
                e.SetAttribute("mailconfirmed", XmlConvert.ToString(item.EmailAddressConfirmed));
            }

            if (item.EmailConfirmationToken != null)
            {
                e.SetAttribute("mailconfirmhash", item.EmailConfirmationToken);
            }

            if (item.DeletionConfirmationToken != null)
            {
                e.SetAttribute("deleteconfirmhash", item.DeletionConfirmationToken);
            }

            if (item.DeletionConfirmationTimestamp != null)
            {
                e.SetAttribute(
                    "deletetimestamp",
                    XmlConvert.ToString(item.DeletionConfirmationTimestamp.Value, XmlDateTimeSerializationMode.Utc));
            }

            if (item.EmailConfirmationTimestamp != null)
            {
                e.SetAttribute(
                    "emailtimestamp",
                    XmlConvert.ToString(item.EmailConfirmationTimestamp.Value, XmlDateTimeSerializationMode.Utc));
            }

            return(e);
        }
Ejemplo n.º 6
0
        public static void SetGroup(IContext context, IBotUser botUser, IBotGroup group)
        {
            EnsureIdentified(context);

            if(context.User.Equals(botUser))
                throw new InvalidOperationException("Cannot set your own group.");

            if(botUser.Group.IsMoreOrSamePrivileged(context.User.Group))
                throw new InvalidOperationException("Cannot set group for users that have the same or more privileges than yourself.");

            if(group.IsMoreOrSamePrivileged(context.User.Group))
                throw new InvalidOperationException("Cannot set group to one that has the same or more privileges than yourself.");

            botUser.Group = group;
        }
Ejemplo n.º 7
0
        public IEnumerable <SubscriptionResult> GetUserStalkSubscriptionsInChannel(IBotUser user, IIrcChannel channel)
        {
            var channelSubscribed = channel.Users.Where(x => x.Subscribed).Any(x => x.Mask.Equals(user.Mask));

            var results = new List <SubscriptionResult>();

            foreach (var stalk in channel.Stalks)
            {
                var result = new SubscriptionResult
                {
                    Channel = channel, BotUser = user, Stalk = stalk.Value, Complete = true
                };

                if (channelSubscribed)
                {
                    result.IsSubscribed = true;
                    result.Source       = SubscriptionSource.Channel;
                }

                var subscription = stalk.Value.Subscribers.FirstOrDefault(x => x.Mask.Equals(user.Mask));
                if (subscription == null)
                {
                    // use the channel result.
                    results.Add(result);
                    continue;
                }

                if (subscription.Subscribed)
                {
                    result.IsSubscribed = true;
                    result.Source       = SubscriptionSource.Stalk;
                }
                else
                {
                    result.IsSubscribed = false;
                    result.Overridden   = true;
                    result.Source       = SubscriptionSource.Stalk;
                }

                results.Add(result);
            }

            return(results);
        }
Ejemplo n.º 8
0
        private IrcUser GetIrcUser(IIrcChannel channel, IBotUser currentUser)
        {
            if (!this.FreenodeClient.Channels.ContainsKey(channel.Identifier))
            {
                return(null);
            }

            var freenodeClientChannel = this.FreenodeClient.Channels[channel.Identifier];
            var channelUser           = freenodeClientChannel.Users.Values
                                        .FirstOrDefault(x => currentUser.Mask.Matches(x.User).GetValueOrDefault());
            var ircUser = channelUser != null
                ? channelUser.User
                : new IrcUser(this.FreenodeClient)
            {
                Account = currentUser.Mask.ToString().Substring(3), SkeletonStatus = IrcUserSkeletonStatus.Account
            };

            return(ircUser);
        }
Ejemplo n.º 9
0
        private IEnumerable <CommandResponse> GetBotUser(out IBotUser botUser)
        {
            botUser = null;

            var accountKey = string.Format("$a:{0}", this.User.Account);

            botUser = this.botUserConfiguration[accountKey];

            if (botUser == null)
            {
                return(new[]
                {
                    new CommandResponse
                    {
                        Message = "You are not registered with the bot!",
                        Destination = CommandResponseDestination.PrivateMessage
                    }
                });
            }

            return(null);
        }
Ejemplo n.º 10
0
        public bool Check(IBotUser user, bool defaultAllowed = true)
        {
            if(!HasAllowed)
                return defaultAllowed;

            if(!Allowed)
                return false;

            if(!HasLimit || !HasTimespan)
                return true;

            CheckLimitReset(user);

            return PeekLimit(user);
        }
        public string FormatStalkListForEmail(IEnumerable <IStalk> stalks, IBotUser botUser)
        {
            var stalkInfo = new StringBuilder();

            foreach (var stalk in stalks)
            {
                var expiry = stalk.ExpiryTime.HasValue
                    ? stalk.ExpiryTime.Value.ToString(this.appConfig.DateFormat)
                    : "never";

                var dynamicExpiry = stalk.DynamicExpiry.HasValue
                    ? " (on trigger, up to an additional " + stalk.DynamicExpiry.Value.ToString(this.appConfig.TimeSpanFormat) + ")"
                    : string.Empty;

                var lastTrigger = (stalk.LastTriggerTime.HasValue && stalk.LastTriggerTime != DateTime.MinValue)
                    ? stalk.LastTriggerTime.Value.ToString(this.appConfig.DateFormat)
                    : "never";

                var lastUpdate = stalk.LastUpdateTime.HasValue
                    ? stalk.LastUpdateTime.Value.ToString(this.appConfig.DateFormat)
                    : "never";

                var creation = stalk.CreationDate == DateTime.MinValue
                    ? stalk.CreationDate.ToString(this.appConfig.DateFormat)
                    : "before records began";

                var subList = new List <string>();
                var subItem = stalk.Subscribers.FirstOrDefault(x => x.Mask.ToString() == botUser.Mask.ToString());
                if (subItem != null)
                {
                    subList.Add(subItem.Subscribed ? "via stalk" : "excluded stalk");
                }

                if (this.channelConfig[stalk.Channel]
                    .Users
                    .Any(x => x.Mask.ToString() == botUser.Mask.ToString() && x.Subscribed))
                {
                    subList.Add("via channel");
                }

                var subscription = string.Join(", ", subList);
                if (string.IsNullOrWhiteSpace(subscription))
                {
                    subscription = "none";
                }

                var hookContent = "\n";

                var handler = this.OnStalkFormat;
                if (handler != null)
                {
                    var stalkInfoFormattingEventArgs = new StalkInfoFormattingEventArgs(stalk);
                    handler(this, stalkInfoFormattingEventArgs);
                    hookContent = stalkInfoFormattingEventArgs.ToString();
                }

                stalkInfo.Append(
                    string.Format(
                        this.templates.EmailStalkTemplate,
                        stalk.Identifier,
                        stalk.Description,
                        stalk.SearchTree,
                        stalk.Channel,
                        expiry,
                        lastTrigger,
                        stalk.TriggerCount,
                        subscription,
                        lastUpdate,
                        stalk.WatchChannel,
                        dynamicExpiry,
                        creation,
                        hookContent
                        ));
            }

            var stalksFormatted = stalkInfo.ToString().TrimEnd();

            return(stalksFormatted);
        }
        public string FormatRecentChangeStalksForEmail(IEnumerable <IStalk> stalks, IRecentChange rc, IBotUser botUser)
        {
            var stalksFormatted = this.FormatStalkListForEmail(stalks, botUser);

            var sizeDiff = "N/A";

            if (rc.SizeDiff.HasValue)
            {
                sizeDiff = (rc.SizeDiff.Value > 0 ? "+" : string.Empty) +
                           rc.SizeDiff.Value.ToString(CultureInfo.InvariantCulture);
            }

            return(string.Format(
                       this.templates.EmailRcTemplate,
                       stalksFormatted,
                       rc.Url,
                       rc.Page,
                       rc.User,
                       rc.EditSummary,
                       sizeDiff,
                       rc.EditFlags,
                       DateTime.UtcNow.ToString(this.appConfig.DateFormat)
                       ));
        }
Ejemplo n.º 13
0
        private void Allowed(ICommand command, bool privateMessage, IBotUser botUser)
        {
            if(command.Private && !privateMessage)
                throw new InvalidOperationException("This command can only be sent in a private message.");

            IPermission permission = _bot.Permission.GetPermission(command, botUser.Group);
            if(command.DefaultPermissions.Length > 0)
            {
                permission.CheckThrows(botUser, false);
            }
            else
            {
                permission.CheckThrows(botUser, true);
            }
        }
Ejemplo n.º 14
0
        private void CheckLimitReset(IBotUser user)
        {
            TimeSpan timespan;
            if(_timespan == null || !_timespan.HasValue)
                timespan = _defaultTimespan.Value;
            else
                timespan = _timespan.Value;

            if(DateTime.Now >= _nextTimeReset.GetOrCreate(user, () => DateTime.MinValue))
            {
                _nextTimeReset[user] = DateTime.Now + timespan;
                _currentItemsPerTimespan[user] = 0;
            }
        }
Ejemplo n.º 15
0
        public void Unregister(IUser user, IBotUser botUser, String username, String password)
        {
            if(!botUser.Username.Equals(username))
                throw new ArgumentException("Incorrect username.", "username");

            if(!botUser.CheckPassword(password))
                throw new ArgumentException("Incorrect password.", "password");

            _identifiedUsers.Remove(user);
            _users.Remove(botUser.Username);
        }
Ejemplo n.º 16
0
        public void RemoveMask(IBotUser user, IdentityMask mask)
        {
            if(!_allMasks.Contains(mask))
                throw new ArgumentException("Identity mask " + mask + " does not exists.", "mask");

            _masks.Remove(user, mask);
            _userData[user.Username].Masks.Remove(mask);
            _allMasks.Remove(mask);
        }
Ejemplo n.º 17
0
 public IEnumerable<IdentityMask> Masks(IBotUser user)
 {
     return _masks[user];
 }
Ejemplo n.º 18
0
        public void AddMask(IBotUser user, IdentityMask mask)
        {
            // TODO: What about conflicting masks?
            if(_allMasks.Contains(mask))
                throw new ArgumentException("Identity mask " + mask + " already exists.", "mask");

            _masks.Add(user, mask);
            _userData[user.Username].Masks.Add(mask);
            _allMasks.Add(mask);
        }
Ejemplo n.º 19
0
        public string SendEmail(
            string message,
            string subject,
            string inReplyTo,
            IBotUser recipient,
            Dictionary <string, string> extraHeaders)
        {
            if (this.appConfig.EmailConfiguration == null)
            {
                this.logger.Debug("Not sending email; email configuration is disabled");
                return(null);
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                this.logger.Error("No subject specified in outbound email!");
                return(null);
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                this.logger.Error("No message specified in outbound email!");
                return(null);
            }

            if (string.IsNullOrWhiteSpace(recipient.EmailAddress))
            {
                this.logger.Info("No recipient address provided!");
                return(null);
            }

            var signaturePattern = string.Format(
                this.templates.EmailSignature,
                recipient.Identifier.Substring(3),
                this.freenodeClient.Nickname,
                this.appConfig.CommandPrefix,
                this.appConfig.PrivacyPolicy);

            var builder = new StringBuilder();

            builder.Append(this.templates.EmailGreeting);
            builder.Append(message);
            builder.Append(signaturePattern);

            var subjectPrefix = this.appConfig.EmailConfiguration.SubjectPrefix;

            subjectPrefix = subjectPrefix == null ? string.Empty : subjectPrefix.TrimEnd() + " ";

            return(this.emailSender.SendEmail(
                       this.appConfig.EmailConfiguration.Sender,
                       recipient.EmailAddress,
                       string.Format("{0}{1}", subjectPrefix, subject),
                       builder.ToString(),
                       this.appConfig.EmailConfiguration.Hostname,
                       this.appConfig.EmailConfiguration.Port,
                       this.appConfig.EmailConfiguration.Username,
                       this.appConfig.EmailConfiguration.Password,
                       this.appConfig.EmailConfiguration.Thumbprint,
                       inReplyTo,
                       extraHeaders
                       ));
        }
Ejemplo n.º 20
0
 public bool IsSubscribedToChannel(IBotUser botUser, IIrcChannel channel)
 {
     return(this.GetUserSubscriptionsToChannel(botUser).Any(x => x.Equals(channel)));
 }
Ejemplo n.º 21
0
 public UserIdentity(IBotUser botUser)
 {
     this.botUser = botUser;
 }
Ejemplo n.º 22
0
        public void CheckThrows(IBotUser user, bool defaultAllowed = true)
        {
            if(!HasAllowed)
                if(defaultAllowed)
                    return;
                else
                    throw new InvalidOperationException("Not allowed.");

            if(!Allowed)
                throw new InvalidOperationException("Not allowed.");

            if(!HasLimit || !HasTimespan)
                return;

            CheckLimitReset(user);

            if(!PeekLimit(user))
                throw new InvalidOperationException("Not allowed, too many attempts.");
        }
Ejemplo n.º 23
0
 public bool IsSubscribedToStalk(IBotUser botUser, IIrcChannel channel, IStalk stalk)
 {
     return(this.GetUserSubscriptionsToStalk(channel, stalk)
            .Where(x => x.IsSubscribed)
            .Any(x => Equals(x.BotUser, botUser)));
 }
Ejemplo n.º 24
0
        private bool PeekLimit(IBotUser user)
        {
            ushort limit;
            if(_limit == null || !_limit.HasValue)
                limit = _defaultLimit.Value;
            else
                limit = _limit.Value;

            if(_currentItemsPerTimespan.GetOrCreate(user, () => (ushort)0) < limit)
            {
                ++_currentItemsPerTimespan[user];
                return true;
            }

            ++_currentItemsPerTimespan[user];
            return false;
        }