# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
#     """Generates an ASCII-only slug."""
#     result = []
#     text = text.replace("'", "")
#     for word in _punct_re.split(text.lower()):
#         word = word.encode('translit/long')
#         if word:
#             result.append(word)
#     return unicode(delim.join(result)).strip()
# 
# def timesince(dt, default="just now"):
#     """
#     Returns string representing "time since" e.g.
#     3 days ago, 5 hours ago etc.
#     """
# 
#     now = datetime.datetime.now()
#     diff = now - dt
# 
#     periods = (
#         (diff.days / 365, "year", "years"),
#         (diff.days / 30, "month", "months"),
#         (diff.days / 7, "week", "weeks"),
#         (diff.days, "day", "days"),
#         (diff.seconds / 3600, "hour", "hours"),
#         (diff.seconds / 60, "minute", "minutes"),
#         (diff.seconds, "second", "seconds"),
#     )
# 
#     for period, singular, plural in periods:
# 
#         if period:
#             return "%d %s ago" % (period, singular if period == 1 else plural)
# 
#     return default
# 
# def timeuntil(dt):
#     """
#     Returns string representing "time util" e.g.
#     3 days, 5 hours, etc.
#     """
#     tardis = 'future'
#     now = datetime.datetime.now()
#     if dt < now:
#         tardis = 'past'
# 
#     if tardis == 'future':
#         diff = relativedelta(dt, now)
#     elif tardis == 'past':
#         diff = relativedelta(now, dt)
# 
#     msg = []
#     if diff.months > 0:
#         msg.append("%s months" % diff.months)
#     if diff.days > 0:
#         msg.append("%s days" % diff.days)
#     if diff.hours > 0 and diff.days <= 0:
#         msg.append("%s hours" % diff.hours)
#     if diff.minutes > 0 and diff.hours <= 0:
#         msg.append("%s minutes" % diff.minutes)
# 
#     if len(msg) > 1:
#         msg = ', '.join(msg)
#     elif len(msg) == 1:
#         msg = ''.join(msg)
# 
#     if tardis == 'future':
#         msg = "In %s" % msg
#     elif tardis == 'past':
#         msg = "%s ago" % msg
# 
#     if msg:
#         return msg
# 
#     return dt.strftime("%m/%d/%Y")
# 
# def jsonencode(data):
#     import json
#     return json.dumps(data)
# 
# def configure_logging(app):
#     LEVELS = {'debug': logging.DEBUG,
#               'info': logging.INFO,
#               'warning': logging.WARNING,
#               'error': logging.ERROR,
#               'critical': logging.CRITICAL}
# 
#     if app.config.get('LOG_FILE'):
#         log_file = app.config['LOG_FILE']
#         log_file = os.path.abspath(os.path.expanduser(log_file))
#         new_handler = RotatingFileHandler(
#             log_file, maxBytes=100000, backupCount=3)
#         if app.config.get('LOG_LEVEL'):
#             new_level = app.config['LOG_LEVEL']
#             new_level = LEVELS.get(new_level, logging.error)
#             new_handler.setLevel(new_level)
# 
#         log_format = (
#             '-' * 80 + '\n' +
#             '%(asctime)-15s\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
#             '%(message)s\n' +
#             '-' * 80
#         )
#         new_handler.setFormatter(logging.Formatter(log_format))
# 
#         app.logger.addHandler(new_handler)
# 
# def newrelic_head():
#     agent = get_newrelic_agent()
#     if agent:
#         content = [
#             '<!-- New Relic tracking -->'
#         ]
#         header = agent.get_browser_timing_header()
#         content.append(header)
#         return '\n'.join(content)
#     return ''
# 
# def newrelic_foot():
#     agent = get_newrelic_agent()
#     if agent:
#         content = [
#             '<!-- New Relic tracking -->'
#         ]
#         footer = agent.get_browser_timing_footer()
#         content.append(footer)
#         return '\n'.join(content)
#     return ''
# 
# class FixGunicorn(object):
#     def __init__(self, app):
#         self.app = app
# 
#     def __call__(self, environ, start_response):
#         environ['SERVER_PORT'] = str(environ['SERVER_PORT'])
#         return self.app(environ, start_response)


import os
import socket
import path
import statsd
from flask import Flask
from flaskext.cache import Cache
from flask.ext.mongoengine import MongoEngine
from jinja2 import ModuleLoader
    from flask_debugtoolbar import DebugToolbarExtension
    from raven.contrib.flask import Sentry
from kardboard.util import (
    slugify,
    timesince,
    timeuntil,
    jsonencode,
    configure_logging,
    newrelic_head,
    newrelic_foot,
    FixGunicorn
)


try:
    DEBUG_TOOLBAR = True
except ImportError:
    DEBUG_TOOLBAR = False

try:
    SENTRY_SUPPORT = True
except ImportError:
    SENTRY_SUPPORT = False


def get_app():
    app = Flask('kardboard')
    app.config.from_object('kardboard.default_settings')
    if os.getenv('KARDBOARD_SETTINGS', None):
        app.config.from_envvar('KARDBOARD_SETTINGS')

    app.secret_key = app.config['SECRET_KEY']

    app.db = MongoEngine(app)

    app.jinja_env.add_extension('kardboard.util.Markdown2Extension')
    app.jinja_env.filters['slugify'] = slugify
    app.jinja_env.filters['timesince'] = timesince

# Path: kardboard/util.py
# def slugify(text, delim=u'-'):
#     """Generates an ASCII-only slug."""
#     result = []
#     text = text.replace("'", "")
#     for word in _punct_re.split(text.lower()):
#         word = word.encode('translit/long')
#         if word:
#             result.append(word)
#     return unicode(delim.join(result)).strip()
# 
# def timesince(dt, default="just now"):
#     """
#     Returns string representing "time since" e.g.
#     3 days ago, 5 hours ago etc.
#     """
# 
#     now = datetime.datetime.now()
#     diff = now - dt
# 
#     periods = (
#         (diff.days / 365, "year", "years"),
#         (diff.days / 30, "month", "months"),
#         (diff.days / 7, "week", "weeks"),
#         (diff.days, "day", "days"),
#         (diff.seconds / 3600, "hour", "hours"),
#         (diff.seconds / 60, "minute", "minutes"),
#         (diff.seconds, "second", "seconds"),
#     )
# 
#     for period, singular, plural in periods:
# 
#         if period:
#             return "%d %s ago" % (period, singular if period == 1 else plural)
# 
#     return default
# 
# def timeuntil(dt):
#     """
#     Returns string representing "time util" e.g.
#     3 days, 5 hours, etc.
#     """
#     tardis = 'future'
#     now = datetime.datetime.now()
#     if dt < now:
#         tardis = 'past'
# 
#     if tardis == 'future':
#         diff = relativedelta(dt, now)
#     elif tardis == 'past':
#         diff = relativedelta(now, dt)
# 
#     msg = []
#     if diff.months > 0:
#         msg.append("%s months" % diff.months)
#     if diff.days > 0:
#         msg.append("%s days" % diff.days)
#     if diff.hours > 0 and diff.days <= 0:
#         msg.append("%s hours" % diff.hours)
#     if diff.minutes > 0 and diff.hours <= 0:
#         msg.append("%s minutes" % diff.minutes)
# 
#     if len(msg) > 1:
#         msg = ', '.join(msg)
#     elif len(msg) == 1:
#         msg = ''.join(msg)
# 
#     if tardis == 'future':
#         msg = "In %s" % msg
#     elif tardis == 'past':
#         msg = "%s ago" % msg
# 
#     if msg:
#         return msg
# 
#     return dt.strftime("%m/%d/%Y")
# 
# def jsonencode(data):
#     import json
#     return json.dumps(data)
# 
# def configure_logging(app):
#     LEVELS = {'debug': logging.DEBUG,
#               'info': logging.INFO,
#               'warning': logging.WARNING,
#               'error': logging.ERROR,
#               'critical': logging.CRITICAL}
# 
#     if app.config.get('LOG_FILE'):
#         log_file = app.config['LOG_FILE']
#         log_file = os.path.abspath(os.path.expanduser(log_file))
#         new_handler = RotatingFileHandler(
#             log_file, maxBytes=100000, backupCount=3)
#         if app.config.get('LOG_LEVEL'):
#             new_level = app.config['LOG_LEVEL']
#             new_level = LEVELS.get(new_level, logging.error)
#             new_handler.setLevel(new_level)
# 
#         log_format = (
#             '-' * 80 + '\n' +
#             '%(asctime)-15s\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
#             '%(message)s\n' +
#             '-' * 80
#         )
#         new_handler.setFormatter(logging.Formatter(log_format))
# 
#         app.logger.addHandler(new_handler)
# 
# def newrelic_head():
#     agent = get_newrelic_agent()
#     if agent:
#         content = [
#             '<!-- New Relic tracking -->'
#         ]
#         header = agent.get_browser_timing_header()
#         content.append(header)
#         return '\n'.join(content)
#     return ''
# 
# def newrelic_foot():
#     agent = get_newrelic_agent()
#     if agent:
#         content = [
#             '<!-- New Relic tracking -->'
#         ]
#         footer = agent.get_browser_timing_footer()
#         content.append(footer)
#         return '\n'.join(content)
#     return ''
# 
# class FixGunicorn(object):
#     def __init__(self, app):
#         self.app = app
# 
#     def __call__(self, environ, start_response):
#         environ['SERVER_PORT'] = str(environ['SERVER_PORT'])
#         return self.app(environ, start_response)


# Path: kardboard/app.py
import os
import socket
import path
import statsd
from flask import Flask
from flaskext.cache import Cache
from flask.ext.mongoengine import MongoEngine
from jinja2 import ModuleLoader
    from flask_debugtoolbar import DebugToolbarExtension
    from raven.contrib.flask import Sentry
from kardboard.util import (
    slugify,
    timesince,
    timeuntil,
    jsonencode,
    configure_logging,
    newrelic_head,
    newrelic_foot,
    FixGunicorn
)



try:
    DEBUG_TOOLBAR = True
except ImportError:
    DEBUG_TOOLBAR = False

try:
    SENTRY_SUPPORT = True
except ImportError:
    SENTRY_SUPPORT = False


def get_app():
    app = Flask('kardboard')
    app.config.from_object('kardboard.default_settings')
    if os.getenv('KARDBOARD_SETTINGS', None):
        app.config.from_envvar('KARDBOARD_SETTINGS')

    app.secret_key = app.config['SECRET_KEY']

    app.db = MongoEngine(app)

    app.jinja_env.add_extension('kardboard.util.Markdown2Extension')
    app.jinja_env.filters['slugify'] = slugify
    app.jinja_env.filters['timesince'] = timesince

    app.jinja_env.filters['timeuntil'] = timeuntil