fixing i2psnarks new form with pythonscript

Issues and ideas about I2PSnark
Post Reply
Titus
Posts: 4
Joined: 28 Dec 2021 16:17

fixing i2psnarks new form with pythonscript

Post by Titus »

Hi,

as i have voiced before using the IRC2P i was deeply annoyed by i2psnark changing the form of of there start download form to included an upload option which prevented me from using firefox custom search keyword funktion to quickly add magnet links. Now i finally managed to get a workaround out of chatgpt:

Code: Select all

#!/usr/bin/env python3

# i2pSnarkFeeding.py
# Developed with the assistance of OpenAI's GPT-3.5

import requests
import configparser
import sys
import os
import re
from urllib.parse import urlparse

def get_language():
    lang = os.getenv("LANG")
    if lang:
        lang = lang.split('.')[0] # Berücksichtige nur den Sprachcode
    return lang

def get_translation(lang):
    if lang == "es":
        return {
            "adding_success": "¡Enlace magnético o archivo torrent añadido correctamente a i2psnark!",
            "adding_error": "Error al agregar el enlace magnético o archivo torrent a i2psnark.",
            "usage": "Uso: python script.py [archivo.torrent | enlace_magnético | enlace_http_a_torrent]",
            "help": [
                "Opciones:",
                "  -h, --help                 Mostrar este mensaje de ayuda"
            ]
        }
    elif lang == "de":
        return {
            "adding_success": "Magnet-Link oder Torrent-Datei erfolgreich zu i2psnark hinzugefügt!",
            "adding_error": "Fehler beim Hinzufügen des Magnet-Links oder der Torrent-Datei zu i2psnark.",
            "usage": "Verwendung: python script.py [torrent_datei | magnet_link | http_link_zu_torrent]",
            "help": [
                "Optionen:",
                "  -h, --help                 Diese Hilfemeldung anzeigen"
            ]
        }
    else: # Englisch als Standardsprache
        return {
            "adding_success": "Magnet link or torrent file successfully added to i2psnark!",
            "adding_error": "Error adding the magnet link or torrent file to i2psnark.",
            "usage": "Usage: python script.py [torrent_file | magnet_link | http_link_to_torrent]",
            "help": [
                "Options:",
                "  -h, --help                 Display this help message"
            ]
        }

def get_nonce(snark_url):
    try:
        response = requests.get(snark_url, timeout=5)
        nonce = response.text.split('name="nonce" value="', 1)[1].split('"', 1)[0]
        return nonce
    except Exception as e:
        print("Error fetching nonce:", str(e))
        return None

def add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations):
    try:
        url = snark_url + "/_post" # _post an die Snark-URL anhängen
        files = {'newFile': open(input_value, 'rb')} if os.path.isfile(input_value) else {'newFile': None}
        data = {
            'nonce': nonce,
            'p': '1',
            'sort': '-9',
            'action': 'Add',
            'nofilter_newURL': input_value if not files['newFile'] else '',
            'nofilter_newDir': target_dir,
            'foo': 'Add torrent'
        }
        response = requests.post(url, files=files, data=data)
        print("Response from server:", response.text) # Drucke die Serverantwort
        if "Torrent added successfully" in response.text:
            print(translations["adding_success"])
        else:
            print(translations["adding_error"])
    except Exception as e:
        print("Error adding the magnet link or torrent file to i2psnark:", str(e))

def display_help(translations):
    print(translations["usage"])
    for line in translations["help"]:
        print(line)
    sys.exit()

def main():
    # Sprache ermitteln
    lang = get_language()
    translations = get_translation(lang)

    # Konfigurationsdatei lesen
    config = configparser.ConfigParser()
    config.read('i2pSnarkFeeding.ini')
    target_dir = config['DEFAULT'].get('target_dir', '')

    # Nonce abrufen
    snark_url = config['DEFAULT'].get('snark_url', 'http://127.0.0.1:7657/i2psnark')
    nonce = get_nonce(snark_url)
    if nonce:
        # CLI-Argumente verarbeiten
        if len(sys.argv) == 1 or "-h" in sys.argv or "--help" in sys.argv:
            display_help(translations)
        else:
            input_value = sys.argv[1]
            if os.path.isfile(input_value):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            elif re.match(r'^magnet:', input_value):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            elif urlparse(input_value).scheme.startswith('http'):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            else:
                print("Invalid input. Please provide either a torrent file, a magnet link, or a link to a torrent file.")

if __name__ == "__main__":
    main()

just save this file somewhere on a system with access to the router, create a ini file like this along

i2pSnarkFeeding.ini:

Code: Select all

[DEFAULT]
target_dir = /I/i2psnark/
snark_url = http://127.0.0.1:7657/i2psnark
make the i2pSnarkFeeding.py if you are using and tell your browser to handle magnet links using that file and if you wish your os to open .torrent files using it to.

This script should be silent so you have to check your i2psnark in your browser yourself. I thought of implementing some desktop notifications but the time i was done i had enough of gpt3.5s stupidity and was happy it worked, but if you wish feel free to improve opon it.

happy hacking

Mr. T
Titus
Posts: 4
Joined: 28 Dec 2021 16:17

Re: fixing i2psnarks new form with pythonscript

Post by Titus »

grate, now i destroyed my whole i2psnark by changing the data dir in its global config, i cant seam to fix the issue with data dir is not transmitted correctly, there added torrents always get to my /home/ drive which filles up and brakes everything. Maybe somebody here wich actually speaks python can fix that. Here is my latest try, but i give up for now (or till i get gpt 4 through some means)

Code: Select all

$ cat ~/bin/i2pSnarkFeeding.py 
#!/usr/bin/env python3

# i2pSnarkFeeding.py
# Developed with the assistance of OpenAI's GPT-3.5

import requests
import configparser
import sys
import os
import re
from urllib.parse import urlparse
import logging
from datetime import datetime

def setup_logging(logfile):
    logging.basicConfig(filename=logfile, level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

def get_language():
    lang = os.getenv("LANG")
    if lang:
        lang = lang.split('.')[0] # Consider only the language code
    return lang

def get_translation(lang):
    if lang == "es":
        return {
            "adding_success": "¡Enlace magnético o archivo torrent añadido correctamente a i2psnark!",
            "usage": "Uso: python script.py [archivo.torrent | enlace_magnético | enlace_http_a_torrent]",
            "help": [
                "Opciones:",
                "  -h, --help                 Mostrar este mensaje de ayuda"
            ]
        }
    elif lang == "de":
        return {
            "adding_success": "Magnet-Link oder Torrent-Datei erfolgreich zu i2psnark hinzugefügt!",
            "usage": "Verwendung: python script.py [torrent_datei | magnet_link | http_link_zu_torrent]",
            "help": [
                "Optionen:",
                "  -h, --help                 Diese Hilfemeldung anzeigen"
            ]
        }
    else: # English as default language
        return {
            "adding_success": "Magnet link or torrent file successfully added to i2psnark!",
            "usage": "Usage: python script.py [torrent_file | magnet_link | http_link_to_torrent]",
            "help": [
                "Options:",
                "  -h, --help                 Display this help message"
            ]
        }

def get_nonce(snark_url):
    try:
        response = requests.get(snark_url, timeout=5)
        nonce = response.text.split('name="nonce" value="', 1)[1].split('"', 1)[0]
        return nonce
    except Exception as e:
        logging.error("Error fetching nonce: %s", str(e))
        return None

def log_error(message):
    logging.error(message)
    print(message)

def add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations):
    try:
        url = snark_url + "/_post" # Append _post to the Snark URL
        files = {'newFile': open(input_value, 'rb')} if os.path.isfile(input_value) else {'newFile': None}
        data = {
            'nonce': nonce,
            'p': '1',
            'sort': '-9',
            'action': 'Add',
            'nofilter_newDir': target_dir,
               'nofilter_newURL': input_value, 
            'foo': 'Add torrent'

        }
        response = requests.post(url, files=files, data=data)
        logging.info("Server response: %s", response.text)
        if "Torrent added successfully" in response.text:
            print(translations["adding_success"])
        else:
            log_error("Error adding the magnet link or torrent file to i2psnark.")
    except Exception as e:
        log_error("Error adding the magnet link or torrent file to i2psnark: %s", str(e))

def display_help(translations):
    print(translations["usage"])
    for line in translations["help"]:
        print(line)
    sys.exit()

def main():
    # Set up logging
    config = configparser.ConfigParser()
    config.read('i2pSnarkFeeding.ini')
    logfile = config['DEFAULT'].get('logfile', 'i2pSnarkFeeding.log')
    setup_logging(logfile)

    # Language detection
    lang = get_language()
    translations = get_translation(lang)

    # Read configuration file
    target_dir = config['DEFAULT'].get('target_dir', '')

    # Get nonce
    snark_url = config['DEFAULT'].get('snark_url', 'http://127.0.0.1:7657/i2psnark')
    nonce = get_nonce(snark_url)
    if nonce:
        # Process command-line arguments
        if len(sys.argv) == 1 or "-h" in sys.argv or "--help" in sys.argv:
            display_help(translations)
        else:
            input_value = sys.argv[1]
            if os.path.isfile(input_value):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            elif re.match(r'^magnet:', input_value):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            elif urlparse(input_value).scheme.startswith('http'):
                add_to_i2psnark(input_value, target_dir, snark_url, nonce, translations)
            else:
                print("Invalid input. Please provide either a torrent file, a magnet link, or a link to a torrent file.")

if __name__ == "__main__":
    main()

:~/bin$ cat ~/bin/i2pSnarkFeeding
#!/bin/bash

# i2pSnarkFeedingWrapper.sh

# Logfile path
LOG_FILE="~/bin/i2pSnarkFeedingWrapper.log"

# Log command line parameters
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Command line parameters: $@" >> "$LOG_FILE"

# Call the Python script with the provided parameters
python3 ~/bin/i2pSnarkFeeding.py "$@" >> "$LOG_FILE" 2>&1
Post Reply