# Path: lanshark/config.py
# def in_pathlist(file, pathlist = os.environ.get("PATH").split(os.pathsep)):
# def select_app(*apps):
# def get_mediaplayer():
#         def get_registry_value (subkey, name):
# def get_imageviewer():
# def get_openfile():
# def get_sys_encoding():
#     def __init__(self, path):
#     def debug(self):
#     def set_prefix(self, value):
#     def save(self, path=None):
# class Config(configuration.Config):
#     LOG_LEVEL = Enum('CRITICAL',
#                      ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'),
#                      'Sets the verbosity of logging output')
#     LOG_TARGET = String('-',
#                         'Target of logging output. Set to - to log stderr')
#     LOG_FORMAT = String('%(levelname)s:%(name)s:%(message)s',
#                         'Format of logging output. '
#                         'See http://docs.python.org/lib/node422.html '
#                         'for format description')
#     BROADCAST_IP = String("255.255.255.255",
#             "IP to use for udp broadcasts")
#     PORT = Integer(31337, "Port to use for both UDP and TCP")
#     CLIENT_PORT = Integer(31338, "Port for the clients udp sockets")
#     SEARCH_TIMEOUT = Integer(5,
#             "Time to wait for search results in seconds")
#     DISCOVER_TIMEOUT = Integer(5,
#             "Time to wait for new hosts to answer in seconds")
#     DISCOVER_INTERVAL = Integer(60,
#             "Interval to search for new computers in seconds")
#     NETWORK_NAME = String("HELO",
#             "Word to use for discovery, might act as simple password")
#     CACHE_TIMEOUT = Integer(600, "HTTP cache time to live")
#     SHARE_PATH = String("", "Path to the files you want to share")
#     INCOMING_PATH = String("", "Path to store the downloaded files")
#     MAX_SEARCH_RESULTS = Integer(128,
#             "Maximal number of search results per peer")
#     FOLDER_IMAGES = StringList([r"\.?folder\.(png|jpg|gif|img)$",
#                          r"cover\.(png|jpg|gif)$",
#                          r"(cover\-)?front\.(png|jpg|gif)$",
#                          r"cover.*?\.(png|jpg|gif)$",
#                          r"albumart.*?large\.jpg$",
#                          r"albumart.*?\.jpg"],
#             "regexps to match the folder images/covers")
#     MAX_IMAGE_SIZE = Integer(250000,
#             "Maximal size of preview images/covers to use")
#     DAEMON_IN_GUI = Boolean(True,
#             "Integrates daemon in the gui process")
#     RESOLVE_HOSTS = Boolean(False, "Resolve hostnames")
#     INDEX_INTERVAL = Integer(3600,
#             "Interval to update the fileindex in seconds")
#     GUI_ICON_SIZE = Integer(48, "Icon size in the gtkui")
#     PID_FILE = String(os.path.join("$configdir", "lanshark.pid"),
#             "Location of the pid file")
#     SOCKET_TIMEOUT = Integer(5000, "The timeout of tcp sockets in ms")
#     VIDEO_PLAYER = String(get_mediaplayer(),
#             "Command to play video files %s gets replaced with "
#             "the url to the video")
#     AUDIO_PLAYER = String(get_mediaplayer(),
#             "Command to play audio files %s gets replaced with"
#             "the url to the audio file ")
#     IMAGE_VIEWER = String(get_imageviewer(),
#             "Command to view images files %s gets replaced with"
#             "the url to the image ")
#     DISABLE_WEBINTERFACE = Boolean(False, "Do not show html interface")
#     FS_ENCODING = String(sys.getfilesystemencoding(), "Filesystem encoding")
#     SYS_ENCODING = String(get_sys_encoding(), 'System Encoding')
#     HOSTNAME = String(socket.gethostname(), "The name of your host/share")
#     DOWNLOAD_RELPATH = Boolean(True, "Use relative paths for downloads"
#             "instead of absolute ones")
#     INVISIBLE = Boolean(False, "Do not answer to discovery or search requests")
#     STATUSICON = Boolean(True, "Show icon in statusbar")
#     STATICHOSTS = StringList([], "Static peer entries for networks where udp"
#             "broadcasts are not avaible. "
#             "Exmaple: example.com:31337, 192.168.1.2:31337")
#     HIDDEN_FILES = StringList([r"\..*", r"Thumbs\.db"],
#             "Regexps to match hidden files")
#     PSYCO = Boolean(False, "Enable psyco JIT")
#     OPENFILE = String(get_openfile(), "The application used to start/open files")
#     LANGUAGES = [locale.getdefaultlocale()[0] or "en_US", "en_US"]
#     WEBSITE = "http://lanshark.29a.ch/"
#     VERSION = Integer(6, "Version of the config file")
#     DOWNLOAD_BS = 65536
# 
# Path: lanshark/cache.py
# def cached(timeout=600, max_items=128, stats=False):
#     """cache decorator with variable timeout and maximal items"""
#     return lambda func: _Cached(func, timeout, max_items, stats)
# 
# Path: lanshark/network.py
# def broadcast_dgram_socket(port):


import gc
import logging
import math
import os
import re
import select, socket, subprocess, sys
import time
import urllib2
import simplejson
from lanshark.config import config
from lanshark.cache import cached
from lanshark import network
    return addr

def discover(async=False):
    """Discover other hosts in the network"""
    for item in config.STATICHOSTS:
        url = "http://%s/" % item
        yield (item, url)
    s = network.broadcast_dgram_socket(config.CLIENT_PORT)
    hello = config.NETWORK_NAME
    s.sendto(hello, (config.BROADCAST_IP, config.PORT))
    for data in recv(s, config.DISCOVER_TIMEOUT, async):
        if data:
            msg, (addr, port) = data
            if config.STATICHOSTS and\
                    "%s:%i" % (addr, port) in config.STATICHOSTS:
                continue
            if msg.startswith(hello):
                name = msg[len(hello)+1:]
                url = "http://%s:%i/" % (resolve(addr), port)
                yield (name, url)
            else:
                yield None
        else:
            yield None

def search(what, async=False):
    """Search for files"""
    sock = network.broadcast_dgram_socket(config.CLIENT_PORT)
    what = what.encode('utf8')
    msg = "search %s %s" % (config.NETWORK_NAME, what)

# Path: lanshark/config.py
# def in_pathlist(file, pathlist = os.environ.get("PATH").split(os.pathsep)):
# def select_app(*apps):
# def get_mediaplayer():
#         def get_registry_value (subkey, name):
# def get_imageviewer():
# def get_openfile():
# def get_sys_encoding():
#     def __init__(self, path):
#     def debug(self):
#     def set_prefix(self, value):
#     def save(self, path=None):
# class Config(configuration.Config):
#     LOG_LEVEL = Enum('CRITICAL',
#                      ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'),
#                      'Sets the verbosity of logging output')
#     LOG_TARGET = String('-',
#                         'Target of logging output. Set to - to log stderr')
#     LOG_FORMAT = String('%(levelname)s:%(name)s:%(message)s',
#                         'Format of logging output. '
#                         'See http://docs.python.org/lib/node422.html '
#                         'for format description')
#     BROADCAST_IP = String("255.255.255.255",
#             "IP to use for udp broadcasts")
#     PORT = Integer(31337, "Port to use for both UDP and TCP")
#     CLIENT_PORT = Integer(31338, "Port for the clients udp sockets")
#     SEARCH_TIMEOUT = Integer(5,
#             "Time to wait for search results in seconds")
#     DISCOVER_TIMEOUT = Integer(5,
#             "Time to wait for new hosts to answer in seconds")
#     DISCOVER_INTERVAL = Integer(60,
#             "Interval to search for new computers in seconds")
#     NETWORK_NAME = String("HELO",
#             "Word to use for discovery, might act as simple password")
#     CACHE_TIMEOUT = Integer(600, "HTTP cache time to live")
#     SHARE_PATH = String("", "Path to the files you want to share")
#     INCOMING_PATH = String("", "Path to store the downloaded files")
#     MAX_SEARCH_RESULTS = Integer(128,
#             "Maximal number of search results per peer")
#     FOLDER_IMAGES = StringList([r"\.?folder\.(png|jpg|gif|img)$",
#                          r"cover\.(png|jpg|gif)$",
#                          r"(cover\-)?front\.(png|jpg|gif)$",
#                          r"cover.*?\.(png|jpg|gif)$",
#                          r"albumart.*?large\.jpg$",
#                          r"albumart.*?\.jpg"],
#             "regexps to match the folder images/covers")
#     MAX_IMAGE_SIZE = Integer(250000,
#             "Maximal size of preview images/covers to use")
#     DAEMON_IN_GUI = Boolean(True,
#             "Integrates daemon in the gui process")
#     RESOLVE_HOSTS = Boolean(False, "Resolve hostnames")
#     INDEX_INTERVAL = Integer(3600,
#             "Interval to update the fileindex in seconds")
#     GUI_ICON_SIZE = Integer(48, "Icon size in the gtkui")
#     PID_FILE = String(os.path.join("$configdir", "lanshark.pid"),
#             "Location of the pid file")
#     SOCKET_TIMEOUT = Integer(5000, "The timeout of tcp sockets in ms")
#     VIDEO_PLAYER = String(get_mediaplayer(),
#             "Command to play video files %s gets replaced with "
#             "the url to the video")
#     AUDIO_PLAYER = String(get_mediaplayer(),
#             "Command to play audio files %s gets replaced with"
#             "the url to the audio file ")
#     IMAGE_VIEWER = String(get_imageviewer(),
#             "Command to view images files %s gets replaced with"
#             "the url to the image ")
#     DISABLE_WEBINTERFACE = Boolean(False, "Do not show html interface")
#     FS_ENCODING = String(sys.getfilesystemencoding(), "Filesystem encoding")
#     SYS_ENCODING = String(get_sys_encoding(), 'System Encoding')
#     HOSTNAME = String(socket.gethostname(), "The name of your host/share")
#     DOWNLOAD_RELPATH = Boolean(True, "Use relative paths for downloads"
#             "instead of absolute ones")
#     INVISIBLE = Boolean(False, "Do not answer to discovery or search requests")
#     STATUSICON = Boolean(True, "Show icon in statusbar")
#     STATICHOSTS = StringList([], "Static peer entries for networks where udp"
#             "broadcasts are not avaible. "
#             "Exmaple: example.com:31337, 192.168.1.2:31337")
#     HIDDEN_FILES = StringList([r"\..*", r"Thumbs\.db"],
#             "Regexps to match hidden files")
#     PSYCO = Boolean(False, "Enable psyco JIT")
#     OPENFILE = String(get_openfile(), "The application used to start/open files")
#     LANGUAGES = [locale.getdefaultlocale()[0] or "en_US", "en_US"]
#     WEBSITE = "http://lanshark.29a.ch/"
#     VERSION = Integer(6, "Version of the config file")
#     DOWNLOAD_BS = 65536
# 
# Path: lanshark/cache.py
# def cached(timeout=600, max_items=128, stats=False):
#     """cache decorator with variable timeout and maximal items"""
#     return lambda func: _Cached(func, timeout, max_items, stats)
# 
# Path: lanshark/network.py
# def broadcast_dgram_socket(port):


# Path: lanshark/lib.py
import gc
import logging
import math
import os
import re
import select, socket, subprocess, sys
import time
import urllib2
import simplejson
from lanshark.config import config
from lanshark.cache import cached
from lanshark import network

    return addr

def discover(async=False):
    """Discover other hosts in the network"""
    for item in config.STATICHOSTS:
        url = "http://%s/" % item
        yield (item, url)
    s = network.broadcast_dgram_socket(config.CLIENT_PORT)
    hello = config.NETWORK_NAME
    s.sendto(hello, (config.BROADCAST_IP, config.PORT))
    for data in recv(s, config.DISCOVER_TIMEOUT, async):
        if data:
            msg, (addr, port) = data
            if config.STATICHOSTS and\
                    "%s:%i" % (addr, port) in config.STATICHOSTS:
                continue
            if msg.startswith(hello):
                name = msg[len(hello)+1:]
                url = "http://%s:%i/" % (resolve(addr), port)
                yield (name, url)
            else:
                yield None
        else:
            yield None

def search(what, async=False):
    """Search for files"""
    sock = network.broadcast_dgram_socket(config.CLIENT_PORT)
    what = what.encode('utf8')
    msg = "search %s %s" % (config.NETWORK_NAME, what)

    sock.sendto(msg, (config.BROADCAST_IP, config.PORT))