Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SHRI improvement #343

Closed
tiberio87 opened this issue Feb 13, 2025 · 5 comments · Fixed by #348
Closed

SHRI improvement #343

tiberio87 opened this issue Feb 13, 2025 · 5 comments · Fixed by #348

Comments

@tiberio87
Copy link

Hi, I have a question to suggest on the SHRI tracker. If you see the AITHER tracker code that does a check on the audio track language, can you implement something similar for the SHRI tracker?
Let me give you an example, now the title of a file with the Italian audio track is named as follows:
Speak No Evil 2024 1080p BluRay DD+ 7.1 x265-iSlaNd
With the change should come out like this:
Speak No Evil 2024 1080p ITALIAN BluRay DD+ 7.1 x265-iSlaNd
This case applies only to files with a single audio track, when there are two audio tracks for example English and Italian must come out like this:
Speak No Evil 2024 1080p BluRay Dual-Audio DD+ 7.1 x265-iSlaNd

Thank.

@Audionut
Copy link
Owner

Audionut commented Feb 14, 2025

Do you only want non-English in title?
HUNO will put any language in title for instance

def get_audio(self, meta):

@tiberio87
Copy link
Author

tiberio87 commented Feb 14, 2025

Yes I want the non-English in the title. If there is only one Italian audio track you must write ITALIAN, two audio tracks you must write Dual-Audio.

@Audionut
Copy link
Owner

Audionut commented Feb 14, 2025

Something like this should work.

    async def upload(self, meta, disctype):
        common = COMMON(config=self.config)
        await common.edit_torrent(meta, self.tracker, self.source_flag)
	name = await self.edit_name(meta)
		
.....

        if nfo_file:
            files['nfo'] = ("nfo_file.nfo", nfo_file, "text/plain")
        data = {
            'name': name,

.....


    async def edit_name(self, meta):
        shri_name = meta['name']
        media_info_tracks = meta.get('media_info_tracks', [])  # noqa #F841
        resolution = meta.get('resolution')

        if not meta['is_disc']:
            def has_english_audio(tracks=None, media_info_text=None):
                if media_info_text:
                    audio_section = re.findall(r'Audio[\s\S]+?Language\s+:\s+(\w+)', media_info_text)
                    for i, language in enumerate(audio_section):
                        language = language.lower().strip()
                        if language.lower().startswith('en'):  # Check if it's English
                            return True
                return False

            def get_audio_lang(tracks=None, is_bdmv=False, media_info_text=None):
                if media_info_text:
                    match = re.search(r'Audio[\s\S]+?Language\s+:\s+(\w+)', media_info_text)
                    if match:
                        return match.group(1).upper()
                return ""

            try:
                media_info_path = f"{meta['base_dir']}/tmp/{meta['uuid']}/MEDIAINFO.txt"
                with open(media_info_path, 'r', encoding='utf-8') as f:
                    media_info_text = f.read()

                if not has_english_audio(media_info_text=media_info_text):
                    audio_lang = get_audio_lang(media_info_text=media_info_text)
                    if audio_lang and not meta['audio'] == "Dual-Audio":
			shri_name = aither_name.replace(meta['resolution'], f"{meta['resolution']} {audio_lang}", 1)
            except (FileNotFoundError, KeyError) as e:
                print(f"Error processing MEDIAINFO.txt: {e}")

        return shri_name

@tiberio87
Copy link
Author

I get some mistakes:

[r0cks@debian-r0cks: $~/git/SHRI-Upload-Assistant]$ python3.12 upload.py /*/*/*/*/*/*.2024.1080p.BluRay.DDP5.1.x265-*.mkv --no-seed --trackers SHRI Traceback (most recent call last): File "/*/*/git/SHRI-Upload-Assistant/upload.py", line 16, in <module> from src.trackersetup import tracker_class_map, api_trackers, other_api_trackers, http_trackers File "/*/*/git/SHRI-Upload-Assistant/src/trackersetup.py", line 35, in <module> from src.trackers.SHRI import SHRI File "/*/*/git/SHRI-Upload-Assistant/src/trackers/SHRI.py", line 188 shri_name = aither_name.replace(meta['resolution'], f"{meta['resolution']} {audio_lang}", 1) TabError: inconsistent use of tabs and spaces in indentation

`import asyncio
import requests
import platform
import os
import glob
import httpx

from src.trackers.COMMON import COMMON
from src.console import console

class SHRI():
"""
Edit for Tracker:
Edit BASE.torrent with announce and source
Check for duplicates
Set type/category IDs
Upload
"""

def __init__(self, config):
    self.config = config
    self.tracker = 'SHRI'
    self.source_flag = 'Shareisland'
    self.upload_url = 'https://shareisland.org/api/torrents/upload'
    self.search_url = 'https://shareisland.org/api/torrents/filter'
    self.signature = "\n[center][url=https://github.com/Audionut/Upload-Assistant]Created by Audionut's Upload Assistant[/url][/center]"
    self.banned_groups = [""]
    pass

async def get_cat_id(self, category_name):
    category_id = {
        'MOVIE': '1',
        'TV': '2',
    }.get(category_name, '0')
    return category_id

async def get_type_id(self, type):
    type_id = {
        'DISC': '26',
        'REMUX': '7',
        'WEBDL': '27',
        'WEBRIP': '27',
        'HDTV': '6',
        'ENCODE': '15'
    }.get(type, '0')
    return type_id

async def get_res_id(self, resolution):
    resolution_id = {
        '8640p': '10',
        '4320p': '1',
        '2160p': '2',
        '1440p': '3',
        '1080p': '3',
        '1080i': '4',
        '720p': '5',
        '576p': '6',
        '576i': '7',
        '480p': '8',
        '480i': '9'
    }.get(resolution, '10')
    return resolution_id

async def upload(self, meta, disctype):
    common = COMMON(config=self.config)
    await common.edit_torrent(meta, self.tracker, self.source_flag)
    name = await self.edit_name(meta)
    cat_id = await self.get_cat_id(meta['category'])
    type_id = await self.get_type_id(meta['type'])
    resolution_id = await self.get_res_id(meta['resolution'])
    await common.unit3d_edit_desc(meta, self.tracker, self.signature)
    region_id = await common.unit3d_region_ids(meta.get('region'))
    distributor_id = await common.unit3d_distributor_ids(meta.get('distributor'))
    if meta['anon'] == 0 and not self.config['TRACKERS'][self.tracker].get('anon', False):
        anon = 0
    else:
        anon = 1

    if meta['bdinfo'] is not None:
        mi_dump = None
        bd_dump = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/BD_SUMMARY_00.txt", 'r', encoding='utf-8').read()
    else:
        mi_dump = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/MEDIAINFO.txt", 'r', encoding='utf-8').read()
        bd_dump = None
    desc = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/[{self.tracker}]DESCRIPTION.txt", 'r', encoding='utf-8').read()
    open_torrent = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/[{self.tracker}]{meta['clean_name']}.torrent", 'rb')
    files = {'torrent': open_torrent}
    base_dir = meta['base_dir']
    uuid = meta['uuid']
    specified_dir_path = os.path.join(base_dir, "tmp", uuid, "*.nfo")
    nfo_files = glob.glob(specified_dir_path)
    nfo_file = None
    if nfo_files:
        nfo_file = open(nfo_files[0], 'rb')
    if nfo_file:
        files['nfo'] = ("nfo_file.nfo", nfo_file, "text/plain")
    data = {
        'name': name,
        'description': desc,
        'mediainfo': mi_dump,
        'bdinfo': bd_dump,
        'category_id': cat_id,
        'type_id': type_id,
        'resolution_id': resolution_id,
        'tmdb': meta['tmdb'],
        'imdb': meta['imdb_id'].replace('tt', ''),
        'tvdb': meta['tvdb_id'],
        'mal': meta['mal_id'],
        'igdb': 0,
        'anonymous': anon,
        'stream': meta['stream'],
        'sd': meta['sd'],
        'keywords': meta['keywords'],
        'personal_release': int(meta.get('personalrelease', False)),
        'internal': 0,
        'featured': 0,
        'free': 0,
        'doubleup': 0,
        'sticky': 0,
    }
    # Internal
    if self.config['TRACKERS'][self.tracker].get('internal', False) is True:
        if meta['tag'] != "" and (meta['tag'][1:] in self.config['TRACKERS'][self.tracker].get('internal_groups', [])):
            data['internal'] = 1

    if region_id != 0:
        data['region_id'] = region_id
    if distributor_id != 0:
        data['distributor_id'] = distributor_id
    if meta.get('category') == "TV":
        data['season_number'] = meta.get('season_int', '0')
        data['episode_number'] = meta.get('episode_int', '0')
    headers = {
        'User-Agent': f'Upload Assistant/2.2 ({platform.system()} {platform.release()})'
    }
    params = {
        'api_token': self.config['TRACKERS'][self.tracker]['api_key'].strip()
    }

    if meta['debug'] is False:
        response = requests.post(url=self.upload_url, files=files, data=data, headers=headers, params=params)
        try:
            console.print(response.json())
            # adding torrent link to comment of torrent file
            t_id = response.json()['data'].split(".")[1].split("/")[3]
            await common.add_tracker_torrent(meta, self.tracker, self.source_flag, self.config['TRACKERS'][self.tracker].get('announce_url'), "https://shareisland.org/torrents/" + t_id)
        except Exception:
            console.print("It may have uploaded, go check")
            return
    else:
        console.print("[cyan]Request Data:")
        console.print(data)
    open_torrent.close()

async def edit_name(self, meta):
    shri_name = meta['name']
    media_info_tracks = meta.get('media_info_tracks', [])  # noqa #F841
    resolution = meta.get('resolution')

    if not meta['is_disc']:
        def has_english_audio(tracks=None, media_info_text=None):
            if media_info_text:
                audio_section = re.findall(r'Audio[\s\S]+?Language\s+:\s+(\w+)', media_info_text)
                for i, language in enumerate(audio_section):
                    language = language.lower().strip()
                    if language.lower().startswith('en'):  # Check if it's English
                        return True
            return False

        def get_audio_lang(tracks=None, is_bdmv=False, media_info_text=None):
            if media_info_text:
                match = re.search(r'Audio[\s\S]+?Language\s+:\s+(\w+)', media_info_text)
                if match:
                    return match.group(1).upper()
            return ""

        try:
            media_info_path = f"{meta['base_dir']}/tmp/{meta['uuid']}/MEDIAINFO.txt"
            with open(media_info_path, 'r', encoding='utf-8') as f:
                media_info_text = f.read()

            if not has_english_audio(media_info_text=media_info_text):
                audio_lang = get_audio_lang(media_info_text=media_info_text)
                if audio_lang and not meta['audio'] == "Dual-Audio":
		shri_name = aither_name.replace(meta['resolution'], f"{meta['resolution']} {audio_lang}", 1)
        except (FileNotFoundError, KeyError) as e:
            print(f"Error processing MEDIAINFO.txt: {e}")

    return shri_name

async def search_existing(self, meta, disctype):
    dupes = []
    console.print("[yellow]Searching for existing torrents on SHRI...")
    params = {
        'api_token': self.config['TRACKERS'][self.tracker]['api_key'].strip(),
        'tmdbId': meta['tmdb'],
        'categories[]': await self.get_cat_id(meta['category']),
        'types[]': await self.get_type_id(meta['type']),
        'resolutions[]': await self.get_res_id(meta['resolution']),
        'name': ""
    }
    if meta['category'] == 'TV':
        params['name'] = params['name'] + f" {meta.get('season', '')}"
    if meta.get('edition', "") != "":
        params['name'] = params['name'] + f" {meta['edition']}"
    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            response = await client.get(url=self.search_url, params=params)
            if response.status_code == 200:
                data = response.json()
                for each in data['data']:
                    result = [each][0]['attributes']['name']
                    dupes.append(result)
            else:
                console.print(f"[bold red]Failed to search torrents. HTTP Status: {response.status_code}")
    except httpx.TimeoutException:
        console.print("[bold red]Request timed out after 5 seconds")
    except httpx.RequestError as e:
        console.print(f"[bold red]Unable to search for existing torrents: {e}")
    except Exception as e:
        console.print(f"[bold red]Unexpected error: {e}")
        await asyncio.sleep(5)

    return dupes`

@Audionut
Copy link
Owner

I just copy/pasted some code into notepad++, edited, and copy/pasted here.
You should check for proper indentation.

If it works, can you pr?

@Audionut Audionut linked a pull request Feb 16, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants