# Path: baleen/config.py
# class MongoConfiguration(confire.Configuration):
# class ServerConfiguration(confire.Configuration):
# class BaleenConfiguration(confire.Configuration):
#     CONF_PATHS = [
#         "/etc/baleen.yaml",                      # System configuration
#         os.path.expanduser("~/.baleen.yaml"),    # User specific config
#         os.path.abspath("conf/baleen.yaml"),     # Local configuration
#     ]
# 
# Path: baleen/models.py
# class Feed(me.DynamicDocument):
# 
#     version   = me.StringField(choices=FEEDTYPES)
#     etag      = me.StringField()
#     modified  = me.StringField()
#     title     = me.StringField(max_length=256)
#     link      = me.URLField(required=True, unique=True)
#     urls      = me.DictField()
#     category  = me.StringField(required=True)
#     active    = me.BooleanField(default=True)
#     fetched   = me.DateTimeField(default=None)
#     created   = me.DateTimeField(default=datetime.now, required=True)
#     updated   = me.DateTimeField(default=datetime.now, required=True)
# 
#     @classmethod
#     def pre_save(cls, sender, document, **kwargs):
#         document.updated = datetime.now()
# 
#     meta      = {
#         'collection': 'feeds',
#     }
# 
#     @property
#     def xmlurl(self):
#         return self.link
# 
#     @property
#     def htmlurl(self):
#         return self.urls.get('htmlUrl')
# 
#     def count_posts(self):
#         """
#         Count the number of associated posts
# 
#         TODO: This is very, very slow on Mongo (fix and make better).
#         """
#         return Post.objects(feed=self).count()
# 
#     def __unicode__(self):
#         return self.title if self.title else self.link
# 
# Path: baleen/utils/timez.py
# def localnow():
#     return datetime.now(tzlocal())
# 
# Path: baleen/exceptions.py
# class FeedTypeError(BaleenError):
#     """
#     Could not detect the feed type for synchronization
#     """
#     pass
# 
# Path: baleen/exceptions.py
# class SynchronizationError(IngestionError):
#     """
#     Something went wrong with feed synchronization
#     """
#     pass
# 
# Path: baleen/utils/decorators.py
# def memoized(fget):
#     """
#     Return a property attribute for new-style classes that only calls its
#     getter on the first access. The result is stored and on subsequent
#     accesses is returned, preventing the need to call the getter any more.
#     https://github.com/estebistec/python-memoized-property
#     """
#     attr_name = '_{0}'.format(fget.__name__)
# 
#     @wraps(fget)
#     def fget_memoized(self):
#         if not hasattr(self, attr_name):
#             setattr(self, attr_name, fget(self))
#         return getattr(self, attr_name)
# 
#     return property(fget_memoized)
# 
# def reraise(klass=BaleenError, message=None, trap=Exception):
#     """
#     Catches exceptions (those specified by trap) and then reraises the
#     exception type specified by class. Also embeds the original exception as
#     a property of the new exception: `error.original`. Finally you can
#     specify another message to raise, otherwise the error string is used.
#     """
# 
#     def reraise_decorator(func):
# 
#         @wraps(func)
#         def reraise_wrapper(*args, **kwargs):
#             """
#             Capture Wrapper
#             """
#             try:
#                 return func(*args, **kwargs)
#             except trap as e:
#                 error = klass(message or e.message)
#                 error.original = e
#                 raise error
# 
#         return reraise_wrapper
# 
#     return reraise_decorator
# 
# def timeout(seconds):
#     """
#     Raises a TimeoutError if a function does not terminate within
#     specified seconds.
#     """
#     def _timeout_error(signal, frame):
#         raise TimeoutError("Operation did not finish within \
#         {} seconds".format(seconds))
# 
#     def timeout_decorator(func):
# 
#         @wraps(func)
#         def timeout_wrapper(*args, **kwargs):
#             signal.signal(signal.SIGALRM, _timeout_error)
#             signal.alarm(seconds)
#             try:
#                 return func(*args, **kwargs)
#             finally:
#                 signal.alarm(0)
# 
#         return timeout_wrapper
# 
#     return timeout_decorator


import feedparser
from baleen.config import settings
from baleen.models import Feed
from baleen.utils.timez import localnow
from baleen.exceptions import FeedTypeError
from baleen.exceptions import SynchronizationError
from baleen.utils.decorators import memoized, reraise, timeout
            yield klass(feed)

    def __init__(self, feed):
        """
        Feed can be a string (url), a dictionary with an `xmlUrl` or a Feed.
        """
        self.feed = feed

    @memoized
    def type(self):
        """
        Returns the type of the feed.
        """
        if isinstance(self.feed, basestring):
            return self.URL

        if isinstance(self.feed, Feed):
            return self.MODEL

        if isinstance(self.feed, dict):
            if 'xmlUrl' not in self.feed:
                raise FeedTypeError(
                    "Dictionary object does not contain 'xmlUrl' key!"
                )
            return self.DICT

        raise FeedTypeError(
            "Could not determine feed type from '{}'".format(type(self.feed))
        )


# Path: baleen/config.py
# class MongoConfiguration(confire.Configuration):
# class ServerConfiguration(confire.Configuration):
# class BaleenConfiguration(confire.Configuration):
#     CONF_PATHS = [
#         "/etc/baleen.yaml",                      # System configuration
#         os.path.expanduser("~/.baleen.yaml"),    # User specific config
#         os.path.abspath("conf/baleen.yaml"),     # Local configuration
#     ]
# 
# Path: baleen/models.py
# class Feed(me.DynamicDocument):
# 
#     version   = me.StringField(choices=FEEDTYPES)
#     etag      = me.StringField()
#     modified  = me.StringField()
#     title     = me.StringField(max_length=256)
#     link      = me.URLField(required=True, unique=True)
#     urls      = me.DictField()
#     category  = me.StringField(required=True)
#     active    = me.BooleanField(default=True)
#     fetched   = me.DateTimeField(default=None)
#     created   = me.DateTimeField(default=datetime.now, required=True)
#     updated   = me.DateTimeField(default=datetime.now, required=True)
# 
#     @classmethod
#     def pre_save(cls, sender, document, **kwargs):
#         document.updated = datetime.now()
# 
#     meta      = {
#         'collection': 'feeds',
#     }
# 
#     @property
#     def xmlurl(self):
#         return self.link
# 
#     @property
#     def htmlurl(self):
#         return self.urls.get('htmlUrl')
# 
#     def count_posts(self):
#         """
#         Count the number of associated posts
# 
#         TODO: This is very, very slow on Mongo (fix and make better).
#         """
#         return Post.objects(feed=self).count()
# 
#     def __unicode__(self):
#         return self.title if self.title else self.link
# 
# Path: baleen/utils/timez.py
# def localnow():
#     return datetime.now(tzlocal())
# 
# Path: baleen/exceptions.py
# class FeedTypeError(BaleenError):
#     """
#     Could not detect the feed type for synchronization
#     """
#     pass
# 
# Path: baleen/exceptions.py
# class SynchronizationError(IngestionError):
#     """
#     Something went wrong with feed synchronization
#     """
#     pass
# 
# Path: baleen/utils/decorators.py
# def memoized(fget):
#     """
#     Return a property attribute for new-style classes that only calls its
#     getter on the first access. The result is stored and on subsequent
#     accesses is returned, preventing the need to call the getter any more.
#     https://github.com/estebistec/python-memoized-property
#     """
#     attr_name = '_{0}'.format(fget.__name__)
# 
#     @wraps(fget)
#     def fget_memoized(self):
#         if not hasattr(self, attr_name):
#             setattr(self, attr_name, fget(self))
#         return getattr(self, attr_name)
# 
#     return property(fget_memoized)
# 
# def reraise(klass=BaleenError, message=None, trap=Exception):
#     """
#     Catches exceptions (those specified by trap) and then reraises the
#     exception type specified by class. Also embeds the original exception as
#     a property of the new exception: `error.original`. Finally you can
#     specify another message to raise, otherwise the error string is used.
#     """
# 
#     def reraise_decorator(func):
# 
#         @wraps(func)
#         def reraise_wrapper(*args, **kwargs):
#             """
#             Capture Wrapper
#             """
#             try:
#                 return func(*args, **kwargs)
#             except trap as e:
#                 error = klass(message or e.message)
#                 error.original = e
#                 raise error
# 
#         return reraise_wrapper
# 
#     return reraise_decorator
# 
# def timeout(seconds):
#     """
#     Raises a TimeoutError if a function does not terminate within
#     specified seconds.
#     """
#     def _timeout_error(signal, frame):
#         raise TimeoutError("Operation did not finish within \
#         {} seconds".format(seconds))
# 
#     def timeout_decorator(func):
# 
#         @wraps(func)
#         def timeout_wrapper(*args, **kwargs):
#             signal.signal(signal.SIGALRM, _timeout_error)
#             signal.alarm(seconds)
#             try:
#                 return func(*args, **kwargs)
#             finally:
#                 signal.alarm(0)
# 
#         return timeout_wrapper
# 
#     return timeout_decorator


# Path: baleen/feed.py
import feedparser
from baleen.config import settings
from baleen.models import Feed
from baleen.utils.timez import localnow
from baleen.exceptions import FeedTypeError
from baleen.exceptions import SynchronizationError
from baleen.utils.decorators import memoized, reraise, timeout

            yield klass(feed)

    def __init__(self, feed):
        """
        Feed can be a string (url), a dictionary with an `xmlUrl` or a Feed.
        """
        self.feed = feed

    @memoized
    def type(self):
        """
        Returns the type of the feed.
        """
        if isinstance(self.feed, basestring):
            return self.URL

        if isinstance(self.feed, Feed):
            return self.MODEL

        if isinstance(self.feed, dict):
            if 'xmlUrl' not in self.feed:
                raise FeedTypeError(
                    "Dictionary object does not contain 'xmlUrl' key!"
                )
            return self.DICT

        raise FeedTypeError(
            "Could not determine feed type from '{}'".format(type(self.feed))
        )


    @memoized