grgr.me

latest commits to https://grgr.me/
Log | Files | Refs

youtube-embed.py (1279B)


      1 #!/usr/bin/env python3
      2 
      3 from bs4 import BeautifulSoup
      4 import sys
      5 
      6 raw = sys.stdin.read()
      7 raw = BeautifulSoup(raw, "html.parser")
      8 
      9 lists = raw.find_all('li')
     10 for li in lists:
     11     anchor = li.find('a')
     12     if not anchor:
     13         continue
     14     elif anchor.parent.name == "p" or len(anchor.find_parents("ul")) > 1:
     15         continue
     16     elif "youtube.com" in anchor['href']:
     17         leftSide = True if len(anchor.get_text()) < 32 else False
     18         vid = anchor['href'].split('v=')[1]
     19         vid = vid.split('&')[0]
     20         if 't=' in anchor['href']:
     21             timestamp = '?start=' + anchor['href'].split('t=')[1].split('s')[0]
     22         else:
     23             timestamp = ''
     24         embed_markup = (' <span class="nowrap">[<button class="embed"'
     25                         f'onclick="toggleYT(\'{vid}\', \'{timestamp}\')">'
     26                         f'<img class="embed{" left" if leftSide else ""}" '
     27                         'alt="" src='
     28                         f'"https://img.youtube.com/vi/{vid}/mqdefault.jpg">'
     29                         'toggle embed</button>]</span>'
     30                         f'<div class="embed" id="{vid}"></div>'
     31                         )
     32         embed_markup = BeautifulSoup(embed_markup, 'html.parser')
     33         li.insert(1, embed_markup)
     34 
     35 sys.stdout.write(str(raw))