1
# coding utf-8
2
# classes/sweet.py
3
# class:: Sweet
4
5
from flask import current_app
6
from datetime import datetime
7
8
from swtstore.classes.database import db
9
# custom SQLAlchemy type JSONType
10
from swtstore.classes.models.types import JSONType
11
from swtstore.classes.utils import urlnorm # normalize URLs
12
from swtstore.classes.models import Context, User
13
14
class Sweet(db.Model):
15
    """ customary docstring """
16
17
    __tablename__ = 'sweets'
18
19
    id = db.Column(db.Integer, primary_key=True)
20
21
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
22
    who = db.relationship('User')
23
24
    context_id = db.Column(db.Integer, db.ForeignKey('contexts.id'))
25
    what = db.relationship('Context')
26
27
    where = db.Column(db.UnicodeText, nullable=False)
28
29
    how = db.Column(JSONType)
30
31
    created = db.Column(db.DateTime, default=datetime.utcnow)
32
33
34
    def __init__(self, who, what, where, how):
35
        current_app.logger.info('initing sweet..')
36
        self.who = who
37
        self.what = what
38
        self.where = urlnorm(where)
39
        self.how = how
40
41
42
    def __repr__(self):
43
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
44
                                                        self.what, self.where)
45
46
    def __str__(self):
47
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
48
                                                        self.what, self.where)
49
50
    # Update the sweet - only 'how' and 'where' fields can be updated
51
    def update(self, **kwargs):
52
        if kwargs.get('how'):
53
            self.how = kwargs.get('how')
54
            self.persist()
55
        if kwargs.get('where'):
56
            self.where = kwargs.get('where')
57
            self.persist()
58
59
        return None
60
61
62
    # create multiple sweets from a list of JSON
63
    @staticmethod
64
    def createSweets(who, payload):
65
        # the payload has to be a list; a list of swts
66
        for each in payload:
67
            if 'what' not in each and 'where' not in\
68
                each and 'how' not in each:
69
70
                raise InvalidPayload('Invalid payload %s \n for creating\
71
                                     mutiple sweets' % (each))
72
                return None
73
74
        # all ok. create swts from the list now
75
        swts = []
76
        for each in payload:
77
78
            what = Context.getByName(each['what'])
79
80
            if what is None:
81
                current_app.logger.info('Context "%s" do not exist. Aborting',
82
                                    what)
83
                g.error = 'Context do not exist'
84
                abort(400) # this context doesn't exist!
85
86
            current_app.logger.debug('SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----',
87
                                 who, what, each['where'], each['how'])
88
89
            new_sweet = Sweet(who, what, each['where'], each['how'])
90
91
            new_sweet.persist()
92
            current_app.logger.debug('New Sweet %s', new_sweet)
93
            swts.append(new_sweet)
94
95
        return swts
96
97
    # get Sweets for frontend
98
    @staticmethod
99
    def getFrontendSwts():
100
        return Sweet.query.order_by(Sweet.created.desc()).all()
101
102
    # get all sweets authored by a particular user
103
    @staticmethod
104
    def getByCreator(user):
105
        return Sweet.query.filter_by(who=user).\
106
                order_by(Sweet.created.desc()).all()
107
108
    # allow to query all sweets based on "who", "what" and "where" params
109
    @staticmethod
110
    def queryByAll(params):
111
        if params.get('who'):
112
            params['who'] = User.getByName(params['who'])
113
        if params.get('what'):
114
            params['what'] = Context.getByName(params['what'])
115
116
        return Sweet.query.filter_by(**params).all()
117
118
    # return a dictionary of data members
119
    def to_dict(self):
120
        return {
121
            'id': self.id,
122
            'who': self.who.username,
123
            'user_id': self.user_id,
124
            'what': self.what.name,
125
            'context_id': self.context_id,
126
            'where': self.where,
127
            'how': self.how,
128
            #'created': self.created.isoformat()
129
            'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'),
130
        }
131
132
133
    # create and persist the sweet to the database
134
    def persist(self):
135
136
        current_app.logger.debug('Commiting sweet %s to db', self)
137
        db.session.add(self)
138
        db.session.commit()