Ejemplo n.º 1
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/r/" + subreddit.name
    if days:
        subject = "you've been temporarily banned from %(subreddit)s"
        message = ("you have been temporarily banned from posting to "
            "%(subreddit)s. this ban will last for %(duration)s days.")
    else:
        subject = "you've been banned from %(subreddit)s"
        message = "you have been banned from posting to %(subreddit)s."

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + ("you can contact the moderators regarding your ban "
        "by replying to this message. **warning**: using other accounts to "
        "circumvent a subreddit ban is considered a violation of reddit's "
        "[site rules](/rules) and can result in being banned from reddit "
        "entirely.")

    item, inbox_rel = Message._new(
        mod, user, subject, message, request.ip, sr=subreddit, from_sr=True,
        can_send_email=False)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 2
0
def send_system_message(user, subject, body, system_user=None,
                        distinguished='admin', repliable=False,
                        add_to_sent=True, author=None):
    from r2.lib.db import queries

    if system_user is None:
        system_user = Account.system_user()
    if not system_user:
        g.log.warning("Can't send system message "
                      "- invalid system_user or g.system_user setting")
        return
    if not author:
        author = system_user

    item, inbox_rel = Message._new(author, user, subject, body,
                                   ip='0.0.0.0')
    item.distinguished = distinguished
    item.repliable = repliable
    item.display_author = system_user._id
    item._commit()

    try:
        queries.new_message(item, inbox_rel, add_to_sent=add_to_sent)
    except MemcachedError:
        raise MessageError('reddit_inbox')
Ejemplo n.º 3
0
def send_system_message(user,
                        subject,
                        body,
                        system_user=None,
                        distinguished='admin',
                        repliable=False,
                        add_to_sent=True,
                        author=None,
                        signed=False):
    from r2.lib.db import queries

    if system_user is None:
        system_user = Account.system_user()
    if not system_user:
        g.log.warning("Can't send system message "
                      "- invalid system_user or g.system_user setting")
        return
    if not author:
        author = system_user

    item, inbox_rel = Message._new(author, user, subject, body, ip='0.0.0.0')
    item.distinguished = distinguished
    item.repliable = repliable
    item.display_author = system_user._id
    item.signed = signed
    item._commit()

    try:
        queries.new_message(item, inbox_rel, add_to_sent=add_to_sent)
    except MemcachedError:
        raise MessageError('reddit_inbox')
Ejemplo n.º 4
0
    def POST_traffic_viewer(self, form, jquery, user, thing):
        """
        Adds a user to the list of users allowed to view a promoted
        link's traffic page.
        """
        if not form.has_errors("name",
                               errors.USER_DOESNT_EXIST, errors.NO_USER):
            form.set_inputs(name="")
            form.set_html(".status:first", _("added"))
            if promote.add_traffic_viewer(thing, user):
                user_row = TrafficViewerList(thing).user_row('traffic_viewer', user)
                jquery(".traffic_viewer-table").show(
                    ).find("table").insert_table_rows(user_row)

                # send the user a message
                msg = user_added_messages['traffic']['pm']['msg']
                subj = user_added_messages['traffic']['pm']['subject']
                if msg and subj:
                    d = dict(url=thing.make_permalink_slow(),
                             traffic_url=promote.promo_traffic_url(thing),
                             title=thing.title)
                    msg = msg % d
                    item, inbox_rel = Message._new(c.user, user,
                                                   subj, msg, request.ip)
                    queries.new_message(item, inbox_rel)
Ejemplo n.º 5
0
    def POST_traffic_viewer(self, form, jquery, user, thing):
        """
        Adds a user to the list of users allowed to view a promoted
        link's traffic page.
        """
        if not form.has_errors("name", errors.USER_DOESNT_EXIST,
                               errors.NO_USER):
            form.set_inputs(name="")
            form.set_html(".status:first", _("added"))
            if promote.add_traffic_viewer(thing, user):
                user_row = TrafficViewerList(thing).user_row(user)
                jquery("#traffic-table").show().find(
                    "table").insert_table_rows(user_row)

                # send the user a message
                msg = strings.msg_add_friend.get("traffic")
                subj = strings.subj_add_friend.get("traffic")
                if msg and subj:
                    d = dict(url=thing.make_permalink_slow(),
                             traffic_url=promote.promo_traffic_url(thing),
                             title=thing.title)
                    msg = msg % d
                    subk = msg % d
                    item, inbox_rel = Message._new(c.user, user, subj, msg,
                                                   request.ip)
                    if g.write_query_queue:
                        queries.new_message(item, inbox_rel)
Ejemplo n.º 6
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/r/" + subreddit.name
    if days:
        subject = "you've been temporarily banned from %(subreddit)s"
        message = ("you have been temporarily banned from posting to "
            "%(subreddit)s. this ban will last for %(duration)s days.")
    else:
        subject = "you've been banned from %(subreddit)s"
        message = "you have been banned from posting to %(subreddit)s."

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + ("you can contact the moderators regarding your ban "
        "by replying to this message. **warning**: using other accounts to "
        "circumvent a subreddit ban is considered a violation of reddit's "
        "[site rules](/help/contentpolicy#section_prohibited_behavior) "
        "and can result in the "
        "[suspension](https://reddit.zendesk.com/hc/articles/205687686) "
        "of your reddit account.")

    item, inbox_rel = Message._new(mod, user, subject, message, request.ip,
        sr=subreddit, from_sr=True)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 7
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/r/" + subreddit.name
    if days:
        subject = "you've been temporarily banned from %(subreddit)s"
        message = ("you have been temporarily banned from posting to "
                   "%(subreddit)s. this ban will last for %(duration)s days.")
    else:
        subject = "you've been banned from %(subreddit)s"
        message = "you have been banned from posting to %(subreddit)s."

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + (
        "you can contact the moderators regarding your ban "
        "by replying to this message. **warning**: using other accounts to "
        "circumvent a subreddit ban is considered a violation of reddit's "
        "[site rules](/rules) and can result in being banned from reddit "
        "entirely.")

    item, inbox_rel = Message._new(mod,
                                   user,
                                   subject,
                                   message,
                                   request.ip,
                                   sr=subreddit,
                                   from_sr=True)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 8
0
def notify_user_added(rel_type, author, user, target, message=None):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type == "banned" and not user.has_interacted_with(target):
            return

        if rel_type == "banned" and message:
            msg += "\n\n" + N_("note from the moderators:\n\n\"%(message)s\"")
            msg %= {'message': message}

        if rel_type in ("banned", "moderator_invite"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(author,
                                           user,
                                           subject,
                                           msg,
                                           request.ip,
                                           sr=target,
                                           from_sr=True)
        else:
            item, inbox_rel = Message._new(author, user, subject, msg,
                                           request.ip)

        queries.new_message(item, inbox_rel)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author,
                                       target,
                                       subject,
                                       msg,
                                       request.ip,
                                       sr=target)
        queries.new_message(item, inbox_rel)
Ejemplo n.º 9
0
def notify_user_added(rel_type, author, user, target):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type in ("moderator_invite", "contributor"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(author,
                                           user,
                                           subject,
                                           msg,
                                           request.ip,
                                           sr=target,
                                           from_sr=True,
                                           can_send_email=False)
        else:
            item, inbox_rel = Message._new(author,
                                           user,
                                           subject,
                                           msg,
                                           request.ip,
                                           can_send_email=False)

        queries.new_message(item, inbox_rel, update_modmail=False)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author,
                                       target,
                                       subject,
                                       msg,
                                       request.ip,
                                       sr=target)
        queries.new_message(item, inbox_rel)
Ejemplo n.º 10
0
    def perform_actions(self, item, data):
        """Execute all the rule's actions against the item."""
        for key, target in self.targets.iteritems():
            target_item = self.get_target_item(item, data, key)
            target.perform_actions(target_item, data)

        if self.comment:
            comment = self.build_message(self.comment, item, data, disclaimer=True)

            # TODO: shouldn't have to do all this manually
            if isinstance(item, Comment):
                link = data["link"]
                parent_comment = item
            else:
                link = item
                parent_comment = None
            new_comment, inbox_rel = Comment._new(
                ACCOUNT, link, parent_comment, comment, None)
            new_comment.distinguished = "yes"
            new_comment._commit()
            queries.queue_vote(ACCOUNT, new_comment, True, None)
            queries.new_comment(new_comment, inbox_rel)

            g.stats.simple_event("automoderator.comment")

        if self.modmail:
            message = self.build_message(self.modmail, item, data, permalink=True)
            subject = replace_placeholders(
                self.modmail_subject, data, self.matches)
            subject = subject[:100]

            new_message, inbox_rel = Message._new(ACCOUNT, data["subreddit"],
                subject, message, None)
            new_message.distinguished = "yes"
            new_message._commit()
            queries.new_message(new_message, inbox_rel)

            g.stats.simple_event("automoderator.modmail")

        if self.message and not data["author"]._deleted:
            message = self.build_message(self.message, item, data,
                disclaimer=True, permalink=True)
            subject = replace_placeholders(
                self.message_subject, data, self.matches)
            subject = subject[:100]

            new_message, inbox_rel = Message._new(ACCOUNT, data["author"],
                subject, message, None)
            queries.new_message(new_message, inbox_rel)

            g.stats.simple_event("automoderator.message")

        PerformedRulesByThing.mark_performed(item, self)
Ejemplo n.º 11
0
    def POST_adduser(self, lang, a):
        from r2.lib.db import queries
        if a and Translator.exists(lang):
            tr = get_translator(locale = lang)
            tr.author.add(a.name)
            tr.save()

            # send the user a message
            body = Translator_Message(lang, a).render("html")
            subject = "Thanks for offering to help translate!"
            m, inbox_rel = Message._new(c.user, a, subject, body, request.ip)
            queries.new_message(m, inbox_rel)

        return self.redirect("/admin/i18n")
Ejemplo n.º 12
0
    def POST_adduser(self, lang, a):
        from r2.lib.db import queries
        if a and Translator.exists(lang):
            tr = get_translator(locale=lang)
            tr.author.add(a.name)
            tr.save()

            # send the user a message
            body = Translator_Message(lang, a).render("html")
            subject = "Thanks for offering to help translate!"
            m, inbox_rel = Message._new(c.user, a, subject, body, request.ip)
            queries.new_message(m, inbox_rel)

        return self.redirect("/admin/i18n")
Ejemplo n.º 13
0
def notify_user_added(rel_type, author, user, target):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type in ("moderator_invite", "contributor"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(
                author, user, subject, msg, request.ip, sr=target, from_sr=True,
                can_send_email=False, is_auto_modmail=True)
        else:
            item, inbox_rel = Message._new(
                author, user, subject, msg, request.ip, can_send_email=False)

        queries.new_message(item, inbox_rel, update_modmail=False)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            # Don't send the separate moderator invite message from the
            # system user to new modmail, since the one sent to the invitee
            # will already show up in there.
            # TODO: when new modmail is fully deployed, the "modmail" dict
            # should be completely removed from the moderator_invite section
            # of user_added_messages, and this check removed.
            if feature.is_enabled('new_modmail', subreddit=target.name):
                return

            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author, target, subject, msg,
                                       request.ip, sr=target,
                                       is_auto_modmail=True)
        queries.new_message(item, inbox_rel)
Ejemplo n.º 14
0
def send_system_message(user, subject, body):
    from r2.lib.db import queries

    system_user = Account.system_user()
    if not system_user:
        g.log.warning("g.system_user isn't set properly. Can't send system message.")
        return

    item, inbox_rel = Message._new(system_user, user, subject, body,
                                   ip='0.0.0.0')
    item.distinguished = 'admin'
    item.repliable = False
    item._commit()

    queries.new_message(item, inbox_rel)
Ejemplo n.º 15
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/" + g.brander_community_abbr + "/" + subreddit.name
    if days:
        subject = "You've been temporarily banned from participating in %(subreddit)s"
        message = ("You have been temporarily banned from participating in "
                   "%(subreddit)s. This ban will last for %(duration)s days. ")
    else:
        subject = "You've been banned from participating in %(subreddit)s"
        message = "You have been banned from participating in %(subreddit)s. "

    message += ("You can still view and subscribe to %(subreddit)s, but you "
                "won't be able to post or comment.")

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'Note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + (
        "If you have a question regarding your ban, you can "
        "contact the moderator team for %(subreddit)s by replying to this "
        "message.") % {
            "subreddit": sr_name
        }

    message += "\n\n" + (
        "**Reminder from the %(site_name)s staff**: If you use "
        "another account to circumvent this sub ban, that will be "
        "considered a violation of [the Content Policy](/s/SaidIt/comments/j1/the_saiditnet_terms_and_content_policy/) "
        "and can result in your account being suspended"
        "from the site as a whole.") % {
            "site_name": g.brander_site
        }

    item, inbox_rel = Message._new(mod,
                                   user,
                                   subject,
                                   message,
                                   request.ip,
                                   sr=subreddit,
                                   from_sr=True,
                                   can_send_email=False)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 16
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/r/" + subreddit.name
    if days:
        subject = "You've been temporarily banned from participating in %(subreddit)s"
        message = ("You have been temporarily banned from participating in "
                   "%(subreddit)s. This ban will last for %(duration)s days. ")
    else:
        subject = "You've been banned from participating in %(subreddit)s"
        message = "You have been banned from participating in %(subreddit)s. "

    message += ("You can still view and subscribe to %(subreddit)s, but you "
                "won't be able to post or comment.")

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'Note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + (
        "If you have a question regarding your ban, you can "
        "contact the moderator team for %(subreddit)s by replying to this "
        "message.") % {
            "subreddit": sr_name
        }

    message += "\n\n" + (
        "**Reminder from the Reddit staff**: If you use "
        "another account to circumvent this subreddit ban, that will be "
        "considered a violation of [the Content Policy](/help/contentpolicy#section_prohibited_behavior) "
        "and can result in your account being [suspended](https://reddit.zendesk.com/hc/en-us/articles/205687686) "
        "from the site as a whole.")

    item, inbox_rel = Message._new(mod,
                                   user,
                                   subject,
                                   message,
                                   request.ip,
                                   sr=subreddit,
                                   from_sr=True,
                                   can_send_email=False,
                                   is_auto_modmail=True)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 17
0
def notify_user_added(rel_type, author, user, target, message=None):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type == "banned" and not user.has_interacted_with(target):
            return

        if rel_type == "banned" and message:
            msg += "\n\n" + N_("note from the moderators:\n\n\"%(message)s\"")
            msg %= {'message': message}

        if rel_type in ("banned", "moderator_invite"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(author, user, subject, msg, request.ip,
                                           sr=target, from_sr=True)
        else:
            item, inbox_rel = Message._new(author, user, subject, msg, request.ip)

        queries.new_message(item, inbox_rel, update_modmail=False)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author, target, subject, msg,
                                       request.ip, sr=target)
        queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 18
0
def send_system_message(user, subject, body, system_user=None, distinguished="admin", repliable=False):
    from r2.lib.db import queries

    if system_user is None:
        system_user = Account.system_user()
    if not system_user:
        g.log.warning("Can't send system message " "- invalid system_user or g.system_user setting")
        return

    item, inbox_rel = Message._new(system_user, user, subject, body, ip="0.0.0.0")
    item.distinguished = distinguished
    item.repliable = repliable
    item._commit()

    try:
        queries.new_message(item, inbox_rel)
    except MemcachedError:
        raise MessageError("reddit_inbox")
Ejemplo n.º 19
0
def send_mod_removal_message(subreddit, mod, user):
    sr_name = "/r/" + subreddit.name
    subject = "You've been removed as a moderator from %(subreddit)s"
    message = (
        "You have been removed as a moderator from %(subreddit)s.  "
        "If you have a question regarding your removal, you can "
        "contact the moderator team for %(subreddit)s by replying to this "
        "message."
    )
    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name}

    item, inbox_rel = Message._new(
        mod, user, subject, message, request.ip,
        sr=subreddit,
        from_sr=True,
        can_send_email=False,
    )
    queries.new_message(item, inbox_rel, update_modmail=True)
Ejemplo n.º 20
0
def notify_user_added(rel_type, author, user, target):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type in ("moderator_invite", "contributor"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(
                author, user, subject, msg, request.ip, sr=target, from_sr=True,
                can_send_email=False)
        else:
            item, inbox_rel = Message._new(
                author, user, subject, msg, request.ip, can_send_email=False)

        queries.new_message(item, inbox_rel, update_modmail=False)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author, target, subject, msg,
                                       request.ip, sr=target)
        queries.new_message(item, inbox_rel)
Ejemplo n.º 21
0
def send_mod_removal_message(subreddit, mod, user):
    sr_name = "/r/" + subreddit.name
    subject = "You've been removed as a moderator from %(subreddit)s"
    message = (
        "You have been removed as a moderator from %(subreddit)s.  "
        "If you have a question regarding your removal, you can "
        "contact the moderator team for %(subreddit)s by replying to this "
        "message.")
    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name}

    item, inbox_rel = Message._new(
        mod,
        user,
        subject,
        message,
        request.ip,
        sr=subreddit,
        from_sr=True,
        can_send_email=False,
    )
    queries.new_message(item, inbox_rel, update_modmail=True)
Ejemplo n.º 22
0
def send_ban_message(subreddit, mod, user, note=None, days=None, new=True):
    sr_name = "/r/" + subreddit.name
    if days:
        subject = "You've been temporarily banned from participating in %(subreddit)s"
        message = ("You have been temporarily banned from participating in "
            "%(subreddit)s. This ban will last for %(duration)s days. ")
    else:
        subject = "You've been banned from participating in %(subreddit)s"
        message = "You have been banned from participating in %(subreddit)s. "

    message += ("You can still view and subscribe to %(subreddit)s, but you "
                "won't be able to post or comment.")

    if not new:
        subject = "Your ban from %(subreddit)s has changed"

    subject %= {"subreddit": sr_name}
    message %= {"subreddit": sr_name, "duration": days}

    if note:
        message += "\n\n" + 'Note from the moderators:'
        message += "\n\n" + blockquote_text(note)

    message += "\n\n" + ("If you have a question regarding your ban, you can "
        "contact the moderator team for %(subreddit)s by replying to this "
        "message.") % {"subreddit": sr_name}

    message += "\n\n" + ("**Reminder from the Reddit staff**: If you use "
        "another account to circumvent this subreddit ban, that will be "
        "considered a violation of [the Content Policy](/help/contentpolicy#section_prohibited_behavior) "
        "and can result in your account being [suspended](https://reddit.zendesk.com/hc/en-us/articles/205687686) "
        "from the site as a whole.")

    item, inbox_rel = Message._new(
        mod, user, subject, message, request.ip, sr=subreddit, from_sr=True,
        can_send_email=False, is_auto_modmail=True)
    queries.new_message(item, inbox_rel, update_modmail=False)
Ejemplo n.º 23
0
def send_notification_message(user, target, subject, message, ip):
    m, inbox_rel = Message._new(user, target, subject, message, ip, in_box='notifications')
    amqp.add_item('new_notification', m._fullname)
    queries.new_message(m, inbox_rel)
Ejemplo n.º 24
0
    def POST_mod_messages(self, conversation, msg_body, is_author_hidden,
                          is_internal):
        """Creates a new message for a particular ModmailConversation

        URL Params:
        conversation_id -- id of the conversation to post a new message to

        POST Params:
        body            -- this is the message body
        isAuthorHidden  -- boolean on whether to hide author, i.e. respond as
                           the subreddit
        isInternal      -- boolean to signify a moderator only message
        """
        self._validate_vmodconversation()

        sr = Subreddit._by_fullname(conversation.owner_fullname)
        self._feature_enabled_check(sr)

        # make sure the user is not muted before posting a message
        if sr.is_muted(c.user):
            return self.send_error(400, errors.USER_MUTED)

        if conversation.is_internal and not is_internal:
            is_internal = True

        is_mod = sr.is_moderator(c.user)
        if not is_mod and is_author_hidden:
            return self.send_error(
                403,
                errors.MOD_REQUIRED,
                fields='isAuthorHidden',
            )
        elif not is_mod and is_internal:
            return self.send_error(
                403,
                errors.MOD_REQUIRED,
                fields='isInternal',
            )

        try:
            if not conversation.is_internal and not conversation.is_auto:
                participant = conversation.get_participant_account()

                if participant and sr.is_muted(participant):
                    return self.send_error(
                        400,
                        errors.MUTED_FROM_SUBREDDIT,
                    )
        except NotFound:
            pass

        try:
            new_message = conversation.add_message(
                c.user,
                msg_body,
                is_author_hidden=is_author_hidden,
                is_internal=is_internal,
            )
        except:
            return self.send_error(500, errors.MODMAIL_MESSAGE_NOT_SAVED)

        # Add the message to the legacy messaging system as well (unless it's
        # an internal message on a non-internal conversation, since we have no
        # way to hide specific messages from the external participant)
        legacy_incompatible = is_internal and not conversation.is_internal
        if (conversation.legacy_first_message_id and not legacy_incompatible):
            first_message = Message._byID(conversation.legacy_first_message_id)
            subject = conversation.subject
            if not subject.startswith('re: '):
                subject = 're: ' + subject

            # Retrieve the participant to decide whether to send the message
            # to the sr or to the participant. If the currently logged in user
            # is the same as the participant then address the message to the
            # sr.
            recipient = sr
            if not is_internal:
                try:
                    participant = (
                        ModmailConversationParticipant.get_participant(
                            conversation.id))

                    is_participant = (
                        (c.user._id == participant.account_id)
                        and not sr.is_moderator_with_perms(c.user, 'mail'))

                    if not is_participant:
                        recipient = Account._byID(participant.account_id)
                except NotFound:
                    pass

            message, inbox_rel = Message._new(
                c.user,
                recipient,
                subject,
                msg_body,
                request.ip,
                parent=first_message,
                from_sr=is_author_hidden,
                create_modmail=False,
            )
            queries.new_message(message, inbox_rel)

        serializable_convo = conversation.to_serializable(
            entity=sr,
            all_messages=True,
            current_user=c.user,
        )
        messages = serializable_convo.pop('messages')

        g.events.new_modmail_event(
            'ss.send_modmail_message',
            conversation,
            message=new_message,
            msg_author=c.user,
            sr=sr,
            request=request,
            context=c,
        )

        response.status_code = 201
        return simplejson.dumps({
            'conversation': serializable_convo,
            'messages': messages,
        })
Ejemplo n.º 25
0
    def POST_zendeskreply(self):
        request_body = request.POST
        recipient = request_body["recipient"]
        sender_email = request_body["sender"]
        from_ = request_body["from"]
        subject = request_body["subject"]
        body_plain = request_body["body-plain"]
        stripped_text = request_body["stripped-text"]
        stripped_signature = request_body["stripped-signature"]
        timestamp = request_body["timestamp"]
        token = request_body["token"]
        signature = request_body["signature"]
        email_id = request_body["Message-Id"]

        if not validate_mailgun_webhook(timestamp, token, signature):
            # per Mailgun docs send a 406 so the message won't be retried
            abort(406, "invalid signature")

        message_id36 = parse_and_validate_reply_to_address(recipient)

        if not message_id36:
            # per Mailgun docs send a 406 so the message won't be retried
            abort(406, "invalid message")

        parent = Message._byID36(message_id36, data=True)
        to = Account._byID(parent.author_id, data=True)
        sr = Subreddit._byID(parent.sr_id, data=True)
        body = self.get_snipped_body(stripped_text, stripped_signature)

        try:
            markdown_souptest(body)
        except SoupError:
            g.log.warning("bad markdown in modmail email: %s", body)
            abort(406, "invalid body")

        if parent.get_muted_user_in_conversation():
            queue_blocked_muted_email(sr, parent, sender_email, email_id)
            return

        # keep the subject consistent
        message_subject = parent.subject
        if not message_subject.startswith("re: "):
            message_subject = "re: " + message_subject

        # from_ is like '"NAME (GROUP)" <*****@*****.**>'
        match = re.search("\"(?P<name>\w+) [\w ()]*\"", from_)
        from_sr = True
        author = Account.system_user()

        if match and match.group("name") in g.live_config['modmail_account_map']:
            zendesk_name = match.group("name")
            moderator_name = g.live_config['modmail_account_map'][zendesk_name]
            moderator = Account._by_name(moderator_name)
            if sr.is_moderator_with_perms(moderator, "mail"):
                author = moderator
                from_sr = False

        message, inbox_rel = Message._new(
            author=author,
            to=to,
            subject=message_subject,
            body=body,
            ip='0.0.0.0',
            parent=parent,
            sr=sr,
            from_sr=from_sr,
            can_send_email=False,
            sent_via_email=True,
            email_id=email_id,
        )
        message._commit()
        queries.new_message(message, inbox_rel)
        g.stats.simple_event("mailgun.incoming.success")
        g.stats.simple_event("modmail_email.incoming_email")
Ejemplo n.º 26
0
def notify_user_added(rel_type, author, user, target):
    msgs = user_added_messages.get(rel_type)
    if not msgs:
        return

    srname = target.path.rstrip("/")
    d = {
        "url": srname,
        "title": "%s: %s" % (srname, target.title),
        "author": "/u/" + author.name,
        "user": "******" + user.name,
    }

    if "pm" in msgs and author != user:
        subject = msgs["pm"]["subject"] % d
        msg = msgs["pm"]["msg"] % d

        if rel_type in ("moderator_invite", "contributor"):
            # send the message from the subreddit
            item, inbox_rel = Message._new(author,
                                           user,
                                           subject,
                                           msg,
                                           request.ip,
                                           sr=target,
                                           from_sr=True,
                                           can_send_email=False,
                                           is_auto_modmail=True)
        else:
            item, inbox_rel = Message._new(author,
                                           user,
                                           subject,
                                           msg,
                                           request.ip,
                                           can_send_email=False)

        queries.new_message(item, inbox_rel, update_modmail=False)

    if "modmail" in msgs:
        subject = msgs["modmail"]["subject"] % d
        msg = msgs["modmail"]["msg"] % d

        if rel_type == "moderator_invite":
            # Don't send the separate moderator invite message from the
            # system user to new modmail, since the one sent to the invitee
            # will already show up in there.
            # TODO: when new modmail is fully deployed, the "modmail" dict
            # should be completely removed from the moderator_invite section
            # of user_added_messages, and this check removed.
            if feature.is_enabled('new_modmail', subreddit=target.name):
                return

            modmail_author = Account.system_user()
        else:
            modmail_author = author

        item, inbox_rel = Message._new(modmail_author,
                                       target,
                                       subject,
                                       msg,
                                       request.ip,
                                       sr=target,
                                       is_auto_modmail=True)
        queries.new_message(item, inbox_rel)
Ejemplo n.º 27
0
    def POST_zendeskreply(self):
        request_body = request.POST
        recipient = request_body["recipient"]
        sender_email = request_body["sender"]
        from_ = request_body["from"]
        subject = request_body["subject"]
        body_plain = request_body["body-plain"]
        stripped_text = request_body["stripped-text"]
        stripped_signature = request_body["stripped-signature"]
        timestamp = request_body["timestamp"]
        token = request_body["token"]
        signature = request_body["signature"]
        email_id = request_body["Message-Id"]

        if not validate_mailgun_webhook(timestamp, token, signature):
            # per Mailgun docs send a 406 so the message won't be retried
            abort(406, "invalid signature")

        message_id36 = parse_and_validate_reply_to_address(recipient)

        if not message_id36:
            # per Mailgun docs send a 406 so the message won't be retried
            abort(406, "invalid message")

        parent = Message._byID36(message_id36, data=True)
        to = Account._byID(parent.author_id, data=True)
        sr = Subreddit._byID(parent.sr_id, data=True)
        body = self.get_snipped_body(stripped_text, stripped_signature)

        try:
            markdown_souptest(body)
        except SoupError:
            g.log.warning("bad markdown in modmail email: %s", body)
            abort(406, "invalid body")

        if parent.get_muted_user_in_conversation():
            queue_blocked_muted_email(sr, parent, sender_email, email_id)
            return

        # keep the subject consistent
        message_subject = parent.subject
        if not message_subject.startswith("re: "):
            message_subject = "re: " + message_subject

        # from_ is like '"NAME (GROUP)" <*****@*****.**>'
        match = re.search("\"(?P<name>\w+) [\w ()]*\"", from_)
        from_sr = True
        author = Account.system_user()

        if match and match.group(
                "name") in g.live_config['modmail_account_map']:
            zendesk_name = match.group("name")
            moderator_name = g.live_config['modmail_account_map'][zendesk_name]
            moderator = Account._by_name(moderator_name)
            if sr.is_moderator_with_perms(moderator, "mail"):
                author = moderator
                from_sr = False

        message, inbox_rel = Message._new(
            author=author,
            to=to,
            subject=message_subject,
            body=body,
            ip='0.0.0.0',
            parent=parent,
            sr=sr,
            from_sr=from_sr,
            can_send_email=False,
            sent_via_email=True,
            email_id=email_id,
        )
        message._commit()
        queries.new_message(message, inbox_rel)
        g.stats.simple_event("mailgun.incoming.success")
        g.stats.simple_event("modmail_email.incoming_email")
Ejemplo n.º 28
0
    def POST_conversations(self, entity, subject, body, is_author_hidden, to):
        """Creates a new conversation for a particular SR

        This endpoint will create a ModmailConversation object as
        well as the first ModmailMessage within the ModmailConversation
        object.

        POST Params:
        srName          -- the human readable name of the subreddit
        subject         -- the subject of the first message in the conversation
        body            -- the body of the first message in the conversation
        isAuthorHidden  -- boolean on whether the mod name should be hidden
                           (only mods can use this flag)
        to              -- name of the user that a mod wants to create a convo
                           with (only mods can use this flag)
        """
        self._feature_enabled_check(entity)

        # make sure the user is not muted when creating a new conversation
        if entity.is_muted(c.user) and not c.user_is_admin:
            return self.send_error(400, errors.USER_MUTED)

        # validate post params
        if (errors.USER_BLOCKED, to) in c.errors:
            return self.send_error(400, errors.USER_BLOCKED, fields='to')
        elif (errors.USER_DOESNT_EXIST, to) in c.errors:
            return self.send_error(404, errors.USER_DOESNT_EXIST, fields='to')

        if to and not isinstance(to, Account):
            return self.send_error(
                422,
                errors.NO_SR_TO_SR_MESSAGE,
                fields='to',
            )

        # only mods can set a 'to' parameter
        if (not entity.is_moderator_with_perms(c.user, 'mail') and to):
            return self.send_error(403, errors.MOD_REQUIRED, fields='to')

        if to and entity.is_muted(to):
            return self.send_error(
                400,
                errors.MUTED_FROM_SUBREDDIT,
                fields='to',
            )

        try:
            conversation = ModmailConversation(
                entity,
                c.user,
                subject,
                body,
                is_author_hidden=is_author_hidden,
                to=to,
            )
        except MustBeAModError:
            return self.send_error(403,
                                   errors.MOD_REQUIRED,
                                   fields='isAuthorHidden')
        except Exception as e:
            g.log.error('Failed to save conversation: {}'.format(e))
            return self.send_error(500, errors.CONVERSATION_NOT_SAVED)

        # Create copy of the message in the legacy messaging system as well
        if to:
            message, inbox_rel = Message._new(
                c.user,
                to,
                subject,
                body,
                request.ip,
                sr=entity,
                from_sr=is_author_hidden,
                create_modmail=False,
            )
        else:
            message, inbox_rel = Message._new(
                c.user,
                entity,
                subject,
                body,
                request.ip,
                create_modmail=False,
            )
        queries.new_message(message, inbox_rel)
        conversation.set_legacy_first_message_id(message._id)

        # Get author associated account object for serialization
        # of the newly created conversation object
        authors = self._try_get_byID(conversation.author_ids,
                                     Account,
                                     ignore_missing=True)

        response.status_code = 201
        serializable_convo = conversation.to_serializable(authors,
                                                          entity,
                                                          all_messages=True,
                                                          current_user=c.user)
        messages = serializable_convo.pop('messages')
        mod_actions = serializable_convo.pop('modActions')

        g.events.new_modmail_event(
            'ss.send_modmail_message',
            conversation,
            message=conversation.messages[0],
            msg_author=c.user,
            sr=entity,
            request=request,
            context=c,
        )

        return simplejson.dumps({
            'conversation': serializable_convo,
            'messages': messages,
            'modActions': mod_actions,
        })