# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def space_uri(environ, space_name):
#     """
#     Determine the uri of a space based on its name.
#     """
#     host = environ['tiddlyweb.config']['server_host']['host']
#     port = environ['tiddlyweb.config']['server_host']['port']
#     scheme = environ['tiddlyweb.config']['server_host']['scheme']
#     if not _alien_domain(environ, space_name):
#         if port is not '443' and port is not '80':
#             uri = '%s://%s.%s:%s/' % (scheme,
#                     urllib.quote(space_name.encode('utf-8')),
#                     host, port)
#         else:
#             uri = '%s://%s.%s/' % (scheme,
#                     urllib.quote(space_name.encode('utf-8')),
#                     host)
#     else:
#         if space_name == 'frontpage':
#             if port is not '443' and port is not '80':
#                 uri = '%s://%s:%s/' % (scheme, host, port)
#             else:
#                 uri = '%s://%s/' % (scheme, host)
#         else:
#             uri = '%s://%s/' % (scheme, space_name)
#     return uri
# 
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
#     """
#     Extract the current HTTP host from the environment.
#     Return that plus the server_host from config. This is
#     used to help calculate what space we are in when HTTP
#     requests are made.
#     """
#     server_host = environ['tiddlyweb.config']['server_host']
#     port = int(server_host['port'])
#     if port == 80 or port == 443:
#         host_url = server_host['host']
#     else:
#         host_url = '%s:%s' % (server_host['host'], port)
# 
#     http_host = environ.get('HTTP_HOST', host_url)
#     if ':' in http_host:
#         for port in [':80', ':443']:
#             if http_host.endswith(port):
#                 http_host = http_host.replace(port, '')
#                 break
#     return http_host, host_url
# 
# Path: tiddlywebplugins/tiddlyspace/template.py
# def send_template(environ, template_name, template_data=None):
#     """
#     Set some defaults for a template and send the output.
#     """
#     default_css_tiddler = '/bags/common/tiddlers/profile.css'
#     if template_data is None:
#         template_data = {}
#     html_template_prefix = environ['tiddlyweb.space_settings']['htmltemplate']
#     if html_template_prefix:
#         default_css_tiddler = ('/bags/common/tiddlers/%s.css' %
#                 html_template_prefix)
#         html_template_prefix += '/'
#         try:
#             name = html_template_prefix + template_name
#             template = get_template(environ, name)
#         except TemplateNotFound:
#             template = get_template(environ, template_name)
#     else:
#         template = get_template(environ, template_name)
# 
#     store = environ['tiddlyweb.store']
# 
#     linked_resources = {
#             'HtmlCss': [],
#             'HtmlJavascript': []}
# 
#     if not html_template_prefix or template_name in CUSTOMIZABLES:
#         linked_resources['HtmlCss'] = [default_css_tiddler]
#         # Load CSS and JavaScript overrides.
#         current_space = determine_space(environ, determine_host(environ)[0])
#         if current_space:
#             recipe_name = determine_space_recipe(environ, current_space)
#             try:
#                 recipe = store.get(Recipe(recipe_name))
#                 for title in linked_resources:
#                     try:
#                         tiddler = Tiddler(title)
#                         bag = control.determine_bag_from_recipe(recipe,
#                                 tiddler, environ)
#                         tiddler.bag = bag.name
#                         try:
#                             tiddler = store.get(tiddler)
#                             if 'Javascript' in title:
#                                 url_content = tiddler.text.strip()
#                                 if url_content:
#                                     urls = url_content.split('\n')
#                                     linked_resources[title] = urls
#                             else:
#                                 url = '/bags/%s/tiddlers/%s' % (encode_name(
#                                     tiddler.bag), title)
#                                 linked_resources[title] = [url]
#                         except StoreError:
#                             continue
#                     except StoreError:
#                         pass
#             except StoreError:
#                 pass
# 
#     template_defaults = {
#             'original_server_host': original_server_host_url(environ),
#             'css': linked_resources['HtmlCss'],
#             'js': linked_resources['HtmlJavascript'],
#             'server_host': server_base_url(environ),
#     }
#     template_defaults.update(template_data)
#     return template.generate(template_defaults)


import logging
import urllib
import urllib2
from httpexceptor import HTTP404, HTTP400, HTTP415
from tiddlyweb.control import readable_tiddlers_by_bag
from tiddlyweb.store import StoreError, NoUserError
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.user import User
from tiddlyweb.wikitext import render_wikitext
from tiddlyweb.web.handler.search import get as search
from tiddlyweb.web.util import (server_host_url, encode_name,
        get_serialize_type, tiddler_url, get_route_value)
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.tiddlyspace.spaces import space_uri
from tiddlywebplugins.tiddlyspace.web import determine_host
from tiddlywebplugins.tiddlyspace.template import send_template
    from tiddlywebplugins.dispatcher.listener import Listener as BaseListener
"""
Start at the infrastructure for OStatus, including webfinger,
user profiles, etc.
"""







LOGGER = logging.getLogger(__name__)


def add_profile_routes(selector):
    """
    Add the necessary routes for profiles and webfinger.
    """
    selector.add('/.well-known/host-meta', GET=host_meta)
    selector.add('/webfinger', GET=webfinger)
    selector.add('/profiles/{username}[.{format}]', GET=profile)


def profile(environ, start_response):
    """
    Choose between an atom or html profile.
    """

# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def space_uri(environ, space_name):
#     """
#     Determine the uri of a space based on its name.
#     """
#     host = environ['tiddlyweb.config']['server_host']['host']
#     port = environ['tiddlyweb.config']['server_host']['port']
#     scheme = environ['tiddlyweb.config']['server_host']['scheme']
#     if not _alien_domain(environ, space_name):
#         if port is not '443' and port is not '80':
#             uri = '%s://%s.%s:%s/' % (scheme,
#                     urllib.quote(space_name.encode('utf-8')),
#                     host, port)
#         else:
#             uri = '%s://%s.%s/' % (scheme,
#                     urllib.quote(space_name.encode('utf-8')),
#                     host)
#     else:
#         if space_name == 'frontpage':
#             if port is not '443' and port is not '80':
#                 uri = '%s://%s:%s/' % (scheme, host, port)
#             else:
#                 uri = '%s://%s/' % (scheme, host)
#         else:
#             uri = '%s://%s/' % (scheme, space_name)
#     return uri
# 
# Path: tiddlywebplugins/tiddlyspace/web.py
# def determine_host(environ):
#     """
#     Extract the current HTTP host from the environment.
#     Return that plus the server_host from config. This is
#     used to help calculate what space we are in when HTTP
#     requests are made.
#     """
#     server_host = environ['tiddlyweb.config']['server_host']
#     port = int(server_host['port'])
#     if port == 80 or port == 443:
#         host_url = server_host['host']
#     else:
#         host_url = '%s:%s' % (server_host['host'], port)
# 
#     http_host = environ.get('HTTP_HOST', host_url)
#     if ':' in http_host:
#         for port in [':80', ':443']:
#             if http_host.endswith(port):
#                 http_host = http_host.replace(port, '')
#                 break
#     return http_host, host_url
# 
# Path: tiddlywebplugins/tiddlyspace/template.py
# def send_template(environ, template_name, template_data=None):
#     """
#     Set some defaults for a template and send the output.
#     """
#     default_css_tiddler = '/bags/common/tiddlers/profile.css'
#     if template_data is None:
#         template_data = {}
#     html_template_prefix = environ['tiddlyweb.space_settings']['htmltemplate']
#     if html_template_prefix:
#         default_css_tiddler = ('/bags/common/tiddlers/%s.css' %
#                 html_template_prefix)
#         html_template_prefix += '/'
#         try:
#             name = html_template_prefix + template_name
#             template = get_template(environ, name)
#         except TemplateNotFound:
#             template = get_template(environ, template_name)
#     else:
#         template = get_template(environ, template_name)
# 
#     store = environ['tiddlyweb.store']
# 
#     linked_resources = {
#             'HtmlCss': [],
#             'HtmlJavascript': []}
# 
#     if not html_template_prefix or template_name in CUSTOMIZABLES:
#         linked_resources['HtmlCss'] = [default_css_tiddler]
#         # Load CSS and JavaScript overrides.
#         current_space = determine_space(environ, determine_host(environ)[0])
#         if current_space:
#             recipe_name = determine_space_recipe(environ, current_space)
#             try:
#                 recipe = store.get(Recipe(recipe_name))
#                 for title in linked_resources:
#                     try:
#                         tiddler = Tiddler(title)
#                         bag = control.determine_bag_from_recipe(recipe,
#                                 tiddler, environ)
#                         tiddler.bag = bag.name
#                         try:
#                             tiddler = store.get(tiddler)
#                             if 'Javascript' in title:
#                                 url_content = tiddler.text.strip()
#                                 if url_content:
#                                     urls = url_content.split('\n')
#                                     linked_resources[title] = urls
#                             else:
#                                 url = '/bags/%s/tiddlers/%s' % (encode_name(
#                                     tiddler.bag), title)
#                                 linked_resources[title] = [url]
#                         except StoreError:
#                             continue
#                     except StoreError:
#                         pass
#             except StoreError:
#                 pass
# 
#     template_defaults = {
#             'original_server_host': original_server_host_url(environ),
#             'css': linked_resources['HtmlCss'],
#             'js': linked_resources['HtmlJavascript'],
#             'server_host': server_base_url(environ),
#     }
#     template_defaults.update(template_data)
#     return template.generate(template_defaults)


# Path: tiddlywebplugins/tiddlyspace/profiles.py
import logging
import urllib
import urllib2
from httpexceptor import HTTP404, HTTP400, HTTP415
from tiddlyweb.control import readable_tiddlers_by_bag
from tiddlyweb.store import StoreError, NoUserError
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.model.user import User
from tiddlyweb.wikitext import render_wikitext
from tiddlyweb.web.handler.search import get as search
from tiddlyweb.web.util import (server_host_url, encode_name,
        get_serialize_type, tiddler_url, get_route_value)
from tiddlywebplugins.utils import get_store
from tiddlywebplugins.tiddlyspace.spaces import space_uri
from tiddlywebplugins.tiddlyspace.web import determine_host
from tiddlywebplugins.tiddlyspace.template import send_template
    from tiddlywebplugins.dispatcher.listener import Listener as BaseListener

"""
Start at the infrastructure for OStatus, including webfinger,
user profiles, etc.
"""







LOGGER = logging.getLogger(__name__)


def add_profile_routes(selector):
    """
    Add the necessary routes for profiles and webfinger.
    """
    selector.add('/.well-known/host-meta', GET=host_meta)
    selector.add('/webfinger', GET=webfinger)
    selector.add('/profiles/{username}[.{format}]', GET=profile)


def profile(environ, start_response):
    """
    Choose between an atom or html profile.
    """

    http_host, host_url = determine_host(environ)