Ejemplo n.º 1
0
    def do_GET(self):
        """
        Handling the GET requests for scrape and announce according to
        predefined data initialised in the server
        """
        json_responses = self.server.json_responses
        curr_indices = self.server.curr_indices
        self.parsed_path = urlparse(self.path)
        #logging.info(f'Parsed path:{self.parsed_path}')
        #parsed_query=parse_qs(self.parsed_path.query.replace('%',''),errors='backslashreplace'
        #                          )
        input_hash = get_info_hash_field(
            self.parsed_path.query)  #self._get_hash(parsed_query)
        input_hash = convert_url_hash_to_hex(input_hash)
        #logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        logging.info(f'Accepted hash : {input_hash}')
        input_hash = input_hash.lower()
        if input_hash not in json_responses.keys():
            logging.info('Hash not found')
            self._set_response()
            self.wfile.write(
                Bencode.encode({
                    'failure reason':
                    f'SERVER: Hash doesnt exist : {input_hash}'
                }))
            return
        #self.wfile.write(f"GET request for {self.path}\nExtra Data={self.server.data}".encode('utf-8'))
        #logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        cmd = self.parsed_path.path[1:]

        responses = json_responses[input_hash][cmd]
        response_idx = curr_indices[input_hash][cmd]
        logging.info(f'Cmd : {cmd}. Curr idx : {response_idx}')
        curr_indices[input_hash][cmd] = (curr_indices[input_hash][cmd] +
                                         1) % len(responses)
        res = responses[response_idx]

        self._set_response()
        self.wfile.write(res.encode('ISO-8859-1'))
Ejemplo n.º 2
0
def renameTorrent(path, cate=None, type='first'):

    print("I'm renameTorrent()...")
    print("Renaming type is -> " + type)

    # 判断path参数的文件夹是否存在, 不存在就退出
    if os.path.exists(path):
        print(path + " exists...")
    else:
        print(path + " not exists!!! Terminating ...")
        exit()

    winerror = []
    for file in os.listdir(path):
        if os.path.isfile(path + file) & file.endswith('.torrent'):
            print(path + file)

            torrent_metadata = Bencode.read_file(path + file)
            torrent_tracker = torrent_metadata['announce'][0:50]
            torrent_name = torrent_metadata['info']['name']
            if ("private" in torrent_metadata['info'].keys()):
                torrent_is_private = torrent_metadata['info']['private']
            else:
                print("!!!!!")
                print("Torrent don't have PRIVATE attribute...")
                print("!!!!!")
                torrent_is_private = 0
            # print (torrent_metadata['info'].keys());
            # print (torrent_tracker);
            # print (torrent_name + '\n');

            for k, v in cateDict.items():
                # print (k);
                # if re.search(k, torrent_tracker.decode()):
                if re.search(k, torrent_tracker):
                    # print (v)

                    # 增加随机UUID,防止重命名文件时失败
                    uid = uuid.uuid1().hex[0:8]
                    uid = '_' + uid + '_'

                    file_site_first = '[' + v + ']_' + torrent_name + uid + '.torrent'
                    file_site_last = torrent_name + uid + '[' + v + ']' + '.torrent'

                    # print (file_site_first);
                    # print (file_site_last);

                    if (type == 'first'):
                        file_new = file_site_first
                    else:
                        file_new = file_site_last

                    # 切换命名方法
                    # file_new = file_site_first;
                    # file_new = file_site_last;

                    try:
                        if os.path.join(path,
                                        file_new) == os.path.join(path, file):
                            print(file)
                            print("No need to Rename...\n")
                            pass
                        else:
                            print(file + " Renaming -> \n" + file_new)
                            os.rename(os.path.join(path, file),
                                      os.path.join(path, file_new))
                            print("")
                    except WindowsError:
                        pass
                        # winerror.append(file)
    print("renameTorrent done...!\n")
Ejemplo n.º 3
0
def test_encode_errors():
    with pytest.raises(BencodeEncodingError):
        Bencode.encode(object())
Ejemplo n.º 4
0
def test_decode_errors():
    with pytest.raises(BencodeDecodingError):
        Bencode.read_string('u:some')
Ejemplo n.º 5
0
def test_read_file(torr_test_file, struct_torr_file):
    decoded = Bencode.read_file(torr_test_file)
    assert decoded == struct_torr_file
Ejemplo n.º 6
0
def test_read_file_dir(torr_test_dir, struct_torr_dir):
    decoded = Bencode.read_file(torr_test_dir)
    assert decoded == struct_torr_dir
Ejemplo n.º 7
0
def test_encode_errors():
    with pytest.raises(BencodeEncodingError):
        Bencode.encode(object())
Ejemplo n.º 8
0
def test_decode_errors():
    with pytest.raises(BencodeDecodingError):
        Bencode.read_string('u:some')
Ejemplo n.º 9
0
def test_read_file():
    decoded = Bencode.read_file(FPATH_TORRENT_SIMPLE)
    assert decoded == STRUCT_TORRENT_SIMPLE
Ejemplo n.º 10
0
def test_read_file_dir():
    decoded = Bencode.read_file(FPATH_TORRENT_WITH_DIR)
    assert decoded == STRUCT_TORRENT_WITH_DIR
Ejemplo n.º 11
0
def test_encode_error_long():
    # os.path.getsize() can be longs on py2
    a_long = long(741634835)
    encoded_long = Bencode.encode(a_long)