# Path: config.py
# BASE_URL = '/torrent'
# STATIC_URL = BASE_URL + '/static'
# USE_OWN_HTTPD = False
# FILE_BLOCK_SIZE = 4096
# BACKGROUND_IMAGE = 'cat.jpg'
# USE_AUTH = True
# ENABLE_API = False
# CACHE_TIMEOUT=10
# 
# Path: lib/config_parser.py
# CONNECTION_SCGI, CONNECTION_HTTP = list(range(2))
# class RTorrentConfigException(Exception):
# def _parse_config_part_connection(config_dict, name):
# def _parse_config_part_storage(config_dict, info):
# def parse_config_part(config_dict, name):
# def parse_user_part(config_dict, name):
# 
# Path: lib/multibase.py
# class InvalidTorrentException(Exception):
#     """
#     Thrown on xmlrpc error.
#     """
# 
# class InvalidConnectionException(Exception):
#     """
#     Thrown on xmlrpc error.
#     """
# 
# class InvalidTorrentCommandException(Exception):
#     """
#     Thrown on an invalid command.
#     """
# 
# Path: model/rtorrent.py
# class RTorrent(object):
#     """
#     RTorrent class. This wraps most of the RTorrent *main* functionality
#     (read: global functionality) in a class. Think of, current upload and
#     download, libTorrent version.
# 
#     Methods specific to a Torrent can be found in the :ref:`torrent-class`
#     class.
#     """
# 
#     # FIXME: If we leave URL at '' xmlrpclib will default to /RPC2 as well.
#     def __init__(self, target):
#         """
#         Initialise the RTorrent object.
#         ``target`` is target dict as parsed by parse_config (pyrotorrent.py).
#         """
#         self.target = target
#         self.s = RTorrentXMLRPC(target)
# 
#         self.hacks()
# 
#     def hacks(self):
#         # Hack in all the methods in _rpc_methods!
#         for x, y in _rpc_methods.items():
# 
#         #   caller = create_caller(y[0], create_argcheck(y[2])) # belongs to the
#         #   argument checking
# 
#             caller = (lambda name: lambda self, *args: getattr(self.s, name)(*args))(y[0])
#             caller.__doc__ = y[1] + '\nOriginal libTorrent method: ``%s``' % y[0]
#             setattr(RTorrent, x, types.MethodType(caller, self))
# 
#             del caller
# 
#     def __repr__(self):
#         return 'RTorrent(%s)' % self.target['name']
# 
#     def get_download_list(self, _type=''):
#         """
#         Returns a list of torrents.
#         _type defines what is returned. Valid:
# 
#             *   '' (Empty string), 'default'
#             *   'complete'
#             *   'incomplete'
#             *   'started'
#             *   'stopped'
#             *   'active'
#             *   'hashing'
#             *   'seeding'
# 
#         Plus all customly defined views.
#         """
#         # FIXME: List is not complete(?) + exception should be raised.
#         if _type not in ('complete', 'incomplete', 'started', 'stopped',
#                 'active', 'hashing', 'seeding', '', 'default'):
#             return None
# 
#         res = self.s.download_list(_type)
# 
#         # FIXME: We now only have the hashes. Do we also want to fetch all the
#         # data per torrent? Or perhaps only the basic info?
# 
#         return res
# 
#     def query(self):
#         """
#         Query returns a new RTorrentQuery object with the target
#         from the current RTorrent object.
# 
#         Use this to execute several (different) calls on the RTorrent class in
#         one request. This can increase performance and reduce latency and load.
# 
#         See :ref:`rtorrentquery-class` on how to use it.
#         """
#         from lib.rtorrentquery import RTorrentQuery
#         return RTorrentQuery(self.target)


import sys
from flask import redirect, g, session, url_for, render_template
from config import FILE_BLOCK_SIZE, BACKGROUND_IMAGE, \
        USE_AUTH, ENABLE_API, rtorrent_config, torrent_users
from lib.config_parser import parse_config_part, parse_user_part, \
    RTorrentConfigException, CONNECTION_SCGI, CONNECTION_HTTP
from lib.multibase import InvalidTorrentException, InvalidConnectionException, \
    InvalidTorrentCommandException
from model.rtorrent import RTorrent
    #ret = unicode(template.render(vars)).encode('utf8')

    return render_template(template, **kw)

# Fetch some useful rtorrent info from all targets.
def fetch_global_info():
    """
    Fetch global stuff (always displayed):
        -   Down/Up Rate.
        -   IP (perhaps move to static global)
    """
    res = {}
    for target in targets:
        rtorrent = RTorrent(target)
        try:
            r = rtorrent.query().get_upload_rate().get_download_rate()\
                .get_upload_throttle().get_download_throttle().get_ip()\
                .get_hostname().get_memory_usage().get_max_memory_usage()\
                .get_libtorrent_version().get_view_list()

            h = hash(r)

            res[target['name']] = cache.get(h)
            if res[target['name']]:
                continue

            res[target['name']] = r.first()

            cache.set(h, res[target['name']], timeout=60)


# Path: config.py
# BASE_URL = '/torrent'
# STATIC_URL = BASE_URL + '/static'
# USE_OWN_HTTPD = False
# FILE_BLOCK_SIZE = 4096
# BACKGROUND_IMAGE = 'cat.jpg'
# USE_AUTH = True
# ENABLE_API = False
# CACHE_TIMEOUT=10
# 
# Path: lib/config_parser.py
# CONNECTION_SCGI, CONNECTION_HTTP = list(range(2))
# class RTorrentConfigException(Exception):
# def _parse_config_part_connection(config_dict, name):
# def _parse_config_part_storage(config_dict, info):
# def parse_config_part(config_dict, name):
# def parse_user_part(config_dict, name):
# 
# Path: lib/multibase.py
# class InvalidTorrentException(Exception):
#     """
#     Thrown on xmlrpc error.
#     """
# 
# class InvalidConnectionException(Exception):
#     """
#     Thrown on xmlrpc error.
#     """
# 
# class InvalidTorrentCommandException(Exception):
#     """
#     Thrown on an invalid command.
#     """
# 
# Path: model/rtorrent.py
# class RTorrent(object):
#     """
#     RTorrent class. This wraps most of the RTorrent *main* functionality
#     (read: global functionality) in a class. Think of, current upload and
#     download, libTorrent version.
# 
#     Methods specific to a Torrent can be found in the :ref:`torrent-class`
#     class.
#     """
# 
#     # FIXME: If we leave URL at '' xmlrpclib will default to /RPC2 as well.
#     def __init__(self, target):
#         """
#         Initialise the RTorrent object.
#         ``target`` is target dict as parsed by parse_config (pyrotorrent.py).
#         """
#         self.target = target
#         self.s = RTorrentXMLRPC(target)
# 
#         self.hacks()
# 
#     def hacks(self):
#         # Hack in all the methods in _rpc_methods!
#         for x, y in _rpc_methods.items():
# 
#         #   caller = create_caller(y[0], create_argcheck(y[2])) # belongs to the
#         #   argument checking
# 
#             caller = (lambda name: lambda self, *args: getattr(self.s, name)(*args))(y[0])
#             caller.__doc__ = y[1] + '\nOriginal libTorrent method: ``%s``' % y[0]
#             setattr(RTorrent, x, types.MethodType(caller, self))
# 
#             del caller
# 
#     def __repr__(self):
#         return 'RTorrent(%s)' % self.target['name']
# 
#     def get_download_list(self, _type=''):
#         """
#         Returns a list of torrents.
#         _type defines what is returned. Valid:
# 
#             *   '' (Empty string), 'default'
#             *   'complete'
#             *   'incomplete'
#             *   'started'
#             *   'stopped'
#             *   'active'
#             *   'hashing'
#             *   'seeding'
# 
#         Plus all customly defined views.
#         """
#         # FIXME: List is not complete(?) + exception should be raised.
#         if _type not in ('complete', 'incomplete', 'started', 'stopped',
#                 'active', 'hashing', 'seeding', '', 'default'):
#             return None
# 
#         res = self.s.download_list(_type)
# 
#         # FIXME: We now only have the hashes. Do we also want to fetch all the
#         # data per torrent? Or perhaps only the basic info?
# 
#         return res
# 
#     def query(self):
#         """
#         Query returns a new RTorrentQuery object with the target
#         from the current RTorrent object.
# 
#         Use this to execute several (different) calls on the RTorrent class in
#         one request. This can increase performance and reduce latency and load.
# 
#         See :ref:`rtorrentquery-class` on how to use it.
#         """
#         from lib.rtorrentquery import RTorrentQuery
#         return RTorrentQuery(self.target)


# Path: lib/helper.py
import sys
from flask import redirect, g, session, url_for, render_template
from config import FILE_BLOCK_SIZE, BACKGROUND_IMAGE, \
        USE_AUTH, ENABLE_API, rtorrent_config, torrent_users
from lib.config_parser import parse_config_part, parse_user_part, \
    RTorrentConfigException, CONNECTION_SCGI, CONNECTION_HTTP
from lib.multibase import InvalidTorrentException, InvalidConnectionException, \
    InvalidTorrentCommandException
from model.rtorrent import RTorrent

    #ret = unicode(template.render(vars)).encode('utf8')

    return render_template(template, **kw)

# Fetch some useful rtorrent info from all targets.
def fetch_global_info():
    """
    Fetch global stuff (always displayed):
        -   Down/Up Rate.
        -   IP (perhaps move to static global)
    """
    res = {}
    for target in targets:
        rtorrent = RTorrent(target)
        try:
            r = rtorrent.query().get_upload_rate().get_download_rate()\
                .get_upload_throttle().get_download_throttle().get_ip()\
                .get_hostname().get_memory_usage().get_max_memory_usage()\
                .get_libtorrent_version().get_view_list()

            h = hash(r)

            res[target['name']] = cache.get(h)
            if res[target['name']]:
                continue

            res[target['name']] = r.first()

            cache.set(h, res[target['name']], timeout=60)


        except InvalidConnectionException as e: