Skip to content
This repository was archived by the owner on Mar 21, 2023. It is now read-only.

Commit 7409188

Browse files
play_url and yt_url related to #59 (#60)
* related to #49 * refactor(play): play_url - documentation - isort - use boolean for yt_url's print_title - type hint * refactor(search): yt_url - isort - documentation - only work on unique video id - fix video title when printing - print title when there is only video title - use boolean for print_title parameter * docs(pafy): extract_video_id - isort - documentation Co-authored-by: Talha Asghar <[email protected]> Co-authored-by: rachmadani haryono <[email protected]>
1 parent d7fa4e9 commit 7409188

File tree

3 files changed

+85
-28
lines changed

3 files changed

+85
-28
lines changed

mps_youtube/commands/play.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1+
import random
12
import sys
3+
import typing as T
24
import webbrowser
3-
import random
45
from urllib.error import HTTPError, URLError
56

6-
from .. import g, c, streams, util, content, config
7-
from . import command, WORD, RS
7+
from .. import c, config, content, g, streams, util
8+
from . import RS, WORD, command
9+
from .search import related, yt_url
810
from .songlist import plist
9-
from .search import yt_url, related
1011

1112

1213
@command(r'play\s+(%s|\d+)' % WORD, 'play')
@@ -122,11 +123,20 @@ def play_all(pre, choice, post=""):
122123

123124

124125
@command(r'playurl\s(.*[-_a-zA-Z0-9]{11}[^\s]*)(\s-(?:f|a|w))?', 'playurl')
125-
def play_url(url, override):
126-
""" Open and play a youtube video url. """
126+
def play_url(url: str, override: T.Any):
127+
"""Open and play a youtube video url.
128+
129+
Args:
130+
url: url to be played
131+
override: override
132+
133+
Raises:
134+
SystemExit: If run from command line
135+
"""
136+
# @fixme check override type hint
127137
override = override if override else "_"
128138
g.browse_mode = "normal"
129-
yt_url(url, print_title=1)
139+
yt_url(url, print_title=True)
130140

131141
if len(g.model) == 1:
132142
play(override, "1", "_")

mps_youtube/commands/search.py

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
import re
2-
import json
3-
import math
41
import base64
2+
import json
53
import logging
4+
import math
5+
import re
6+
import typing as T
7+
from argparse import ArgumentParser
68
from datetime import datetime, timedelta
9+
from urllib import parse
10+
711
from .. import pafy
8-
from argparse import ArgumentParser
912

1013
parser = ArgumentParser()
1114
parser.add_argument('-d', '--duration', choices=('any', 'short', 'medium', 'long'))
@@ -15,11 +18,10 @@
1518
parser.add_argument('search', nargs='+')
1619

1720

18-
from .. import g, c, screen, config, util, content, listview, contentquery
19-
from ..playlist import Video, Playlist
21+
from .. import c, config, content, contentquery, g, listview, screen, util
22+
from ..playlist import Playlist, Video
2023
from . import command
21-
from .songlist import plist, paginatesongs
22-
24+
from .songlist import paginatesongs, plist
2325

2426
ISO8601_TIMEDUR_EX = re.compile(r'PT((\d{1,3})H)?((\d{1,3})M)?((\d{1,2})S)?')
2527

@@ -552,17 +554,32 @@ def mix(num):
552554
g.message = util.F('no mix')
553555

554556

555-
@command(r'url\s(.*[-_a-zA-Z0-9]{11}.*)', 'url')
556-
def yt_url(url, print_title=0):
557-
""" Acess videos by urls. """
557+
@command(r"url\s(.*[-_a-zA-Z0-9]{11}.*)", "url")
558+
def yt_url(url: str, print_title: bool = False):
559+
"""Acess videos by urls.
560+
561+
If `print_title` is true only last title from unique parsed id will be printed.
562+
563+
If for example `vid1` and `vid2` have title `title1` and `title2`, respectively,
564+
`yt_url('vid1 vid2 vid1', True)`
565+
will print `title2` from `vid2` instead `title1` from last entry `vid1`.
566+
567+
Args:
568+
url: youtube url
569+
print_title: print title or not
570+
"""
558571
url_list = url.split()
559572

560573
g.model.songs = []
561574

562-
for u in url_list:
575+
v_ids = set()
576+
v_title = None
577+
for url in url_list:
563578
try:
564-
p = pafy.get_video_info(url.split('?v=')[1])#util.get_pafy(u)
565-
579+
v_id = pafy.extract_video_id(url)
580+
if v_id in v_ids:
581+
continue
582+
p = pafy.get_video_info(v_id)
566583
except (IOError, ValueError) as e:
567584
g.message = c.r + str(e) + c.w
568585
g.content = g.content or content.generate_songlist_display(
@@ -571,13 +588,16 @@ def yt_url(url, print_title=0):
571588

572589
g.browse_mode = "normal"
573590
v = Video(p['id'], p['title'], int(p['duration']['secondsText']))
591+
if p and isinstance(p, dict):
592+
v_title = p.get("title")
574593
g.model.songs.append(v)
594+
v_ids.add(v_id)
575595

576596
if not g.command_line:
577597
g.content = content.generate_songlist_display()
578598

579-
if print_title:
580-
util.xprint(v.title)
599+
if print_title and v_title:
600+
util.xprint(v_title)
581601

582602

583603
@command(r'url_file\s(\S+)', 'url_file')

mps_youtube/pafy.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
1-
from youtubesearchpython import *
2-
import yt_dlp, random, os, requests, json, re
1+
import json
2+
import os
3+
import random
4+
import re
35
from urllib.parse import parse_qs, urlparse
6+
7+
import requests
8+
import yt_dlp
9+
from youtubesearchpython import *
10+
11+
412
class MyLogger:
513
def debug(self, msg):
614
# For compatibility with youtube-dl, both debug and info are passed into debug
@@ -119,8 +127,27 @@ def get_video_info(video_id):
119127
def return_dislikes(video_id):
120128
return json.loads(requests.get('https://returnyoutubedislikeapi.com/votes?videoId=' + video_id).text)
121129

122-
def extract_video_id(url):
123-
""" Extract the video id from a url, return video id as str. """
130+
131+
def extract_video_id(url: str) -> str:
132+
"""Extract the video id from a url, return video id as str.
133+
134+
Args:
135+
url: url contain video id
136+
137+
Returns:
138+
video id
139+
140+
Raises:
141+
ValueError: If no video id found
142+
143+
Examples:
144+
145+
>>> extract_video_id('http://example.com')
146+
>>> extract_video_id('https://www.youtube.com/watch?v=LDU_Txk06tM')
147+
LDU_Txk06tM
148+
>>> extract_video_id('https://youtu.be/LDU_Txk06tM')
149+
LDU_Txk06tM
150+
"""
124151
idregx = re.compile(r'[\w-]{11}$')
125152
url = str(url).strip()
126153

@@ -140,4 +167,4 @@ def extract_video_id(url):
140167
return vidid
141168

142169
err = "Need 11 character video id or the URL of the video. Got %s"
143-
raise ValueError(err % url)
170+
raise ValueError(err % url)

0 commit comments

Comments
 (0)