# Path: beavy/common/access_query.py
# class AccessQuery(BaseQuery):
# 
#     def _gen_filters(self, class_, fltr):
#         return [x for x in filter(lambda x: x is not None, [
#             t(class_, fltr)
#             # weirdly class_.__access_filters fails on us
#             # probably some sqlalchemy magic
#             for t in getattr(class_, "__access_filters")[fltr]]
#             )
#         ]
# 
#     def filter_visible(self, attr, remoteAttr):
#         filters = self._gen_filters(remoteAttr.class_, 'view')
#         if not filters:
#             return self.filter(False)
# 
#         return self.filter(attr.in_(
#             remoteAttr.class_.query.filter(or_(*filters))
#                              .with_entities(remoteAttr)
#                              .subquery()
#             )
#         )
# 
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
#     __LOOKUP_ATTRS__ = []
#     id = db.Column(db.Integer, primary_key=True)
#     created_at = db.Column('created_at', db.DateTime(), nullable=False,
#                            server_default=func.now())
#     email = db.Column(db.String(255), unique=True, nullable=False)
#     name = db.Column(db.String(255))
#     password = db.Column(db.String(255))
#     active = db.Column(db.Boolean())
#     confirmed_at = db.Column(db.DateTime())
# 
#     last_login_at = db.Column(db.DateTime())
#     current_login_at = db.Column(db.DateTime())
#     last_login_ip = db.Column(db.String(255))
#     current_login_ip = db.Column(db.String(255))
#     login_count = db.Column(db.Integer())
#     language_preference = db.Column(db.String(2))
# 
#     roles = db.relationship('Role', secondary=roles_users,
#                             backref=db.backref('users', lazy='dynamic'))
# 
#     def __str__(self):
#         return "<User #{} '{}' ({})>".format(self.id,
#                                              self.name or "",
#                                              self.email)
# 
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
#     _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
#     def injnect_manifest():
# def make_celery(app):
#         def __call__(self, *args, **kwargs):
#     def login_failed_redirect(self, profile, provider):
#     def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
#     def ensure_users():
#     def print_routes():
#     class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):


from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import contains_eager, aliased
from enum import Enum, unique
from sqlalchemy import func
from flask.ext.security import current_user
from beavy.common.access_query import AccessQuery
from itertools import chain
from flask import abort
from .user import User
from beavy.app import db
from collections import defaultdict
        from .activity import Activity


class ObjectQuery(AccessQuery):

    def by_capability(self, aborting=True, abort_code=404, *caps):
        caps = set(chain.from_iterable(map(lambda c:
                                           getattr(Object.TypesForCapability,
                                                   getattr(c, 'value', c), []),
                                           caps)))
        if not caps:
            # No types found, break right here.
            if aborting:
                raise abort(abort_code)
            return self.filter("1=0")

        return self.filter(Object.discriminator.in_(caps))

    def with_my_activities(self):
        if not current_user or not current_user.is_authenticated:
            return self


        my_activities = aliased(Activity.query.filter(
            Activity.subject_id == current_user.id
            ).cte(name="my_activities"), "my_activities")

        return self.outerjoin(my_activities).options(contains_eager(
            Object.my_activities, alias=my_activities))



# Path: beavy/common/access_query.py
# class AccessQuery(BaseQuery):
# 
#     def _gen_filters(self, class_, fltr):
#         return [x for x in filter(lambda x: x is not None, [
#             t(class_, fltr)
#             # weirdly class_.__access_filters fails on us
#             # probably some sqlalchemy magic
#             for t in getattr(class_, "__access_filters")[fltr]]
#             )
#         ]
# 
#     def filter_visible(self, attr, remoteAttr):
#         filters = self._gen_filters(remoteAttr.class_, 'view')
#         if not filters:
#             return self.filter(False)
# 
#         return self.filter(attr.in_(
#             remoteAttr.class_.query.filter(or_(*filters))
#                              .with_entities(remoteAttr)
#                              .subquery()
#             )
#         )
# 
# Path: beavy/models/user.py
# class User(db.Model, UserMixin):
#     __LOOKUP_ATTRS__ = []
#     id = db.Column(db.Integer, primary_key=True)
#     created_at = db.Column('created_at', db.DateTime(), nullable=False,
#                            server_default=func.now())
#     email = db.Column(db.String(255), unique=True, nullable=False)
#     name = db.Column(db.String(255))
#     password = db.Column(db.String(255))
#     active = db.Column(db.Boolean())
#     confirmed_at = db.Column(db.DateTime())
# 
#     last_login_at = db.Column(db.DateTime())
#     current_login_at = db.Column(db.DateTime())
#     last_login_ip = db.Column(db.String(255))
#     current_login_ip = db.Column(db.String(255))
#     login_count = db.Column(db.Integer())
#     language_preference = db.Column(db.String(2))
# 
#     roles = db.relationship('Role', secondary=roles_users,
#                             backref=db.backref('users', lazy='dynamic'))
# 
#     def __str__(self):
#         return "<User #{} '{}' ({})>".format(self.id,
#                                              self.name or "",
#                                              self.email)
# 
# Path: beavy/app.py
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# STATIC_FOLDER = os.path.join(BASE_DIR, '..', 'assets')
#     _FLBLPRE = "flask_social_blueprint.providers.{}"
# def make_env(app):
# def setup_statics(app):
#     def injnect_manifest():
# def make_celery(app):
#         def __call__(self, *args, **kwargs):
#     def login_failed_redirect(self, profile, provider):
#     def is_accessible(self):
# def _limiter_key():
# def inject_messages():
# def get_locale():
#     def ensure_users():
#     def print_routes():
#     class ContextTask(TaskBase):
# class SocialBlueprint(SocialBp):
# class BeavyAdminIndexView(AdminIndexView):


# Path: beavy/models/object.py
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import contains_eager, aliased
from enum import Enum, unique
from sqlalchemy import func
from flask.ext.security import current_user
from beavy.common.access_query import AccessQuery
from itertools import chain
from flask import abort
from .user import User
from beavy.app import db
from collections import defaultdict
        from .activity import Activity



class ObjectQuery(AccessQuery):

    def by_capability(self, aborting=True, abort_code=404, *caps):
        caps = set(chain.from_iterable(map(lambda c:
                                           getattr(Object.TypesForCapability,
                                                   getattr(c, 'value', c), []),
                                           caps)))
        if not caps:
            # No types found, break right here.
            if aborting:
                raise abort(abort_code)
            return self.filter("1=0")

        return self.filter(Object.discriminator.in_(caps))

    def with_my_activities(self):
        if not current_user or not current_user.is_authenticated:
            return self


        my_activities = aliased(Activity.query.filter(
            Activity.subject_id == current_user.id
            ).cte(name="my_activities"), "my_activities")

        return self.outerjoin(my_activities).options(contains_eager(
            Object.my_activities, alias=my_activities))



class Object(db.Model):