All files / app/mods/media mp3.ts

100% Statements 3/3
100% Branches 0/0
100% Functions 0/0
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179124x       124x                                                                                                                                                                                                                                                                                                                                                 124x          
import { DateTime } from 'luxon';
import { Plugin } from '../../model/plugin';
import { Mod } from '../../model/tag';
 
export const mp3DeltaPlugin: Plugin = {
  tag: '_plugin/delta/mp3',
  name: $localize`💽 Get MP3`,
  config: {
    mod: $localize`💽 Get MP3`,
    version: 3,
    type: 'tool',
    default: false,
    generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
    description: $localize`Download mp3s using YT-DLP.`,
    actions: [
      { if: 'plugin/embed', tag: '_plugin/delta/mp3', labelOff: $localize`mp3`, title: $localize`Download mp3 YT-DLP.`, global: true },
      { tag: '_plugin/delta/mp3', labelOn: $localize`cancel`, title: $localize`Cancel YT-DLP.` },
    ],
    timeoutMs: 900_000,
    requirements: `
      yt-dlp
      requests
    `,
    language: 'python',
    subDiff: ['script'],
    adminForm: [{
      key: 'script',
      type: 'code',
      props: {
        label: $localize`Script:`,
        language: 'python',
      },
    }],
    // language=python
    script: `
import tempfile
import glob
import os
import sys
import requests
import json
import yt_dlp
ref = json.load(sys.stdin)
origin = ref.get('origin', '')
url = ref.get('plugins', {}).get('plugin/embed', {}).get('url', ref.get('url', ''))
base_opts = {
    'remote_components': ['ejs:github'],
    'js_runtimes': {'bun': {'path': os.environ['JASPER_NODE']}},
    'noprogress': True,
    'format': 'bestaudio/best',
}
def has_tag(tag, tags):
    return tag in tags or any(t.startswith(tag + '/') for t in tags)
def process_single_track(track_url, track_title):
    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        base_name = temp_file.name
    try:
        saveStdout = sys.stdout
        sys.stdout = sys.stderr
        try:
            try:
                with yt_dlp.YoutubeDL({
                  **base_opts,
                  'outtmpl': f'{base_name}.%(ext)s',
                  'writethumbnail': True,
                  'cachedir': False,
                  'break_on_existing': False,
                  'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '256',
                  }, {
                    'key': 'FFmpegMetadata',
                    'add_metadata': True,
                  }, {
                    'key': 'EmbedThumbnail',
                  }]
                }) as ydl:
                    ydl.extract_info(track_url, download=True)
            except Exception as e:
                if 'This live event will begin in' in str(e):
                    return None
                raise
        finally:
            sys.stdout = saveStdout
        downloaded_file = f'{base_name}.mp3'
        with open(downloaded_file, 'rb') as f:
            file_data = f.read()
        response = requests.post(
            f"{os.environ['JASPER_API']}/pub/api/v1/repl/cache",
            data=file_data,
            headers={
                'Local-Origin': origin or 'default',
                'User-Role': 'ROLE_ADMIN',
                'Content-Type': 'audio/mpeg',
            },
            params={
                'origin': origin,
                'title': track_title + '.mp3',
                'mime': 'audio/mpeg',
            }
        )
        if not response.ok:
            print(f"Error {response.status_code}: {response.text}", file=sys.stderr)
            sys.exit(1)
        return response.json()
    finally:
        for target_path in [base_name] + glob.glob(f'{base_name}.*'):
            os.remove(target_path)
saveStdout = sys.stdout
sys.stdout = sys.stderr
try:
    with yt_dlp.YoutubeDL({**base_opts, 'extract_flat': True}) as ydl:
        info = ydl.extract_info(url, download=False)
except Exception as e:
    if 'This live event will begin in' in str(e):
        sys.exit(0)
    raise
finally:
    sys.stdout = saveStdout
output_refs = []
source_urls = []
if 'entries' in info:
    playlist_title = info.get('title', ref.get('title', 'Playlist'))
    parent_tags = ref.get('tags', [])
    child_extra_tags = []
    if has_tag('public', parent_tags):
        for t in parent_tags:
            if t == 'public' or t.startswith('public/'):
                if t not in child_extra_tags:
                    child_extra_tags.append(t)
    for t in parent_tags:
        if t.startswith('_user/') or t.startswith('+user/') or t.startswith('user/'):
            if t not in child_extra_tags:
                child_extra_tags.append(t)
    for index, entry in enumerate(info['entries']):
        if not entry: continue
        entry_url = entry.get('url') or entry.get('webpage_url')
        entry_title = entry.get('title') or f"Track {index + 1}"
        formatted_title = f"{index + 1:02d} - {entry_title}"
        cache_data = process_single_track(entry_url, formatted_title)
        if not cache_data: continue
        child_tags = ['plugin/audio'] + child_extra_tags
        child_ref = {
            'url': entry_url,
            'origin': origin,
            'title': formatted_title,
            'tags': child_tags,
            'plugins': {'plugin/audio': {'url': cache_data['url']}}
        }
        output_refs.append(child_ref)
        source_urls.append(entry_url)
    ref.pop('metadata', None)
    ref.setdefault('tags', []).append('plugin/playlist')
    ref['tags'] = [t for t in ref['tags'] if not (t + '/').startswith('_plugin/delta/mp3/') and not (t + '/').startswith('plugin/embed/')]
    ref.setdefault('plugins', {}).pop('plugin/embed', None)
    ref['sources'] = source_urls
    output_refs.insert(0, ref)
else:
    track_title = info.get('title', ref.get('title', ''))
    cache_data = process_single_track(url, track_title)
    if cache_data:
        ref.pop('metadata', None)
        ref.setdefault('tags', []).append('plugin/audio')
        ref['tags'] = [t for t in ref['tags'] if not (t + '/').startswith('_plugin/delta/mp3/') and not (t + '/').startswith('plugin/embed/')]
        ref.setdefault('plugins', {}).setdefault('plugin/audio', {})['url'] = cache_data['url']
        ref.setdefault('plugins', {}).pop('plugin/embed', None)
        output_refs.append(ref)
print(json.dumps({'ref': output_refs}))
    `,
  },
};
 
export const mp3Mod: Mod = {
  plugin: [
    mp3DeltaPlugin,
  ]
};