summaryrefslogtreecommitdiffstats
path: root/askbot/models/reply_by_email.py
blob: 0d187b462155499d73beb6959bbf7cb862d2e843 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from datetime import datetime
import random
import string

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _

from askbot.models.post import Post
from askbot.models.base import BaseQuerySetManager
from askbot.conf import settings as askbot_settings



class ReplyAddressManager(BaseQuerySetManager):

    def get_unused(self, address):
        return self.get(address = address, used_at__isnull = True)
    
    def create_new(self, post, user):
        reply_address = ReplyAddress(post = post, user = user, allowed_from_email = user.email)
        while True:
            reply_address.address = ''.join(random.choice(string.letters +
                string.digits) for i in xrange(random.randint(12, 25)))
            if self.filter(address = reply_address.address).count() == 0:
                break
        reply_address.save()
        return reply_address
			

class ReplyAddress(models.Model):
    address = models.CharField(max_length = 25, unique = True)
    post = models.ForeignKey(Post)
    user = models.ForeignKey(User)
    allowed_from_email = models.EmailField(max_length = 150)
    used_at = models.DateTimeField(null = True, default = None)

    objects = ReplyAddressManager()


    class Meta:
        app_label = 'askbot'
        db_table = 'askbot_replyaddress'

    def create_reply(self, content):
        result = None
        if self.post.post_type == 'answer' or self.post.post_type == 'comment':
            result = self.user.post_comment(self.post, content)
        elif self.post.post_type == 'question':
            wordcount = len(content.rsplit())
            if wordcount > askbot_settings.MIN_WORDS_FOR_ANSWER_BY_EMAIL:
                result = self.user.post_answer(self.post, content)
            else:
                result = self.user.post_comment(self.post, content)
        self.used_at = datetime.now()
        self.save()
        return result


#TODO move this function to a more appropriate module
def process_reply_email(message, address, host):
    reply_address = ReplyAddress.objects.get_unused(address)
    separator = _("======= Reply above this line. ====-=-=")
    reply_part = message.body().split(separator)[0]
    reply_address.create_reply(reply_part)