# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
#     def create(cls, **kwargs):
#     def update(self, commit=True, **kwargs):
#     def save(self, commit=True):
#     def delete(self, commit=True):
#     def get_by_id(cls, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
# 
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
#     def __init__(self, value, **kwargs):
#     def __repr__(self):
#     def packs_count(self):
#     def nodes_count(self):
#     def queries_count(self):
#     def file_paths_count(self):
#     def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
#                  version=None, description=None, value=None, removed=True,
#                  shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, name, platform=None, version=None,
#                  description=None, shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, host_identifier, node_key=None,
#                  enroll_secret=None, enrolled_on=None, last_checkin=None,
#                  is_active=True, last_ip=None,
#                  **kwargs):
#     def __repr__(self):
#     def get_config(self, **kwargs):
#     def get_new_queries(self, **kwargs):
#     def display_name(self):
#     def packs(self):
#     def queries(self):
#     def file_paths(self):
#     def to_dict(self):
#     def __init__(self, category=None, target_paths=None, *args, **kwargs):
#     def to_dict(self):
#     def get_paths(self):
#     def set_paths(self, *target_paths):
#     def __init__(self, name=None, action=None, columns=None, timestamp=None,
#                  node=None, node_id=None, **kwargs):
#     def __table_args__(cls):
#     def __init__(self, line=None, message=None, severity=None,
#                  filename=None, created=None, node=None, node_id=None,
#                  version=None, **kwargs):
#     def __table_args__(cls):
#     def __init___(self, sql, description=None, not_before=None):
#     def __init__(self, node=None, node_id=None,
#                  distributed_query=None, distributed_query_id=None):
#     def __table_args__(cls):
#     def __init__(self, columns, distributed_query=None, distributed_query_task=None):
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#     def template(self):
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#     def set_password(self, password):
#     def check_password(self, value):
#     NEW = 0
#     PENDING = 1
#     COMPLETE = 2
#     FAILED = 3


from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
    DistributedQuery, DistributedQueryTask,
    Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six
    '''
    # The json package on Python 3 expects a `str` input, so we're going to
    # read the body and possibly convert to the right type
    body = upload.data.read()
    if not isinstance(body, six.string_types):
        body = body.decode('utf-8')

    try:
        data = json.loads(body)
    except ValueError:
        flash(u"Could not load pack as JSON - ensure it is JSON encoded",
              'danger')
        return None
    else:
        if 'queries' not in data:
            flash(u"No queries in pack", 'danger')
            return None

        name = splitext(basename(upload.data.filename))[0]
        pack = Pack.query.filter(Pack.name == name).first()

    if not pack:
        current_app.logger.debug("Creating pack %s", name)
        pack = Pack.create(name=name, **data)

    for query_name, query in data['queries'].items():
        if not validate_osquery_query(query['query']):
            flash('Invalid osquery query: "{0}"'.format(query['query']), 'danger')
            return None


# Path: doorman/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
#     def create(cls, **kwargs):
#     def update(self, commit=True, **kwargs):
#     def save(self, commit=True):
#     def delete(self, commit=True):
#     def get_by_id(cls, record_id):
# def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
# 
# Path: doorman/models.py
# class Tag(SurrogatePK, Model):
# class Query(SurrogatePK, Model):
# class Pack(SurrogatePK, Model):
# class Node(SurrogatePK, Model):
# class FilePath(SurrogatePK, Model):
# class ResultLog(SurrogatePK, Model):
# class StatusLog(SurrogatePK, Model):
# class DistributedQuery(SurrogatePK, Model):
# class DistributedQueryTask(SurrogatePK, Model):
# class DistributedQueryResult(SurrogatePK, Model):
# class Rule(SurrogatePK, Model):
# class User(UserMixin, SurrogatePK, Model):
#     def __init__(self, value, **kwargs):
#     def __repr__(self):
#     def packs_count(self):
#     def nodes_count(self):
#     def queries_count(self):
#     def file_paths_count(self):
#     def __init__(self, name, query=None, sql=None, interval=3600, platform=None,
#                  version=None, description=None, value=None, removed=True,
#                  shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, name, platform=None, version=None,
#                  description=None, shard=None, **kwargs):
#     def __repr__(self):
#     def to_dict(self):
#     def __init__(self, host_identifier, node_key=None,
#                  enroll_secret=None, enrolled_on=None, last_checkin=None,
#                  is_active=True, last_ip=None,
#                  **kwargs):
#     def __repr__(self):
#     def get_config(self, **kwargs):
#     def get_new_queries(self, **kwargs):
#     def display_name(self):
#     def packs(self):
#     def queries(self):
#     def file_paths(self):
#     def to_dict(self):
#     def __init__(self, category=None, target_paths=None, *args, **kwargs):
#     def to_dict(self):
#     def get_paths(self):
#     def set_paths(self, *target_paths):
#     def __init__(self, name=None, action=None, columns=None, timestamp=None,
#                  node=None, node_id=None, **kwargs):
#     def __table_args__(cls):
#     def __init__(self, line=None, message=None, severity=None,
#                  filename=None, created=None, node=None, node_id=None,
#                  version=None, **kwargs):
#     def __table_args__(cls):
#     def __init___(self, sql, description=None, not_before=None):
#     def __init__(self, node=None, node_id=None,
#                  distributed_query=None, distributed_query_id=None):
#     def __table_args__(cls):
#     def __init__(self, columns, distributed_query=None, distributed_query_task=None):
#     def __init__(self, name, alerters, description=None, conditions=None, updated_at=None):
#     def template(self):
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#     def set_password(self, password):
#     def check_password(self, value):
#     NEW = 0
#     PENDING = 1
#     COMPLETE = 2
#     FAILED = 3


# Path: doorman/utils.py
from collections import namedtuple
from operator import itemgetter
from os.path import basename, join, splitext
from flask import current_app, flash
from jinja2 import Markup, Template
from doorman.database import db
from doorman.models import (
    DistributedQuery, DistributedQueryTask,
    Node, Pack, Query, ResultLog, querypacks,
)
import datetime as dt
import json
import pkg_resources
import sqlite3
import string
import threading
import six

    '''
    # The json package on Python 3 expects a `str` input, so we're going to
    # read the body and possibly convert to the right type
    body = upload.data.read()
    if not isinstance(body, six.string_types):
        body = body.decode('utf-8')

    try:
        data = json.loads(body)
    except ValueError:
        flash(u"Could not load pack as JSON - ensure it is JSON encoded",
              'danger')
        return None
    else:
        if 'queries' not in data:
            flash(u"No queries in pack", 'danger')
            return None

        name = splitext(basename(upload.data.filename))[0]
        pack = Pack.query.filter(Pack.name == name).first()

    if not pack:
        current_app.logger.debug("Creating pack %s", name)
        pack = Pack.create(name=name, **data)

    for query_name, query in data['queries'].items():
        if not validate_osquery_query(query['query']):
            flash('Invalid osquery query: "{0}"'.format(query['query']), 'danger')
            return None


        q = Query.query.filter(Query.name == query_name).first()