<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tracker server for hosting .track torrent files.
"""

import socket
import socketserver
import threading

import sys
import os
import os.path

import urllib.parse
from ipaddress import IPv4Address,AddressValueError

import trackerfile
import apiutils
import sillycfg



class TrackerServerHandler(socketserver.BaseRequestHandler):
    """The request handler for TrackerServer.
    """
    
    def handle(self):
        """Convert peer requests into methods
        """
        
        #get (MAX_MESSAGE_LENGTH + 1) bytes
        data = str(self.request.recv(self.server.MAX_MESSAGE_LENGTH+1),
                                                    *apiutils.encoding_defaults)
        
        
        #check if data is <= MAX_MESSAGE_LENGTH
        if len(data) > self.server.MAX_MESSAGE_LENGTH:
            print("Request too long")
            # this is out-of-spec, but necessary
            return self.exception( 'RequestTooLong', "Maximum message length " \
                                "is {}".format(self.server.MAX_MESSAGE_LENGTH) )
        
        print("\nReceived {}".format(data))
        
        #Retrieve command and args from message
        match = apiutils.re_apicommand.match( data )
        if not match:
            print("Bad Request: {!r}".format(data))
            # this is out-of-spec, but necessary
            return self.exception( 'BadRequest', "Failed to parse request" )
        
        command, args = match.group('command','args')
        command = command.lower()
        
        #parse arguments
        args = args.split()
        args = map( apiutils.arg_decode, args )
        
        #find the desired method
        api_method = getattr( self, 'api_{}'.format(command),None )
        if not api_method:
            print("Bad method: {}".format(command) )
            return self.exception( 'BadRequest', "No such method {!r}".format(
                                                                      command) )
        
        #try calling the method with arguments
        try:
            api_method( *args )
        
        except TypeError as err:
            if 'positional arguments' in str(err):
                print("Bad Request: {}".format(err.args[0]))
                return self.exception('BadRequest', err.args[0])
            
        
    
    def api_createtracker(self, fname, fsize, descrip, md5, ip, port):
        """Implements the createtracker API command.
        
        All arguments are expected to be strings, but *fsize* and *port* should
        be castable to :class:`int` and *ip* should be castable to 
        :class:`~ipaddress.IPv4Address`.
        """
        
        fname,descrip,md5 = map( str, (fname,descrip,md5) )
        
        try:
            fsize,port = int(fsize),int(port)
        except ValueError:
            print("Either fsize ({!r}) or port ({!r}) is not a valid " \
                                                "integer".format(fsize,port))
            ##return self.exception('ValueError',"Either fsize ({!r}) or port " \
            ##        "({!r}) is not a valid integer".format(fsize,port) )
            self.request.sendall( b"<createtracker fail>" )
            return
        
        try:
            ip = IPv4Address(ip)
        except AddressValueError:
            print("Malformed IP Address: {!r}".format(ip))
            ##return self.exception('ValueError',"Malformed IP address: " \
            ##                                            "{!r}".format(ip) )
            self.request.sendall( b"<createtracker fail>" )
            return
        
        
        tfname = "{}.track".format( fname )
        
        tfpath = os.path.join( self.server.torrents_dir, tfname )
        
        #check if .track file already exists
        if os.path.exists( tfpath ):
            print("Couldn't create tracker, already exists.")
            self.request.sendall( b"<createtracker ferr>" )
            return
        
        #create a new trackerfile
        try:
            tf = trackerfile.trackerfile( fname, fsize, descrip, md5 )
        except Exception as err:
            print(err)
            ##return self.exception('RuntimeError',"The following exception " \
            ##        "occurred while creating the trackerfile:\n" \
            ##        "{!s}".format(err) )
            self.request.sendall( b"<createtracker fail>" )
            return
        
        print("Created new trackerfile instance for fname={!r}".format(fname))
        
        #add creator as peer
        try:
            tf.updatePeer( ip, port, 0, fsize-1 )
        except Exception as err:
            print(err)
            self.request.sendall( b"<createtracker fail>" )
            return
        
        print("Added {} (creator) to trackerfile".format( ip ))
        
        #write tracker to file
        with open(tfpath, 'w') as fl:
            tf.writeTo( fl )
        
        print("Wrote trackerfile to disk.")
        
        self.request.sendall( b"<createtracker succ>" )
        return
    
    
    def api_updatetracker(self, fname, start_bytes, end_bytes, ip, port):
        """Implements the updatetracker API command.
        
        All arguments are expected to be strings, but *start_bytes*,
        *end_bytes*, and *port* should be castable to :class:`int` and 
        *ip* should be castable to :class:`~ipaddress.IPv4Address`.
        """
        fname = str(fname)
        
        try:
            start_bytes,end_bytes,port = map(int, (start_bytes,end_bytes,port))
        except ValueError:
            print("Either start_bytes ({!r}), end_bytes ({!r}), or port ({!r})"\
                   " is not a valid integer".format(start_bytes,end_bytes,port))
            ##return self.exception('ValueError',"Either start_bytes ({!r}), " \
            ##               "end_bytes ({!r}), or port ({!r}) is not a valid "\
            ##               "integer".format(start_bytes,end_bytes,port))
            self.request.sendall( b"<updatetracker fail>" )
            return
        
        try:
            ip = IPv4Address(ip)
        except AddressValueError:
            print("Malformed IP Address: {!r}".format(ip))
            ##return self.exception('ValueError',"Malformed IP address: " \
            ##                                            "{!r}".format(ip) )
            self.request.sendall( b"<updatetracker fail>" )
            return
        
        tfname = "{}.track".format( fname )
        
        tfpath = os.path.join( self.server.torrents_dir, tfname )
        
        #check if .track file exists
        if not os.path.exists( tfpath ):
            print("Can't update tracker file, doesn't exist")
            self.request.sendall( b"<updatetracker ferr>" )
            return<commit_msg>Removed never-used code<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tracker server for hosting .track torrent files.
"""

import socket
import socketserver
import threading

import sys
import os
import os.path

import urllib.parse
from ipaddress import IPv4Address,AddressValueError

import trackerfile
import apiutils
import sillycfg



class TrackerServerHandler(socketserver.BaseRequestHandler):
    """The request handler for TrackerServer.
    """
    
    def handle(self):
        """Convert peer requests into methods
        """
        
        #get (MAX_MESSAGE_LENGTH + 1) bytes
        data = str(self.request.recv(self.server.MAX_MESSAGE_LENGTH+1),
                                                    *apiutils.encoding_defaults)
        
        
        #check if data is <= MAX_MESSAGE_LENGTH
        if len(data) > self.server.MAX_MESSAGE_LENGTH:
            print("Request too long")
            # this is out-of-spec, but necessary
            return self.exception( 'RequestTooLong', "Maximum message length " \
                                "is {}".format(self.server.MAX_MESSAGE_LENGTH) )
        
        print("\nReceived {}".format(data))
        
        #Retrieve command and args from message
        match = apiutils.re_apicommand.match( data )
        if not match:
            print("Bad Request: {!r}".format(data))
            # this is out-of-spec, but necessary
            return self.exception( 'BadRequest', "Failed to parse request" )
        
        command, args = match.group('command','args')
        command = command.lower()
        
        #parse arguments
        args = args.split()
        args = map( apiutils.arg_decode, args )
        
        #find the desired method
        api_method = getattr( self, 'api_{}'.format(command),None )
        if not api_method:
            print("Bad method: {}".format(command) )
            return self.exception( 'BadRequest', "No such method {!r}".format(
                                                                      command) )
        
        #try calling the method with arguments
        try:
            api_method( *args )
        
        except TypeError as err:
            if 'positional arguments' in str(err):
                print("Bad Request: {}".format(err.args[0]))
                return self.exception('BadRequest', err.args[0])
            
        
    
    def api_createtracker(self, fname, fsize, descrip, md5, ip, port):
        """Implements the createtracker API command.
        
        All arguments are expected to be strings, but *fsize* and *port* should
        be castable to :class:`int` and *ip* should be castable to 
        :class:`~ipaddress.IPv4Address`.
        """
        
        fname,descrip,md5 = map( str, (fname,descrip,md5) )
        
        try:
            fsize,port = int(fsize),int(port)
        except ValueError:
            print("Either fsize ({!r}) or port ({!r}) is not a valid " \
                                                "integer".format(fsize,port))
            self.request.sendall( b"<createtracker fail>" )
            return
        
        try:
            ip = IPv4Address(ip)
        except AddressValueError:
            print("Malformed IP Address: {!r}".format(ip))
            self.request.sendall( b"<createtracker fail>" )
            return
        
        
        tfname = "{}.track".format( fname )
        
        tfpath = os.path.join( self.server.torrents_dir, tfname )
        
        #check if .track file already exists
        if os.path.exists( tfpath ):
            print("Couldn't create tracker, already exists.")
            self.request.sendall( b"<createtracker ferr>" )
            return
        
        #create a new trackerfile
        try:
            tf = trackerfile.trackerfile( fname, fsize, descrip, md5 )
        except Exception as err:
            print(err)
            self.request.sendall( b"<createtracker fail>" )
            return
        
        print("Created new trackerfile instance for fname={!r}".format(fname))
        
        #add creator as peer
        try:
            tf.updatePeer( ip, port, 0, fsize-1 )
        except Exception as err:
            print(err)
            self.request.sendall( b"<createtracker fail>" )
            return
        
        print("Added {} (creator) to trackerfile".format( ip ))
        
        #write tracker to file
        with open(tfpath, 'w') as fl:
            tf.writeTo( fl )
        
        print("Wrote trackerfile to disk.")
        
        self.request.sendall( b"<createtracker succ>" )
        return
    
    
    def api_updatetracker(self, fname, start_bytes, end_bytes, ip, port):
        """Implements the updatetracker API command.
        
        All arguments are expected to be strings, but *start_bytes*,
        *end_bytes*, and *port* should be castable to :class:`int` and 
        *ip* should be castable to :class:`~ipaddress.IPv4Address`.
        """
        fname = str(fname)
        
        try:
            start_bytes,end_bytes,port = map(int, (start_bytes,end_bytes,port))
        except ValueError:
            print("Either start_bytes ({!r}), end_bytes ({!r}), or port ({!r})"\
                   " is not a valid integer".format(start_bytes,end_bytes,port))
            self.request.sendall( b"<updatetracker fail>" )
            return
        
        try:
            ip = IPv4Address(ip)
        except AddressValueError:
            print("Malformed IP Address: {!r}".format(ip))
            self.request.sendall( b"<updatetracker fail>" )
            return
        
        tfname = "{}.track".format( fname )
        
        tfpath = os.path.join( self.server.torrents_dir, tfname )
        
        #check if .track file exists
        if not os.path.exists( tfpath ):
            print("Can't update tracker file, doesn't exist")
            self.request.sendall( b"<updatetracker ferr>" )
            return
{'fraction_non_alphanumeric': 0.10747153330213695, 'fraction_numerical': 0.002651692403681173, 'mean_word_length': 1.6950399327448509, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1391055', 'n_tokens_mistral': 3533, 'n_tokens_neox': 3467, 'n_words': 917}