# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select
                db.execute(
                    visits
                    .update()
                    .where(visits.c.id == id)
                    .values(time=timedelta(seconds=int(get('t', 0)) / 1000)))
                self.log.debug('%r inserted' % self)
            return uuid, False

        elif kind == 'o':
            last_visit = get('l')
            if last_visit and 'undefined' not in last_visit:
                last_visit = datetime.fromtimestamp(int(last_visit) / 1000)
            else:
                last_visit = None

            visit = {'uuid': uuid,
                     'host': get('k'),
                     'site': get('u'),
                     'client_tz_offset': int(float(get('z', 0))),
                     'date': self.stamp,
                     'last_visit': last_visit,
                     'ip': self.ip,
                     'referrer': get('r'),
                     'pretty_referrer': parse_referrer(
                         get('r', from_encoding='latin-1')),
                     'referrer_domain': parse_domain(
                         get('r', from_encoding='latin-1')),
                     'size': get('s'),
                     'page': get('p', from_encoding='latin-1'),
                     'hash': get('h', from_encoding='latin-1'),

# Path: pystil/utils.py
# def try_decode(astring):
#     """Try decoding a string in various encodings, with a fallback to good old
#     ascii."""
#     if isinstance(astring, str):
#         return astring
#     for encoding in ('utf8', 'latin'):
#         try:
#             return astring.decode(encoding)
#         except UnicodeDecodeError:
#             pass
#     return astring.decode('ascii', 'ignore')
# 
# def parse_ua(user_agent):
#     """Parse the user agent to return the platform, browser and version"""
#     for platform, regex in PLATFORMS:
#         match = regex.search(user_agent)
#         if match is not None:
#             break
#     else:
#         platform = ''
#     for browser, regex in BROWSERS:
#         match = regex.search(user_agent)
#         if match is not None:
#             version = match.group(1)
#             break
#     else:
#         browser = version = ''
#     return platform, browser, version
# 
# def parse_referrer(referrer, with_query=False, host_only=False,
#                    second_pass=False):
#     """Return a pretty format for most search engines"""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         if not netloc:
#             if with_query:
#                 return u"Local: %s" % up.path
#             if second_pass:
#                 return referrer
#             return "Local"
# 
#         query = up.query
#         parsed = parse_qs(query)
#         search = parsed.get('q', parsed.get('p', parsed.get('rdata', None)))
#         if search:
#             # TODO Yahoo variable encoding
#             if with_query:
#                 return u"Organic: %s %s" % (netloc, try_decode(search[0]))
#             return u"Organic: %s" % netloc
#         if host_only:
#             return netloc
#         return referrer
#     return "Direct"
# 
# def parse_domain(referrer):
#     """Return the domain of the given referrer."""
#     if referrer:
#         up = urlparse(referrer)
#         netloc = up.netloc
#         return netloc or "Local"
#     return "Direct"
# 
# Path: pystil/db.py
# def string(pkey=False):
# def integer(pkey=False):
# def decimal():
# def datetime():
# def date_column(pkey=False):
# class Visit(Base):
# class CriterionView(Base):


# Path: pystil/tracking.py
from pystil.utils import (
    try_decode, parse_ua, parse_referrer, parse_domain)
from pystil.db import Visit, country, city, asn, VisitIdSeq
from datetime import datetime, timedelta
from sqlalchemy import desc, select

                db.execute(
                    visits
                    .update()
                    .where(visits.c.id == id)
                    .values(time=timedelta(seconds=int(get('t', 0)) / 1000)))
                self.log.debug('%r inserted' % self)
            return uuid, False

        elif kind == 'o':
            last_visit = get('l')
            if last_visit and 'undefined' not in last_visit:
                last_visit = datetime.fromtimestamp(int(last_visit) / 1000)
            else:
                last_visit = None

            visit = {'uuid': uuid,
                     'host': get('k'),
                     'site': get('u'),
                     'client_tz_offset': int(float(get('z', 0))),
                     'date': self.stamp,
                     'last_visit': last_visit,
                     'ip': self.ip,
                     'referrer': get('r'),
                     'pretty_referrer': parse_referrer(
                         get('r', from_encoding='latin-1')),
                     'referrer_domain': parse_domain(
                         get('r', from_encoding='latin-1')),
                     'size': get('s'),
                     'page': get('p', from_encoding='latin-1'),
                     'hash': get('h', from_encoding='latin-1'),

                     'query': get('q'),