DailyPromptBot / minibot / db.py

  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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# The Daily Prompt Mini-Bot - A Shut Up and Write Project
# Author: Marc-Alexandre Chan <laogeodritt at arenthil.net>
#-------------------------------------------------------------------------------
#
# Copyright (c) 2012 Marc-Alexandre Chan. Licensed under the GNU GPL version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#-------------------------------------------------------------------------------

""" Database abstraction classes using the SQLAlchemy ORM module. """

from sqlalchemy import create_engine, Column, Boolean, SmallInteger, Integer,\
    String, Unicode, UnicodeText, DateTime, Date, TIMESTAMP
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.schema import CheckConstraint, ForeignKey
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta

from passlib.hash import pbkdf2_sha512
import hmac
from hashlib import sha512
from datetime import datetime
import logging
from os import makedirs
from os.path import isdir, dirname, realpath


class TablePrefixer(DeclarativeMeta):
    """ DeclarativeMeta class to add table prefix to table names, if applicable.
    """

    def __init__(self, classname, bases, dict_):
        return DeclarativeMeta.__init__(self, classname, bases, dict_)

        # TODO: get table prefixes working/runtime configurable without directly
        # depending on the global config. gconfig does not exist now.
        #if '__tablename__' in dict_ and gconfig.db.tableprefix != None:
        #    newname = gconfig.db.tableprefix + self.__tablename__
        #    self.__tablename__ = dict_['__tablename__'] = newname
        #return DeclarativeMeta.__init__(self, classname, bases, dict_)

Base = declarative_base(name='MinibotDatabase', metaclass=TablePrefixer)
Session = sessionmaker()


class User(Base):
    """ A user of the minibot application. """
    __tablename__ = 'users'
    r_id      = Column(String(8), primary_key=True)
    # https://github.com/reddit/reddit/blob/master/r2/r2/controllers/validator/validator.py
    # line 906 user_rx (validation regex): max length is 20
    uname     = Column(String(20), nullable=False)
    registered= Column(Boolean(), nullable=False, default=False)
    email     = Column(String(64), nullable=True, default='')

    # use set_password() to hash and set the password in the DB
    # should be stored output of passlib.pbkdf2_sha512
    _password = Column('password', String(199),
                    CheckConstraint('LENGTH(password) >= 190'), nullable=False)
    # password hashing configuration
    ROUNDS_DEFAULT = 16384
    SALT_SIZE = 64

    # posts - from Prompt.approver relationship

    def __init__(self, r_id, uname, plain_password=None, email=None,
        globsalt=None, rounds=ROUNDS_DEFAULT):
        """ Create a new User object. If no password is provided, the user is
        assumed unregistered. See set_password for ``globsalt`` and ``rounds``
        parameter descriptions. """
        self.r_id = r_id
        self.uname = uname
        if plain_password:
            self.registered = True
            self.set_password(plain_password, salt, globsalt, rounds)
        else:
            self.registered = False
            # won't be usable since registered=False
            self.set_password('default', globsalt, rounds)

        if email:
            self.email = email

    def set_password(self, password, globsalt=None, rounds=ROUNDS_DEFAULT):
        """ Hash a password and stores it. Optionally specify a global salt
        string ``globsalt`` (recommended). Without a ``globsalt``, the password
        is stored using PBKDF2 implemented using SHA512 and ``round`` rounds
        (default is 12000), with a salt of 64 bytes. With a ``globsalt``, the
        password is first keyed using HMAC with SHA512. ``globsalt`` is never
        stored in the database, and should be made part of application
        configuration separate from the database. """
        if globsalt:
            keyed_pass = hmac.new(globsalt, password, sha512).digest()
        else:
            keyed_pass = password
        self._password = pbkdf2_sha512.encrypt(keyed_pass,
                             salt_size=self.SALT_SIZE, rounds=rounds)

    def check_password(self, password, globsalt=None, rounds=ROUNDS_DEFAULT):
        """ Check whether a password is correct. """
        if globsalt:
            keyed_pass = hmac.new(globsalt, password, sha512).digest()
        else:
            keyed_pass = password
        return pbkdf2_sha512.verify(keyed_pass, self._password,
                    salt_size=self.SALT_SIZE, rounds=rounds)

    def __repr__(self):
        """ Return a human-readable representation of the User row. """
        return u"<User({r_id}, '{uname}', '{email}', {reg})>".format(
                r_id=self.r_id, uname=self.uname, email=self.email,
                reg='registered' if self.registered else 'unregistered')

    def __str__(self):
        """ Return a friendly string representing a User row. """
        return unicode(self).encode('utf8', 'replace')

    def __unicode__(self):
        """ Return a friendly string representing a User row. """
        parts = []
        parts.append(u"/u/{}".format(self.uname))
        if self.email:
            parts.append(u"<{}>".format(self.email))
        if not self.registered:
            parts.append(u"(unregistered)")
        return ' '.join(parts)


class Prompt(Base):
    """ A prompt and its related posting data (suggester, approver, status,
    time posted/to post, etc.). Mapped class for SQLAlchemy. All time data is in
    UTC. """
    __tablename__ = 'prompts'
    id          = Column(Integer(), primary_key=True, autoincrement=True)
    status      = Column(SmallInteger(),
        CheckConstraint('status>=0 AND status<=4'), nullable=False, default=0)
    submit_time = Column('t_submit', TIMESTAMP(), nullable=False,
                         default=datetime.utcnow)
    post_time   = Column('t_post', TIMESTAMP(), nullable=True, default=None)
    # https://github.com/reddit/reddit/blob/master/r2/r2/controllers/validator/validator.py
    # line 906 user_rx (validation regex): max length is 20
    user          = Column(Unicode(20), nullable=True, default=None)
    r_user_id     = Column(String(8), nullable=True, default=None)
    r_approver_id = Column(String(8), ForeignKey('users.r_id'), nullable=False)
    r_post_id     = Column(String(8), nullable=True, default=None)
    r_source_url  = Column(String(128), nullable=True, default=None)
    source_thread_id = Column(String(8), ForeignKey('suggestion_threads.id'),
                             nullable=True, default=None)
    r_source_id   = Column(String(12), nullable=True, default=None)
    title         = Column(Unicode(255), nullable=True, default=None)
    text          = Column(UnicodeText(), nullable=False)

    approver      = relationship('User',
                    backref=backref('posts', order_by=post_time))
    source_thread = relationship('SuggestionThread',
                    backref=backref('prompts', order_by=post_time))

    STATUS_TEXT = ['new', 'accepted', 'queued', 'posted', 'rejected']
    STATUS_NEW      = 0
    STATUS_ACCEPTED = 1
    STATUS_QUEUED   = 2
    STATUS_POSTED   = 3
    STATUS_REJECTED = 4

    def __init__(self, title, text, approver_id, submit_time=None,\
                 user=None, user_id=None, source_url=None, source_thread=None,
                 source_id=None):
        self.status        = self.STATUS_NEW
        self.title         = title
        self.text          = text
        self.submit_time   = submit_time if submit_time is not None\
                             else datetime.utcnow()
        self.user          = user
        self.r_user_id     = user_id
        self.r_approver_id = approver_id
        self.r_source_url  = source_url
        self.source_thread_id = source_thread
        self.r_source_id   = source_id

    def get_status_string(self):
        return self.STATUS_TEXT[self.status]

    def set_new(self):
        """ Set the prompt entry as unqueued. """
        self.status = self.STATUS_NEW
    def accept(self):
        """ Set the prompt entry as accepted for later queuing. """
        self.status = self.STATUS_ACCEPTED

    def reject(self):
        """ Set the prompt entry as rejected. """
        self.status = self.STATUS_REJECTED

    def queue(self, post_time):
        """ Set the prompt entry as queued for posting at the specified time. """
        self.status = self.STATUS_QUEUED
        self.post_time = post_time
        self.r_post_id = None

    def set_posted(self, post_id, post_time):
        """ Set the prompt entry as posted and store the post id and time.
        ``post_id`` is a string; ``post_time`` is a ``datetime`` object (in UTC)
        or a UNIX timestamp (float). """
        self.status = self.STATUS_POSTED
        self.r_post_id = post_id
        try:
            self.post_time = datetime.utcfromtimestamp(post_time)
        except ValueError:
            self.post_time = post_time

    def __repr__(self):
        """ Return a human-readable representation of the Prompt row. """
        return (u"<Prompt(id={id_:d}, status={status}, post_time={tpost}, "
               u"r_post_id={post_id}, submit_time={tsubmit}, "
               u"user='{user}', approver='{approver}', "
               u"title='{title}', text='{excerpt}')>").format(
                              id_=self.id,
                              status=self.get_status_string(),
                              tpost=unicode(self.post_time),
                              post_id=unicode(self.r_post_id),
                              tsubmit=unicode(self.submit_time),
                              user=self.user,
                              approver=self.approver.uname if self.approver else '',
                              title=self.title,
                              excerpt=self.text[0:128]\
                                     +('...' if len(self.text) > 128 else ''))


class SuggestionThread(Base):
    """ A prompt suggestion thread metadata, to track the posting and status
    of suggestion threads (whether to cull data from it, etc.). All time data
    is in UTC. """
    __tablename__ = 'suggestion_threads'
    id = Column(Integer(), primary_key=True, autoincrement=True)
    time = Column(TIMESTAMP(), nullable=False, default=datetime.utcnow)
    status = Column(SmallInteger(), CheckConstraint('status>=0 AND status<=2'),
                    nullable=False, default=0)
    r_post_id = Column(String(8), nullable=True, default=None)
    scan_time = Column('t_scan', TIMESTAMP(), nullable=False,
                       default=datetime.utcnow)
    title = Column(Unicode(255), nullable=True, default=None)
    text = Column(UnicodeText(), nullable=True, default=None)

    STATUS_TEXT = ['queued', 'active', 'archived']
    STATUS_QUEUED = 0
    STATUS_ACTIVE = 1
    STATUS_ARCHIV = 2

    def __init__(self, time, is_active=True, **kwargs):
        self.time      = time if time is not None else datetime.utcnow()
        self.r_post_id = kwargs.get('r_post_id', None)
        self.scan_time = kwargs.get('scan_time', datetime.utcnow())
        self.title     = kwargs.get('title', None)
        self.text      = kwargs.get('text', None)

        if self.r_post_id != None:
            if is_active:
                self.status = self.STATUS_ACTIVE
            else:
                self.status = self.STATUS_ARCHIV
        else:
            self.status = self.STATUS_QUEUED

    def get_status_string(self):
        return self.STATUS_TEXT[self.status]

    def set_posted(self, post_id, post_time):
        """ Sets status as posted and records post id and time.
        ``post_id`` is a string; ``post_time`` is a ``datetime`` object or a
        UNIX timestamp (float). """
        self.status = self.STATUS_ACTIVE
        self.r_post_id = post_id
        try:
            self.post_time = datetime.utcfromtimestamp(post_time)
        except ValueError:
            self.post_time = post_time

    def set_archived(self):
        """ Sets status as archived. """
        self.status = self.STATUS_ARCHIV

    def __repr__(self):
        if self.text:
            if len(self.text) > 127:
                exctext = self.text[0:125] + '...'
            else:
                exctext = self.text
        else:
            exctext = ''
        return (u"<SuggestionThread({id_}, {time_}, {status}, '{post_id}', "
               u"{scan_time}, '{title}', '{excerpt}')>").format(
                    id_=self.id,
                    time_=unicode(self.time),
                    status=self.STATUS_TEXT[self.status],
                    post_id=self.r_post_id,
                    scan_time=unicode(self.scan_time),
                    title=self.title,
                    excerpt=exctext)

class Database(object):
    """ Database management class. Abstracts away the SQLAlchemy engine and
    logging configuration and provides some hooks to the engine.

    Logging occurs in logger objects called 'logging', 'logging.engine',
    'logging.dialects', 'logging.pool' and 'logging.orm' (using the standard
    Python logging module).

    =================
    Public attributes
    =================

    engine
        SQLAlchemy engine for the SQLite database.

    base
        A reference to the declarative base.

    """
    def __init__(self, dbfile='minibot.sqlite', **kwargs):
        """ Constructor. Set up parameters, engine, base, and logging.

        ==========
        Parameters
        ==========

        dbfile
            *Default: minibot.sqlite (current directory)*

            SQLite database file. Relative or absolute path.

        logfile
            *Default: minibot-db.log (current directory)*

            SQL log file location.

        loglevel
            *Default: logging.WARN*

            Logging level. Either one of the ``logging`` module's levels (ERROR,
            WARN, INFO, DEBUG), or a dict associating an SQLAlchemy component
            string to a logging level. Components are: 'engine', 'dialects',
            'pool' and 'orm'. INFO and DEBUG enable logging, while all higher
            levels disable it. See the `SQLAlchemy documentation`_.

        .. _`SQLAlchemy documentation`: http://docs.sqlalchemy.org/en/rel_0_7/core/engines.html#configuring-logging

        logformat
            *Default: '%(asctime)s (%(process)d:%(thread)d) [%(name)s:%(levelname)s] %(message)s'

            Format for log entries. See the Python library's
            ``logging.Formatter`` documentation.

        dateformat
            *Default: '%Y-%m-%d %H:%M:%S'*

            Date/time format for log entries. See the Python library's
            ``logging.Formatter`` documentation.

        table_prefix
            *Default: None*

            Table prefix. String to prepend to every table name in the database.

        """
        # declaration  of instance attributes
        # objects/components
        self.engine      = None
        self.base        = None
        self._loghandler = None

        # parameters
        self.table_prefix = kwargs.get('table_prefix', None)
        self._dbfile = dbfile
        self._logfile = kwargs.get('logfile', 'minibot-db.log')
        self._loglevel = kwargs.get('loglevel', logging.WARN)

        # create engine, base, session; bind as needed
        self.base = Base
        self.engine = create_engine('sqlite:///' + dbfile, echo=False)
        self.base.metadata.bind = self.engine

        # set up logging
        real_logfile = realpath(self._logfile)
        if not isdir(dirname(real_logfile)):
            makedirs(dirname(real_logfile))
        self._loghandler = logging.FileHandler(real_logfile, encoding='utf8')
        fmtr = logging.Formatter(kwargs.get('logformat',\
            '%(asctime)s (%(process)d:%(thread)d) '
            '[%(name)s:%(levelname)s] %(message)s'),\
            kwargs.get('dateformat', '%Y-%m-%d %H:%M:%S'))
        self._loghandler.setFormatter(fmtr)

        # if loglevel is a dict, assign handler to each
        try:
            for logname, loglevel in self._loglevel.itervalues():
                theLogger = None
                if logname == 'sqlalchemy':
                    theLogger = logging.getLogger(logname)
                elif logname in ['engine', 'dialects', 'pool', 'orm']:
                    theLogger = logging.getLogger('sqlalchemy.' + logname)

                if theLogger is not None:
                    theLogger.addHandler(self._loghandler)
                    theLogger.setLevel(loglevel)
        except AttributeError: # not a dict, so just assign to sqlalchemy
            theLogger = logging.getLogger('sqlalchemy')
            theLogger.addHandler(self._loghandler)
            theLogger.setLevel(self._loglevel)

    def __del__(self):
        """ Destructor. Removes the log handler. Other resources held within
        the object are deleted normally. """
        try:
            for logname, loglevel in self._loglevel.itervalues():
                theLogger = None
                if logname == 'sqlalchemy':
                    theLogger = logging.getLogger(logname)
                elif logname in ['engine', 'dialects', 'pool', 'orm']:
                    theLogger = logging.getLogger('sqlalchemy.' + logname)

                if theLogger is not None:
                    theLogger.removeHandler(self._loghandler)
        except AttributeError: # not a dict
            theLogger = logging.getLogger('sqlalchemy')
            theLogger.removeHandler(self._loghandler)


    def create_tables(self, table_classes=None):
        """ Create the specified tables.

        ==========
        Parameters
        ==========

        table_classes
            List of mapped classes. If None, all mapped tables are created.
        """
        table_objects = self._get_table_objects(table_classes)
        self.base.metadata.create_all(tables=table_objects)

    def drop_tables(self, table_classes=None):
        """ Drop the specified tables.

        ==========
        Parameters
        ==========

        table_classes
            List of mapped classes. If None, all tables are dropped.
        """
        table_objects = self._get_table_objects(table_classes)
        self.base.metadata.drop_all(tables=table_objects)

    def get_new_session(self):
        """ Construct and return a new session. """
        return Session(bind=self.engine)

    def get_db_filename(self):
        """ Return the database filename specified at construction. """
        return self._dbfile

    def _get_table_objects(self, mapped_classes=None):
        """ Return a list of Table objects corresponding to a list of mapped
        classes.

        ==========
        Parameters
        ==========

        mapped_classes
            List of mapped classes. If None, None is returned.

        """
        if mapped_classes is not None:
            tables = []
            for mapped_class in mapped_classes:
                tables.append(mapped_class.__table__)
        else:
            tables = None

        return tables
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.