Exemplo n.º 1
0
 def __init__(self):
     (options, args) = self.get_args()
     utils.load_settings(filepath=options.settings)
     self.dry_run = options.dry_run
     self.db = utils.get_db()
     self.args = args
     self.prepare()
Exemplo n.º 2
0
def init_database(dumpfilepath=None):
    db = utils.get_db()
    try:
        db['order']
    except couchdb.ResourceNotFound:
        pass
    else:
        sys.exit('Error: database is not empty')
    utils.initialize(db)
    # No specific items set here; done on-the-fly in e.g. get_next_number
    db.save(dict(_id='order',
                 orderportal_doctype=constants.META))
    print('created meta documents')
    if dumpfilepath:
        try:
            print('reading dump file...')
            undump(db, dumpfilepath)
            designs.regenerate_views_indexes(db)
        except IOError:
            print('Warning: could not load', dumpfilepath)
    else:
        print('no dump file loaded')
    # Load texts from the initial texts YAML file. Only if missing in db!
    print('loading any missing texts from', INIT_TEXTS_FILEPATH)
    try:
        with open(INIT_TEXTS_FILEPATH) as infile:
            texts = yaml.safe_load(infile)
    except IOError:
        print('Warning: could not load', INIT_TEXTS_FILEPATH)
        texts = dict()
    for name in constants.TEXTS:
        if len(list(db.view('text/name', key=name))) == 0:
            with admin.TextSaver(db=db) as saver:
                saver['name'] = name
                saver['text'] = texts.get(name, '')
def init_database(dumpfilepath=None):
    db = utils.get_db()
    try:
        db['order']
    except couchdb.ResourceNotFound:
        pass
    else:
        sys.exit('Error: database is not empty')
    utils.initialize(db)
    # No specific items set here; done on-the-fly in e.g. get_next_number
    db.save(dict(_id='order',
                 orderportal_doctype=constants.META))
    print('created meta documents')
    if dumpfilepath:
        try:
            print('reading dump file...')
            undump(db, dumpfilepath)
            designs.regenerate_views_indexes(db)
        except IOError:
            print('Warning: could not load', dumpfilepath)
    else:
        print('no dump file loaded')
    # Load texts from the initial texts YAML file. Only if missing in db!
    print('loading any missing texts from', INIT_TEXTS_FILEPATH)
    try:
        with open(INIT_TEXTS_FILEPATH) as infile:
            texts = yaml.safe_load(infile)
    except IOError:
        print('Warning: could not load', INIT_TEXTS_FILEPATH)
        texts = dict()
    for name in constants.TEXTS:
        if len(list(db.view('text/name', key=name))) == 0:
            with admin.TextSaver(db=db) as saver:
                saver['name'] = name
                saver['text'] = texts.get(name, '')
Exemplo n.º 4
0
def set_password(email, password):
    db = utils.get_db()
    view = db.view('account/email', include_docs=True)
    rows = list(view[email])
    if len(rows) != 1:
        raise ValueError("no such account %s" % email)
    doc = rows[0].doc
    with AccountSaver(doc=doc, db=db) as saver:
        saver.set_password(password)
Exemplo n.º 5
0
def set_role(email, role):
    assert role in constants.ACCOUNT_ROLES
    db = utils.get_db()
    view = db.view('account/email', include_docs=True)
    rows = list(view[email])
    if len(rows) != 1:
        raise ValueError("no such account %s" % email)
    doc = rows[0].doc
    with AccountSaver(doc=doc, db=db) as saver:
        saver['role'] = role
Exemplo n.º 6
0
def set_password(email, password):
    db = utils.get_db()
    view = db.view('account/email', include_docs=True)
    rows = list(view[email])
    if len(rows) != 1:
        raise ValueError("no such account %s" % email)
    doc = rows[0].doc
    with AccountSaver(doc=doc, db=db) as saver:
        saver.set_password(password)
    print('Set password for', email)
def set_role(email, role):
    assert role in constants.ACCOUNT_ROLES
    db = utils.get_db()
    view = db.view('account/email', include_docs=True)
    rows = list(view[email])
    if len(rows) != 1:
        raise ValueError("no such account %s" % email)
    doc = rows[0].doc
    with AccountSaver(doc=doc, db=db) as saver:
        saver['role'] = role
Exemplo n.º 8
0
 def __init__(self):
     parser = utils.get_command_line_parser(
         description='Fix documents in CouchDB.')
     parser.add_option('-d', '--dry-run',
                       action='store_true', dest='dry_run', default=False,
                       help='do not perform save; for debug')
     (options, args) = parser.parse_args()
     utils.load_settings(filepath=options.settings)
     self.dry_run = options.dry_run
     self.db = utils.get_db()
     self.args = args
     self.prepare()
Exemplo n.º 9
0
def set_password(email, password, verbose=False):
    db = utils.get_db()
    view = db.view('account/email', include_docs=True)
    rows = list(view[email])
    if len(rows) != 1:
        raise ValueError("no such account %s" % email)
    doc = rows[0].doc
    with AccountSaver(doc=doc, db=db) as saver:
        saver.set_password(password)
        if verbose: print('Password was set for', email)
        if saver['status'] != constants.ENABLED:
            saver['status'] = constants.ENABLED
            if verbose: print('Account was enabled.')
Exemplo n.º 10
0
def create_admin(email, password, first_name, last_name, university):
    with AccountSaver(db=utils.get_db()) as saver:
        saver.set_email(email)
        saver['first_name'] = first_name
        saver['last_name'] = last_name
        saver['address'] = dict()
        saver['invoice_address'] = dict()
        saver['university'] = university
        saver['department'] = None
        saver['owner'] = email
        saver.set_password(password)
        saver['role'] = constants.ADMIN
        saver['status'] = constants.ENABLED
    print('Created admin account', email)
Exemplo n.º 11
0
def init_database(dumpfilepath=None):
    db = utils.get_db(create=True)
    print('wiping out database...')
    wipeout_database(db)
    print('wiped out database')
    load_designs(db)
    print('loaded designs')
    # No specific items set here; done on-the-fly in e.g. get_next_number
    db.save(dict(_id='order', orderportal_doctype=constants.META))
    print('created meta documents')
    if dumpfilepath:
        dumpfilepath = utils.expand_filepath(dumpfilepath)
        try:
            print('reading dump file...')
            undump(db, dumpfilepath)
        except IOError:
            print('Warning: could not load', dumpfilepath)
    else:
        print('no dump file loaded')
    # Load initial order messages from file if missing in db
    try:
        db['order_messages']
    except couchdb.ResourceNotFound:
        try:
            filepath = settings['INITIAL_ORDER_MESSAGES_FILEPATH']
        except KeyError:
            print('Warning: no initial order messages')
        else:
            try:
                with open(utils.expand_filepath(filepath)) as infile:
                    messages = yaml.safe_load(infile)
            except IOError:
                print('Warning: could not load', filepath)
                messages = dict()
            messages['_id'] = 'order_messages'
            messages[constants.DOCTYPE] = constants.META
            db.save(messages)
    # Load initial account messages from file if missing in db
    try:
        db['account_messages']
    except couchdb.ResourceNotFound:
        try:
            filepath = settings['INITIAL_ACCOUNT_MESSAGES_FILEPATH']
        except KeyError:
            print('Warning: no initial account messages')
        else:
            try:
                with open(utils.expand_filepath(filepath)) as infile:
                    messages = yaml.safe_load(infile)
            except IOError:
                print('Warning: could not load', filepath)
                messages = dict()
            messages['_id'] = 'account_messages'
            messages[constants.DOCTYPE] = constants.META
            db.save(messages)
    # Load texts from the init text file only if missing id db
    filepath = settings.get('INITIAL_TEXTS_FILEPATH')
    if filepath:
        print('loading missing texts from', filepath)
        try:
            with open(utils.expand_filepath(filepath)) as infile:
                texts = yaml.safe_load(infile)
        except IOError:
            print('Warning: could not load', filepath)
            texts = dict()
    else:
        texts = dict()
    for name in constants.TEXTS:
        if len(list(db.view('text/name', key=name))) == 0:
            with admin.TextSaver(db=db) as saver:
                saver['name'] = name
                saver['text'] = texts.get(name, '')
import yaml

from orderportal import constants
from orderportal import settings
from orderportal import utils


def load_order_messages(db):
    "Load the order messages document."
    for key in ['ORDER_MESSAGES_FILEPATH', 'INITIAL_ORDER_MESSAGES_FILEPATH']:
        filepath = settings.get(key)
        if filepath: break
    else:
        raise KeyError('no order messages file specified')
    print('Order messages from', filepath)
    with open(filepath) as infile:
        doc = yaml.safe_load(infile)
    doc['_id'] = 'order_messages'
    doc[constants.DOCTYPE] = constants.META
    print('saving order messages in database')
    db.save(doc)


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description='Load the order messages document.')
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    db = utils.get_db()
    load_order_messages(db)
Exemplo n.º 13
0
" Get the previous version of the document and save it as new. "

from __future__ import print_function, absolute_import

import sys

from orderportal import utils


def revert(db, docid):
    revisions = list(db.revisions(docid))
    if len(revisions) < 2:
        sys.exit('no previous version to revert to')
    latest = revisions[0]
    previous = revisions[1]
    new = previous.copy()
    new['_rev'] = latest['_rev']
    db.save(new)


if __name__ == '__main__':
    parser = utils.get_command_line_parser(description=
         'Get the previous version of the document and save it as new.')
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    db = utils.get_db()
    for docid in args:
        revert(db, docid)
Exemplo n.º 14
0
    docs = []
    for docid in docids:
        try:
            doc = db[docid]
        except couchdb.ResourceNotFound:
            print('no such document', docid, file=sys.stderr)
        else:
            docs.append(doc)
    if docs:
        if filepath:
            outfile = open(filepath, 'w')
            print('writing to', filepath)
        else:
            outfile = sys.stdout
        json.dump(docs, outfile, indent=2)
    else:
        print('no such document(s)', file=sys.stderr)


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description='Get document(s) from CouchDB and write to JSON file.')
    parser.add_option("-w", "--write",
                      action='store', dest='FILE', default=None,
                      metavar="FILE", help="filepath of file to write")
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    get_documents(utils.get_db(),
                  docids=args,
                  filepath=options.FILE)
Exemplo n.º 15
0
                             mail.as_string())
        self.print_log(message)

    def print_log(self, message):
        if not self.banner_printed:
            print('Messenger', utils.timestamp())
            if self.dry_run:
                print('*** Dry run only! ***')
            self.banner_printed = True
        print(u"sent email '{0}' to {1}".format(
            message['subject'],
            ', '.join(message['recipients'])).encode('utf-8'))


def get_args():
    parser = utils.get_command_line_parser(description='Send unsent messages.')
    parser.add_option('-d',
                      '--dry-run',
                      action='store_true',
                      dest='dry_run',
                      default=False,
                      help='do not send messages; for debug')
    return parser.parse_args()


if __name__ == '__main__':
    (options, args) = get_args()
    utils.load_settings(filepath=options.settings)
    messenger = Messenger(utils.get_db(), dry_run=options.dry_run)
    messenger.process()
Exemplo n.º 16
0
        else:
            try:
                del doc['_rev']
            except KeyError:
                pass
            db.save(doc)
            print('saved', doc['_id'])


def add_docs(docs, data):
    if isinstance(data, dict):
        if not '_id' in data: raise KeyError
        docs.append(data)
    elif isinstance(data, list):
        for item in data:
            if isinstance(item, dict):
                if not '_id' in item: raise KeyError
                docs.append(item)
            else:
                raise ValueError
    else:
        raise ValueError


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description='Put document(s) to CouchDB from JSON file.')
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    put_documents(utils.get_db(), filepaths=args)
Exemplo n.º 17
0
        except KeyError:
            pass
        else:
            with MessageSaver(db=db) as saver:
                saver.set_params(
                    account=account['email'],
                    password_url=absolute_reverse_url('password'),
                    password_code_url=absolute_reverse_url(
                        'password',
                        email=account['email'],
                        code=account['code']),
                    code=account['code'])
                saver.set_template(template)
                saver['recipients'] = [account['email']]
        print(account['email'])
        time.sleep(PAUSE)

def absolute_reverse_url(path, **kwargs):
    url = "https://ngisweden.scilifelab.se/{0}".format(path)
    if kwargs:
        url += '?' + urllib.urlencode(kwargs)
    return url


if __name__ == '__main__':
    parser = utils.get_command_line_parser(description=
        "Enable all pending accounts.")
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    enable_accounts(utils.get_db())
Exemplo n.º 18
0
        except KeyError:
            pass
        else:
            with MessageSaver(db=db) as saver:
                saver.set_params(account=account['email'],
                                 password_url=absolute_reverse_url('password'),
                                 password_code_url=absolute_reverse_url(
                                     'password',
                                     email=account['email'],
                                     code=account['code']),
                                 code=account['code'])
                saver.set_template(template)
                saver['recipients'] = [account['email']]
        print(account['email'])
        time.sleep(PAUSE)


def absolute_reverse_url(path, **kwargs):
    url = "https://ngisweden.scilifelab.se/{0}".format(path)
    if kwargs:
        url += '?' + urllib.urlencode(kwargs)
    return url


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description="Enable all pending accounts.")
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    enable_accounts(utils.get_db())
Exemplo n.º 19
0
def add_text(db, name, textfilepath, force=False):
    "Load the text from file, overwriting the current."
    with open(utils.expand_filepath(textfilepath)) as infile:
        text = infile.read()
        docs = [
            r.doc for r in db.view('text/name', include_docs=True, key=name)
        ]
        try:
            doc = docs[0]
            if not force:
                sys.exit('text exists; not overwritten')
        except IndexError:
            doc = None
        with admin.TextSaver(doc=doc, db=db) as saver:
            saver['name'] = name
            saver['text'] = text
        print("Text '{0}' loaded".format(name))


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description='Load a named text from file into the database.')
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    if len(args) != 2:
        sys.exit('Error: give name and filepath')
    add_text(utils.get_db(),
             name=args[0],
             textfilepath=args[1],
             force=options.force)
        try:
            doc = db[docid]
        except couchdb.ResourceNotFound:
            print('no such document', docid, file=sys.stderr)
        else:
            docs.append(doc)
    if docs:
        if filepath:
            outfile = open(filepath, 'w')
            print('writing to', filepath)
        else:
            outfile = sys.stdout
        json.dump(docs, outfile, indent=2)
    else:
        print('no such document(s)', file=sys.stderr)


if __name__ == '__main__':
    parser = utils.get_command_line_parser(
        description='Get document(s) from CouchDB and write to JSON file.')
    parser.add_option("-w",
                      "--write",
                      action='store',
                      dest='FILE',
                      default=None,
                      metavar="FILE",
                      help="filepath of file to write")
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings)
    get_documents(utils.get_db(), docids=args, filepath=options.FILE)