Full Code of iamtalhaasghar/yewtube for AI

master 547fe7f68770 cached
102 files
368.6 KB
98.3k tokens
416 symbols
1 requests
Download .txt
Showing preview only (395K chars total). Download the full file or copy to clipboard to get everything.
Repository: iamtalhaasghar/yewtube
Branch: master
Commit: 547fe7f68770
Files: 102
Total size: 368.6 KB

Directory structure:
gitextract_ckd9x4df/

├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Dockerfile
├── ISSUE_TEMPLATE.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── RELEASING.md
├── _config.yml
├── doc/
│   ├── conf.py
│   ├── index.rst
│   ├── modules.rst
│   ├── mps_youtube.c.rst
│   ├── mps_youtube.cache.rst
│   ├── mps_youtube.commands.album_search.rst
│   ├── mps_youtube.commands.config.rst
│   ├── mps_youtube.commands.download.rst
│   ├── mps_youtube.commands.local_playlist.rst
│   ├── mps_youtube.commands.misc.rst
│   ├── mps_youtube.commands.play.rst
│   ├── mps_youtube.commands.rst
│   ├── mps_youtube.commands.search.rst
│   ├── mps_youtube.commands.songlist.rst
│   ├── mps_youtube.config.rst
│   ├── mps_youtube.content.rst
│   ├── mps_youtube.g.rst
│   ├── mps_youtube.helptext.rst
│   ├── mps_youtube.history.rst
│   ├── mps_youtube.init.rst
│   ├── mps_youtube.main.rst
│   ├── mps_youtube.mpris.rst
│   ├── mps_youtube.paths.rst
│   ├── mps_youtube.player.rst
│   ├── mps_youtube.playlist.rst
│   ├── mps_youtube.playlists.rst
│   ├── mps_youtube.rst
│   ├── mps_youtube.screen.rst
│   ├── mps_youtube.streams.rst
│   ├── mps_youtube.terminalsize.rst
│   └── mps_youtube.util.rst
├── docs/
│   ├── changelog.md
│   ├── contributing.md
│   ├── css/
│   │   └── mkdocstrings.css
│   ├── gen_ref_nav.py
│   ├── index.md
│   └── license.md
├── mkdocs.yml
├── mps_youtube/
│   ├── __init__.py
│   ├── c.py
│   ├── cache.py
│   ├── commands/
│   │   ├── __init__.py
│   │   ├── album_search.py
│   │   ├── config.py
│   │   ├── download.py
│   │   ├── generate_playlist.py
│   │   ├── lastfm.py
│   │   ├── local_playlist.py
│   │   ├── misc.py
│   │   ├── play.py
│   │   ├── search.py
│   │   ├── songlist.py
│   │   └── spotify_playlist.py
│   ├── config.py
│   ├── content.py
│   ├── contentquery.py
│   ├── description_parser.py
│   ├── g.py
│   ├── helptext.py
│   ├── history.py
│   ├── init.py
│   ├── listview/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── livestream.py
│   │   ├── songtitle.py
│   │   └── user.py
│   ├── main.py
│   ├── mpris.py
│   ├── pafy.py
│   ├── paths.py
│   ├── player.py
│   ├── players/
│   │   ├── GenericPlayer.py
│   │   ├── __init__.py
│   │   ├── mplayer.py
│   │   ├── mpv.py
│   │   └── vlc.py
│   ├── playlist.py
│   ├── playlists.py
│   ├── screen.py
│   ├── streams.py
│   ├── terminalsize.py
│   ├── test/
│   │   ├── test_main.py
│   │   ├── test_mpris.py
│   │   ├── test_players_mplayer.py
│   │   └── test_util.py
│   └── util.py
├── requirements.txt
├── setup.cfg
├── setup.py
├── wheel_recipe.sh
├── yewtube.desktop
└── yt

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.py[cod]
otherstuff/
pafy
vi.py
MANIFEST
.dev
.vscode
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
tags
.env
env/
.idea/
venv/
test.py

================================================
FILE: CHANGELOG.md
================================================
# Changelog

<!--next-version-placeholder-->

## v2.9.2 (2023-01-26)
### Fix
* Remove pyreadline dependency (#105) ([#107](https://github.com/iamtalhaasghar/yewtube/issues/107)) ([`19e4148`](https://github.com/iamtalhaasghar/yewtube/commit/19e4148242380b543a4825962716550114984f11))

## v2.9.1 (2023-01-26)
### Fix
* #50 - brought back download audio file ([`b46dab4`](https://github.com/iamtalhaasghar/yewtube/commit/b46dab47e61c68efa0e51836a8cc9141d15d9e87))

## v2.9.0 (2022-10-20)
### Feature
* **mplayer:** Set cache ([#93](https://github.com/iamtalhaasghar/yewtube/issues/93)) ([`16d3a18`](https://github.com/iamtalhaasghar/yewtube/commit/16d3a186fb9feb24530e1f07b211062c44a515a0))

### Fix
* #76 video pops up ([`eaeff58`](https://github.com/iamtalhaasghar/yewtube/commit/eaeff58f94e2fd89706e42fdab6b8e82ef770941))

## v2.8.5 (2022-09-08)
### Fix
* #75 program crashes while creating custom playlist and saving it without playing ([`2552eff`](https://github.com/iamtalhaasghar/yewtube/commit/2552eff602683fbd28bc6841768bf6cf585fc960))
* **main:** Handle error when setting locale ([#86](https://github.com/iamtalhaasghar/yewtube/issues/86)) ([`ecd117c`](https://github.com/iamtalhaasghar/yewtube/commit/ecd117ca1ef753509b78082d6f919c9bc2b1756b))
* Enable quit-watch-later in mpv #77 ([`079e440`](https://github.com/iamtalhaasghar/yewtube/commit/079e44088260c938dc3ae71cd55146fb51de653e))

### Documentation
* Added common issues file. ([#91](https://github.com/iamtalhaasghar/yewtube/issues/91)) ([`4b69e5e`](https://github.com/iamtalhaasghar/yewtube/commit/4b69e5ee96ed36efa9a68f6315322ed3d44d1e3d))

## v2.8.4 (2022-05-05)
### Fix
* #53 viewing playlists uploaded by a user is back ([`f201cb5`](https://github.com/iamtalhaasghar/yewtube/commit/f201cb5f4cd45b9341ced6b549fc35a57e85eb9f))

## v2.8.3 (2022-04-25)
### Fix
* #45 fetch all videos of a playlist ([`261f468`](https://github.com/iamtalhaasghar/yewtube/commit/261f4687668c6c05415102c66587a27518bbac10))
* Save full playlists by name and all its videos ([`d69a959`](https://github.com/iamtalhaasghar/yewtube/commit/d69a9594c5824d97201774e81444b75aea93e861))
* #67  vlc dummy Interface does not work with live channels  ([`2d4637b`](https://github.com/iamtalhaasghar/yewtube/commit/2d4637b04b6f738ab832b3beacab1e490e99a518))

## v2.8.2 (2022-03-17)
### Fix
* #63 module album search crash ([`3f2fcfb`](https://github.com/iamtalhaasghar/yewtube/commit/3f2fcfb27bb60928282d1a4a68adff22980f5938))

## v2.8.1 (2022-03-08)
### Fix
* #54 play video using youtube short link ([`92d1c77`](https://github.com/iamtalhaasghar/yewtube/commit/92d1c776d4bcc47509becadc5ba9248477dc0dcc))
* Use mkdocs instead of sphinx docs ([`32a2e9c`](https://github.com/iamtalhaasghar/yewtube/commit/32a2e9cdddac3ebb458d7bdcd793ed83ccc2fdf0))

## v2.8.0 (2022-02-28)
### Feature
* **helptext:** Help changelog ([`0643941`](https://github.com/iamtalhaasghar/yewtube/commit/06439411d7a78fe6701f7313e9b3b0720248a197))
* **setup:** Extras dependencies for mpris ([`936e890`](https://github.com/iamtalhaasghar/yewtube/commit/936e8909b5212eda3a64e8b93be79d4353e6d646))

### Fix
* #37 use `set pages` command to config how many search result pages to show ([`2baec5f`](https://github.com/iamtalhaasghar/yewtube/commit/2baec5fd11c0edf88d3543dd81333c5ecf67c918))
* #44 dont run init when importing mps_youtube ([`a072c22`](https://github.com/iamtalhaasghar/yewtube/commit/a072c22e2781160bca79d0164e46e49f07ac28e1))
* **mpris:** Handle no data on time-pos ([`8bb29d3`](https://github.com/iamtalhaasghar/yewtube/commit/8bb29d33825ad826e51d9d8eada32a9b7bd10ffd))
* #39 key error 'data' ([`834ed5b`](https://github.com/iamtalhaasghar/yewtube/commit/834ed5b0af5f92e1233e8ba327327654f67f61a0))
* #38 improved help menu responsiveness ([`972b4ef`](https://github.com/iamtalhaasghar/yewtube/commit/972b4efdb5fe8f5d3295b1c3fe607d209e7d39b6))
* #35 remove api key instructions ([`4f1fee3`](https://github.com/iamtalhaasghar/yewtube/commit/4f1fee3b711b2383b2704fba39bdce772894cc75))
* #24 colorama support for windows ([`9cf2616`](https://github.com/iamtalhaasghar/yewtube/commit/9cf261615a52f6ac64b6fb28390db2a71a7ab470))

## v2.7.0 (2022-02-19)
### Feature
* Use yewtube over tor using torsocks 🔥 ([`1e9c4ce`](https://github.com/iamtalhaasghar/yewtube/commit/1e9c4ce5992528286f552c8b563daef4abf9566a))

## v2.6.9 (2022-02-19)
### Fix
* #28 show changelog with `help new` command ([`d52b65d`](https://github.com/iamtalhaasghar/yewtube/commit/d52b65d0c0cd8708020a2d6788102d82d8ebeee5))

## v2.6.8 (2022-02-19)
### Fix
* fixed #26 album search working now without youtube api ([`9c3ae03`](https://github.com/iamtalhaasghar/yewtube/commit/9c3ae03b8c0ae006f1b9a917e4330270fec2f929))

## v2.6.7 (2022-02-19)
### Fix
* Check for app updates ([`eabfb52`](https://github.com/iamtalhaasghar/yewtube/commit/eabfb5233c7b87c5f300ebc41250a3f52db07411))
* Don't crash if playlists / history file has invalid youtube id fixed #24 ([`323d5d8`](https://github.com/iamtalhaasghar/yewtube/commit/323d5d822cefc23889665d71cfffe9e40750433b))

## v2.6.6 (2022-02-18)
### Fix
* Playlists are working again fixed #18 ([`bfceee4`](https://github.com/iamtalhaasghar/yewtube/commit/bfceee493261d099c85bf2c4c9e79e5710e9799f))
* Buffersize warning ([`d185c3f`](https://github.com/iamtalhaasghar/yewtube/commit/d185c3fdf8d520bcb4595f5e458d6022a7b6d1aa))
* **g:** Mpv msglevel ([`062b125`](https://github.com/iamtalhaasghar/yewtube/commit/062b12503a8fa15dc720cf3ac91f001b74a5cf10))

## v2.6.5 (2022-02-17)
### Fix
* Default player priority is vlc > mpv > mplayer on first install fixed #16 ([`35409eb`](https://github.com/iamtalhaasghar/yewtube/commit/35409eb31cc67f03c50589e02cdff2ad08fe4911))
* **mplayer:** _get_mplayer_version ([`ab21c5d`](https://github.com/iamtalhaasghar/yewtube/commit/ab21c5d1bc872ed482bf482ad37949129c1e4f78))
* Bring back requirements.txt to life ([`ff6e59d`](https://github.com/iamtalhaasghar/yewtube/commit/ff6e59d75834c61d72ec6bbc92f5eb339cc82607))
* **util.uea_pad:** Handle AttributeError on t.split ([`1643266`](https://github.com/iamtalhaasghar/yewtube/commit/1643266f21ccf7a99481a1615b4a53c4fbabc878))

## v2.6.4 (2022-02-16)
### Fix
* Duplicate changelog and readme files ([`0265ef7`](https://github.com/iamtalhaasghar/yewtube/commit/0265ef7507b539791684bdcf40b30ddaafc525e8))

## v2.6.3 (2022-02-16)
### Fix
* Welcome from semantic release python ([`c237a68`](https://github.com/iamtalhaasghar/yewtube/commit/c237a6808869062036f5196775352c1504eafe06))

# yewtube was forked from mps-youtube
### Features
* was made to work without YouTube API v3
* play music in vlc with no gui
<br>
<br>
<hr>
<br>
<br>
Version 0.2.8
17 February 2018

Features:
---------

- Lastfm scrobbling (@rien333) (#758)
- `splaylist` and `suser` commands for Spotify (@ritiek) (#678)
- Autoplay support (@nikhilweee) (#594)
- `genpl` command (@nishanthkarthik) (#642)
- `video_format` configuration setting (@Vrihub) (#656)
- `live` command for live streams (@Razesdark) (#635)
- Add time column (@akaWolf) (#582)
- Add video ID column (@Razesdark) (#627)
- Allow filtering search by duration (@jas32096) (#548)
- Allow filtering search by date (@jas32096) (#553)
- Add `history recent` to display history without duplicates (@srvanrell) (#510)
- `--no-textart` to disable ascii art (for screenreaders) (@Gongreg) (#517)
- `set_title` option to disable setting window title (@ardrabczyk) (#498)
- Add `s` command for getting stream information (@ritiek) (#675)
- Add option to disable mpris (@hrnr) (#728)
- Generate playlist from video description (@Razesdark) (#649)

Enhancements:
-------------
- Store playlists as m3u files instead of binary (@kraetzin) (#682)
- Show replies when displaying comments (@paulfertser) (#677)
- Use https urls for album art (@vszakats) (#574)
- When using "repeat" with mpv, keep player running (@ritiek) (#660)
- Display artist/album in mpris using lastfm (@vn-ki) (#739)
- Use channel.list API for user search (@Razesdark) (#628)
- Maintain volume across songs with mpv (@Razesdark) (#720)
- Prevent mpris from crashing the main process (@hrnr) (#728)

Bug fixes:
----------
- Fix mpris seeking with recent mpv vesions (@mg6) (#687)
- Fix removing video from multi-page playlist (@kraetzin) (#695)
- Skip unavailable tracks (@ritiek) (#734)
- Correctly display minutes/seconds (@Laxa) (#748)
- Handle `null` time-pos from mpv (@pritambaral) (#519)
- Fix da/dv command regex (@Vrihub) (#691)
- Skip channels in video/playlist searches (@ritiek) (#664)
- Fix divide by zero error (@ids1024) (#620)

Use `git log v0.2.7.1..v0.2.8` to see all changes, including various minor
fixes, documentation changes, etc. not included here.

-------------------------------------------------------------------------------

Version 0.2.7.1
6 July 2016

Bug fixes:
----------
- Fix pickle error (@ids1024) (#503)
- Install LICENSE, README.md, and CHANGELOG as package_data (@ids1024)
- Update youtube-dl in py2exe build (@ids1024)

-------------------------------------------------------------------------------

Version 0.2.7
27 June 2016

Features:
---------
- Setting for default audio format (@nishanthkarthik) (#71 #466 #467)
- Search history with `history` command (@kraetzin) (#344 #472)
- Add syntax for repeating a track several times (@ghallak) (#437 #490)
- Reverse command (@kraetzin) (#422 #473)
- New `daurl <url>` command (@maricn) (#402)

Enhancements:
-------------
- Pass `--no-ytdl` to mpv (@ids1024) (#492)
- Do not suppress mpv output in debug mode (@ids1024)
- Print traceback in debug mode (@ids1024)
- Speed up `checkupdate` by avoiding redirects (@ids1024) (#454)
- Pass `--play-and-exit` if vlc is used as a player (@ids1024)`

Bug fixes:
----------
- Fix error with python 3.3 (@ids1024) (#414)
- Fix maxres bug (@ids1024) (#430)
- Fix playlist cache bug in info command (@ids1024) (#468)
- Fix usersearch argument error (@ids1024) (#469 #482)
- Fix progress bar with new mpv versions (@ids1024) (#470 #485)
- Fix syntax error with set command (@ids1024) (#419)
- Fix syntax error with -w, -f, -a (@ids1024) (#420)
- Fix clipboard support (@ids1024) (#461)
- Fix mpv version checking on windows (@ids1024) (#397)
- Add youtube_dl as dependency to Dockerfile (@PI-Victor) (#481)

Internal api changes:
---------------------
- The code is now split between several files (@ids1024) (#208)
- Add initial content api, for now only used for comments (@ids1024)
- Begin documenting internal apis using sphinx (@ids1024)

-------------------------------------------------------------------------------

Version 0.2.6
1 January 2016

Features:
- Add browserplay command to play video in browser (rjvani) (#355 #390)
- Make url command support multiple url, and allow loading urls from file
    (paulnicolet) (#90 #391)
- Make youtube id available to download command (ids1024) (#375)
- Make pagination work properly for all lists of songs (local playlists, etc.)
    and make them all support the dump command (ids1024) (#201)
- Show warning when adding duplicate track to playlist (BensonQiu) (#374 #383)

Bug fixes:
- Support playlists longer than 200 items (ids1024) (#192)
- Make dapl download complete playlist (JKatzwinkel) (#294 #325)
- Use pyperclip instead of xerox, fixing clipboard on linux (ids1024) (#311)
- Fix error message on windows when video title has & (ids1024) (#321)
- Run notifier command in background (hrnr) (#339)
- Correctly handle -v option of play (TimoDritschler) (#352)
- Make it possible to use a pager with --help (livingBEEF) (#349)
- Allow mplayer for https streams if version is new enough
    (ids1024 Evidlo paddatrapper) (#315 #336 #317)
- Use mpv.com instead of mpv.exe on windows (ids1024)

Internal API changes:
- Split code into several files (still a work in progress) (ids1024) (#208)
- Use a python decorator to declare commands (ids1024)
- Create a paginatesongs() function for handling the pagination and dump
  command uniformly as mentioned in features (#399) (ids1024)
- Various others

There have been various other small bug fixes and internal API changes. Use
`git log v0.2.5..0.2.6` to see all of them.

-------------------------------------------------------------------------------

Version 0.2.5
1 June 2015

- Support python 3 only (will not run with python 2)
- Fix progress bar bug on Windows (#215, #223)
- Fix bug in playlist search (#282)
- Add user_order setting for separate order of user searches (lol768) (#277)
- Add mix command (lol768) (#241, #283)
- Add page count with total number of pages and current page (JKatzwinkel)
- Fix UnicodeEncodeError on non-unicode terminals
- Install .desktop in setup.py so it does not have to be installed manually
    required for Ubuntu sound menu support

-------------------------------------------------------------------------------

Version 0.2.4
13 May 2015

 - Fix issue with rate-limiting in "album" command (#217)
 - Implement support for MPRIS (hrnr and ids1024) (#191, #210)
 - Fix display issue with small terminal width (#215)
 - Use version 3 of the youtube api (JKatzwinkel, ids1024, and lol768) (#256)
     version 2 was disabled by youtube and no longer works

-------------------------------------------------------------------------------

Version 0.2.3
17 February 2015

 - Fix issue with opening old playlist file (#214)
 - Fix issue with "set" command
 - Metadata tagging of downloaded audio files
     requires ffmpeg or avconv
     early implementation, uses YouTube video title, needs more work

-------------------------------------------------------------------------------

Version 0.2.2
14 February 2015

- Implement skip to previous track (ids1024) #175 #18 #14
    Use > and < keys for next and prev track, q for quit (was ctrl-c)
    mpv / mplayer input.conf can be imported to use custom keymappings

- Implement optional external download application (ids1024 and np1) #198 #132
    enter "help dl-command" for more info

- Show stream quality on status line (Brebiche38) #134 #163

- Implement support for creating Windows builds with py2exe (ids1024) #190
    Use setup.py in py2exe branch

- Fix progress bar for mpv 0.7 (ids1024) #155 #161
    Resolves issues with playback looping

- Fix mps-youtube does not run on FreeBSD (nivit)

- Fix YouTube comments overshoot window size

- Fix issue with audio remux when using `d` download command

-------------------------------------------------------------------------------

Version 0.2.1
27 November 2014

[Bugfix] - Detect installed player on installation (#149)

-------------------------------------------------------------------------------

Version 0.2.0
25 November 2014

- Auto detect terminal window size

- Transcode audio to MP3 and other formats (requires ffmpeg or avconv)

- Enabled da and dv commands for playlist search results

- Added dapl and dvpl to download YouTube playlist audio/video
    by url/id to a separate subdirectory (mtahmed) #110

- Progress indicator now works with mpv (previously only mplayer)

- Added option to show system notifications (Alex Nisnevich) #95
    (can be used with libnotify - notify-send on linux)

- Added overwrite true/false option for downloads (mtahmed) #93
    (skips download if downloaded file already exists)

- Added copy to clipboard feature #97
    (requires python xerox module and xclip on linux or pywin32 on windows)

- Remux audio downloads for better file compatibility (#135)

[Bugfix] - Accept two-character length usernames (#99)

[Bugfix] - Expand ~ character in download directory setting (punchagan)

[Bugfix] - Don't truncate filename (YoussF) #122

[Bugfix] - Exit with correct status code

-------------------------------------------------------------------------------

Version 0.01.46
May 18 2014

 - Added c <number> to view comments for a video
    (first 50 comments, no reply-comments)

 - Added feature to match album tracks using MusicBrainz (vixus0)
    To search albums, enter "album" optionally followed by album title

 - Custom formatted search result list using "set columns" command
   Optionally shows: rating, likes, dislikes, views, user, date, category
   and comments (number of) in search results

 - Added "set order <relevance|views|rating|date>" command for
     specifying search result ordering

 - Added "set console-width" for setting output width (default 80)

 - Added uploaded date in video info display (request #64)

 - Added likes / dislikes in video info display

-------------------------------------------------------------------------------

Version 0.01.44
Mar 27 2014

 - Added max_res config item for selecting video resolution (request 56)
 - Added window_size and window_pos for selecting size / position of player
 - Improved handling of playlist file read/write (issue 66)
 - Revert to lower quality on unavailable/corrupt streams (issue 65)
 - Enabled multiple invocation commands (comma separated) (request 61)
    Eg: mpsyt //the doors, 1, shuffle, 1-3-a, quit
 - Improved url caching
 - Added shuffle command (no arguments, shuffles displayed items)
 - Handle 'video not available in your country' during multiple downloads
 - Fix UnicodeDecodeError in mplayer progress parsing (issue 58)
 - Fix UnicodeEncodeError under Windows with Python 2.7 (issue 59)

-------------------------------------------------------------------------------

Version 0.01.41
Mar 14 2014

 - new configuration option, max_results - sets number of returned results
    (1 - 50)
 - pl <url> now accepts YouTube playlist id's as well as url's
 - Fix error in download of .m4a files when mplayer is set as player.
 - Added option for downloading multiple items
     eg. da 1-4 or dv 3,5,6

-------------------------------------------------------------------------------

Version 0.01.40
Mar 11 2014

 - Bugfix release, corrects UnicodeDecode error

-------------------------------------------------------------------------------

Version 0.01.39
Mar 10 2014

Features:
 - Added time / progress bar indicator. Big thanks to Thomas LÉVEIL!
    (mplayer only)
 - Added command to retrieve YouTube user playlists; 
    userpl {username} or upl {username}
 - Added command to retrieve related videos; r{number}
 - playurl now respects -f, -w, and -a flags (fullscreen, window or audio)
 - Implemented input history persistence (uses readline, linux only)
 - Implemented non-interactive mode for command line invocation with playurl
 - Implemented less interactive mode for command line invocation with dlurl

Changes:
 - // or .. prefix to search for YouTube playlists (was plsearch / pls)

Help / Documentation:
 - help <command> will show relevant help topic page e.g., help dlurl
 - Documented configuration options ("set" commands)
 - Re-authored some help categories
 - Changed help <number> to help <topic>, removed menu from help pages

Bugfixes
 - mplayer / mpv window now displays content title instead of url
 - Fixed issue with Python3 terminal output on playback ctrl-c interrupt
 - Fixed issue with debug mode not logging to file
 - Changed year format in YT playlist result screen to last two digits.
      (Under some environments it was showing 4-digit years)

-------------------------------------------------------------------------------

Version 0.01.38
Mar 5 2014

 - Added i<number> for YT playlist information display 
 - Added stream url preloading for first item of opened YT playlists
 - Added last-updated date to YT playlist search result list 
 - Fixed UnicodeError when run in non-UTF8 environments
 - Added more verbosity to --version command line option
 - Added --debug command line option (logs to <tmpdir>/mpsyt.log)

-------------------------------------------------------------------------------

Version 0.01.37
Mar 2 2014

 - Excluded YouTube paid videos from search results
 - Added "pl <playlist url>" command to open YouTube playlist url
 - Added "plsearch <query>" command to search for YouTube playlists
 - Added "dump" command to show entire YT playlist (useful for saving locally)
 - Added "undump" command to undo dump (re-paginates YT playlist items)
 - Added "u <number>" command to list uploads by uploader of <number>
 - Added "url <YouTube url>" command for retrieving a specific YT video
 - Added "playurl <YouTube url>" command for directly playing a YT video
 - Added "dlurl <YouTube url>" command for directly downloading a YT video
 - Changed command to list user uploads, new syntax is "user <username>"
 - Added mpsyt --version flag for printing version info
 - Added mpsyt --help flag for printing help text
 - Fixed indentation bug when scrolling through readline history

-------------------------------------------------------------------------------

Version 0.01.36
Feb 27 2014

 - Wait for preloading item if it is selected while preloading
 - Fix bug where -a audio override is sometimes ignored

-------------------------------------------------------------------------------

Version 0.01.35
Feb 25 2014

 - Faster opening of audio streams with mpv 
    (--demuxer-lavf-o=fflags=+ignid argument added for m4a streams)

 - Faster opening of audio streams with mplayer 
    (reject m4a streams, prefer ogg streams)
    (fallback to video stream and suppress video when no ogg available)

-------------------------------------------------------------------------------

Version 0.01.34
Feb 22 2014

 - Fix bug: fails when no playlist file exists

-------------------------------------------------------------------------------

Version 0.01.33
Feb 22 2014

 - Changed structure of playlist file. Now consumes KB's rather than MB's
 - Same playlist file shared between Python2.7+ and Python3+ (was separate)
 - Improved display alignment for Russian text
 - Preload of url fails silently on unobtainable items (previously crashed)
 - Added prompt to mux audio on m4v download (experimental)

-------------------------------------------------------------------------------

Version 0.01.32
Feb 17 2014

 - Improve display alignment with certain unicode characters
 - Fix crash when using 'set' command on Windows (thomasleveil)

-------------------------------------------------------------------------------

Version 0.01.31
Feb 13 2014

 - Migrate location of config directory to reflect new name
   (~/.config/mps-youtube)



================================================
FILE: CONTRIBUTING.md
================================================
# Contributing for yewtube

Contributions are very much appreciated!

* Pull requests should be based on and submitted to the "develop" branch.

* Please raise an issue to discuss what you plan to implement or change before 
you start if it is going to involve a lot of work on your part.

* Please keep pull requests specific, do not make many disparate changes or
new features in one request.  A separate pull request for each feature change
is preferred.

* Please ensure your changes work in Python 3.3+ and Windows.


## Code conventions

* Maximum line length is 80 characters

* Follow the line-spacing style that is already in place.

* Ensure all functions and classes have a PEP257 compliant docstring and the
code is PEP8 compliant.

## Documentation

Install required extra docs package to setup mkdocs: `pip install -e ".[docs]"`

To run built-in dev server: `mkdocs serve`

To deploy documentation to github page: `mkdocs gh-deploy`


================================================
FILE: Dockerfile
================================================
FROM python:3-stretch

LABEL maintainer="Justin Garrison <justinleegarrison@gmail.com>" \
    org.label-schema.schema-version="1.0" \
    org.label-schema.name="mps-youtube" \
    org.label-schema.description="Terminal based YouTube player and downloader " \
    org.label-schema.url="https://github.com/mps-youtube/mps-youtube/wiki" \
    org.label-schema.vcs-url="https://github.com/mps-youtube/mps-youtube" \
    org.label-schema.docker.cmd="docker run -v /dev/snd:/dev/snd -it --rm --privileged --name mpsyt mpsyt"

RUN DEBIAN_FRONTEND=noninteractive && \
    apt-get update && \
    apt-get install -y mplayer mpv && \
    rm -rf /var/lib/apt/lists/* && \
    apt-get clean && apt-get purge

RUN pip install mps-youtube youtube-dl

ENTRYPOINT ["mpsyt"]


================================================
FILE: ISSUE_TEMPLATE.md
================================================
<!--- Provide a general summary of the issue in the Title above -->

## Issue / Suggestion
<!--- If you're describing a bug, tell us what error you are experiencing -->
<!--- Tell us which command you entered inside yewtube that caused the bug so that we can recreate the problem on our end to analyse problem -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->

## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
<!--- Run "mpsyt --version" and post your version information here --->
<!-- What version of the OS are you running, any other  -->
<!-- What music player are you using with mps-youtube, version? -->


================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/}
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    {one line to give the program's name and a brief idea of what it does.}
    Copyright (C) {year}  {name of author}

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see {http://www.gnu.org/licenses/}.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
{http://www.gnu.org/licenses/}.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
{http://www.gnu.org/philosophy/why-not-lgpl.html}.


================================================
FILE: MANIFEST.in
================================================
include mps-youtube.desktop
include LICENSE
include README.md
include CHANGELOG.md


================================================
FILE: README.md
================================================

![](https://img.shields.io/pypi/v/yewtube.svg)  ![](https://img.shields.io/pypi/wheel/yewtube.svg)

<pre>
                      _         _          
                     | |       | |         
  _   _  _____      _| |_ _   _| |__   ___ 
 | | | |/ _ \ \ /\ / / __| | | | '_ \ / _ \
 | |_| |  __/\ V  V /| |_| |_| | |_) |  __/
  \__, |\___| \_/\_/  \__|\__,_|_.__/ \___|
   __/ |                                   
  |___/


</pre>


 Terminal based YouTube player and downloader. No Youtube API key required. Forked from mps-youtube 

Installation
-----------
# Stable Version

### Using pip
1. Install using `pip install yewtube`
2. Run using, `yt`. Enjoy! 

### Using pipx (Recommended)
1.  Install **_pipx_** using `pip install pipx`
2.  Install `yewtube` using `pipx install yewtube`
3.  Now, type `yt` That's it.

# Latest Version

### Using pip
1. Install using `pip install git+https://github.com/iamtalhaasghar/yewtube.git`
2. Run using, `yt`. Enjoy! 

### Using pipx
1.  Install **_pipx_** using `pip install pipx`
2.  Install `yewtube` using `pipx install git+https://github.com/iamtalhaasghar/yewtube.git`
3.  Now, type `yt` That's it.

What's new in yewtube?
----------------------
-   **No Youtube API Key required**
-   **Run audio in VLC with no GUI**

See complete and up-to-date changelog [here](https://github.com/iamtalhaasghar/yewtube/blob/master/CHANGELOG.md).

These features are still inherited from [mps-youtube](https://github.com/mps-youtube/mps-youtube).
-   Search and play audio/video from YouTube
-   Search tracks of albums by album title
-   Search and import YouTube playlists
-   Create and save local playlists
-   Download audio/video
-   Convert to mp3 & other formats (requires ffmpeg or avconv)
-   View video comments
-   Works with Python 3.x
-   Works with Windows, Linux and Mac OS X
-   Requires mplayer, mpv or VLC

This project is based on [mps-youtube](https://github.com/mps-youtube/mps-youtube) and mps-youtube is based on [mps](https://web.archive.org/web/20180429034221/https://github.com/np1/mps), a terminal based program to search, stream and download music. This
implementation uses YouTube as a source of content and can play and
download video as well as audio. The [pafy](https://github.com/mps-youtube/pafy)  library handles interfacing with YouTube.

[mps-youtube wiki](https://github.com/mps-youtube/mps-youtube/wiki/Troubleshooting) <br>
[yewtube wiki](https://github.com/iamtalhaasghar/yewtube/wiki/FAQ)

Screenshots
-----------

Search:<br>
![](http://mps-youtube.github.io/mps-youtube/std-search.png)

A standard search is performed by entering `/` followed by search terms.

You can play all of the search results by giving `1-` as input

Repeating song/songs can be done with `song_number[loop]`, for example:
`1[3]` or `4-6[2]`

Local Playlists:<br>
![](http://mps-youtube.github.io/mps-youtube/local-playlist.png)

Search result items can easily be stored in local playlists.

YouTube Playlists:<br>
![](http://mps-youtube.github.io/mps-youtube/playlist-search.png)

YouTube playlists can be searched and played or saved as local
playlists.

A playlist search is performed by `//` followed by search term.

Download:<br>
![](http://mps-youtube.github.io/mps-youtube/download.png)

Content can be downloaded in various formats and resolutions.

Comments:<br>
![](http://mps-youtube.github.io/mps-youtube/comments.png)

A basic comments browser is available to view YouTube user comments.

Music Album Matching:<br>

![](http://mps-youtube.github.io/mps-youtube/album-1.png)

![](http://mps-youtube.github.io/mps-youtube/album-2.png)

An album title can be specified and yewtube will attempt to find
matches for each track of the album, based on title and duration. Type
`help search` for more info.

Customisation:<br>

![](http://mps-youtube.github.io/mps-youtube/customisation2.png)

Search results can be customised to display additional fields and
ordered by various criteria.

This configuration was set up using the following commands
```
set order views
set columns user:14 date comments rating likes dislikes category:9 views
```

Type `help config` for help on configuration options

Upgrading
---------

### If installed using pipx

` pipx upgrade yewtube `

### If installed using pip

`pip install --upgrade yewtube`

Usage
-----

yewtube is run on the command line using the command:

   `yt`

Enter `h` from within the program for help.


Using yewtube with mpris
------------------------

1. Install PyGObject, GTK and their dependencies based on this guide https://pygobject.readthedocs.io/en/latest/getting_started.html
2. Install yewtube with mpris extra

```shell
> # recommended
> pipx install 'yewtube[mpris]'
> # or
> pip install 'yewtube[mpris]'
```

3. check yewtube version

```shell
> yt --version
yewtube version    : 2.8.2
yt_dlp version     : 2022.02.04
Python version     : 3.9.7 (default, Nov  7 2021, 15:17:57)
[GCC 11.2.0]
Processor          : x86_64
Machine type       : x86_64
Architecture       : 64bit, ELF
Platform           : Linux-5.13.0-35-generic-x86_64-with-glibc2.34
sys.stdout.enc     : utf-8
default enc        : utf-8
Config dir         : /home/user/.config/mps-youtube
dbus               : 1.2.18
glib               : True
env:TERM           : tmux-256color
env:SHELL          : /usr/bin/zsh
env:LANG           : en_US.UTF-8
```

If everything working correctly, dbug and glib would have similar result as above text

4. run `set mpris true` on yewtube
5. check with `playerctl`

```shell
> playerctl -l
mps-youtube.instance567867
```

Check also the [common-issue](https://github.com/iamtalhaasghar/yewtube/wiki/Common-issues) if you are having problem with yewtube.

How to Contribute
-----------------

Contributions are welcomed! However, please check out the [contribution page](https://github.com/iamtalhaasghar/yewtube/blob/master/CONTRIBUTING.md) before making a contribution.


================================================
FILE: RELEASING.md
================================================
Release process for pafy and mps-youtube
========================================

Looking at the commits and Github releases for previous versions can provide an example.

Version numbers
---------------
### pafy
Bump the `__version__` in `__init__.py`.

### mps-youtube
Bump the `version` in `VERSION`, `__version__` and `__notes__` in `__init__.py`, and `VERSION` in `setup.py`.

Changelogs
----------
Update `CHANGELOG` with a summary of changes since the last release. `git shortlog` can be helpful to see what commits have occurred.

### mps-youtube
Also update `New Features` in `helptext.py`. This help section has ended up falling out of date. If it isn't kept up to date, it should probably be removed.

Github Release
--------------
Create a release through the Github website, tagging the commit that should be released. The text from the `CHANGELOG` should be copied to the release.

py2exe
------
For mps-youtube, a `.exe` file should be built with `python setup.py py2exe` under Windows. Make sure the correct pafy and youtube-dl versions are being used, since they will be embedded in the binary. Attach this file to the Github release.

PyPI
----
Push the source, and a wheel build, to PyPI. Be careful that everything is correct at this point; PyPI does not allow replacing an uploaded file with a different one of the same name.

GPG Signatures
--------------
The `.tar.gz` signatures for `pafy` and `mps-youtube` also have GPG signatures attached to the release. Currently, they are signed with @ids1024's key, so only he can perform this step.

Possible Simplifications to this Process
----------------------------------------
The New Features help text isn't really important, but it is genuinely nice to have if kept up to date.

Perhaps the `CHANGELOG` file isn't really needed, if Github releases includes that information.


================================================
FILE: _config.yml
================================================
theme: jekyll-theme-hacker

================================================
FILE: doc/conf.py
================================================
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mps_youtube documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 18 17:35:31 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sphinx_rtd_theme

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.todo',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'mps_youtube'
copyright = '2016, mps-youtube developers'
author = 'mps-youtube developers'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True


# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#html_theme = 'alabaster'
html_theme = "sphinx_rtd_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#html_title = 'mps_youtube v'

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#html_last_updated_fmt = None

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'
#html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'mps_youtubedoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',

# Latex figure (float) alignment
#'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, 'mps_youtube.tex', 'mps\\_youtube Documentation',
     'Author', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'mps_youtube', 'mps_youtube Documentation',
     [author], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False


# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (master_doc, 'mps_youtube', 'mps_youtube Documentation',
     author, 'mps_youtube', 'One line description of project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False


# -- Options for Epub output ----------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright

# The basename for the epub file. It defaults to the project name.
#epub_basename = project

# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to save
# visual space.
#epub_theme = 'epub'

# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''

# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''

# A unique identification for the text.
#epub_uid = ''

# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()

# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()

# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []

# HTML files that should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3

# Allow duplicate toc entries.
#epub_tocdup = True

# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'

# Fix unsupported image types using the Pillow.
#epub_fix_images = False

# Scale large images.
#epub_max_image_width = 0

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'

# If false, no index is generated.
#epub_use_index = True


================================================
FILE: doc/index.rst
================================================
.. mps_youtube documentation master file, created by
   sphinx-quickstart on Mon Apr 18 17:35:31 2016.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

API Documentation for mps_youtube
=================================

Contents:

.. toctree::
   mps_youtube


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`



================================================
FILE: doc/modules.rst
================================================
mps_youtube
===========

.. toctree::
   :maxdepth: 4

   mps_youtube


================================================
FILE: doc/mps_youtube.c.rst
================================================
mps_youtube.c module
====================

.. automodule:: mps_youtube.c
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.cache.rst
================================================
mps_youtube.cache module
========================

.. automodule:: mps_youtube.cache
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.album_search.rst
================================================
mps_youtube.commands.album_search module
========================================

.. automodule:: mps_youtube.commands.album_search
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.config.rst
================================================
mps_youtube.commands.config module
==================================

.. automodule:: mps_youtube.commands.config
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.download.rst
================================================
mps_youtube.commands.download module
====================================

.. automodule:: mps_youtube.commands.download
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.local_playlist.rst
================================================
mps_youtube.commands.local_playlist module
==========================================

.. automodule:: mps_youtube.commands.local_playlist
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.misc.rst
================================================
mps_youtube.commands.misc module
================================

.. automodule:: mps_youtube.commands.misc
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.play.rst
================================================
mps_youtube.commands.play module
================================

.. automodule:: mps_youtube.commands.play
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.rst
================================================
mps_youtube.commands package
============================

Submodules
----------

.. toctree::

   mps_youtube.commands.album_search
   mps_youtube.commands.config
   mps_youtube.commands.download
   mps_youtube.commands.local_playlist
   mps_youtube.commands.misc
   mps_youtube.commands.play
   mps_youtube.commands.search
   mps_youtube.commands.songlist

Module contents
---------------

.. automodule:: mps_youtube.commands
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.search.rst
================================================
mps_youtube.commands.search module
==================================

.. automodule:: mps_youtube.commands.search
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.commands.songlist.rst
================================================
mps_youtube.commands.songlist module
====================================

.. automodule:: mps_youtube.commands.songlist
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.config.rst
================================================
mps_youtube.config module
=========================

.. automodule:: mps_youtube.config
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.content.rst
================================================
mps_youtube.content module
==========================

.. automodule:: mps_youtube.content
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.g.rst
================================================
mps_youtube.g module
====================

.. automodule:: mps_youtube.g
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.helptext.rst
================================================
mps_youtube.helptext module
===========================

.. automodule:: mps_youtube.helptext
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.history.rst
================================================
mps_youtube.history module
==========================

.. automodule:: mps_youtube.history
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.init.rst
================================================
mps_youtube.init module
=======================

.. automodule:: mps_youtube.init
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.main.rst
================================================
mps_youtube.main module
=======================

.. automodule:: mps_youtube.main
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.mpris.rst
================================================
mps_youtube.mpris module
========================

.. automodule:: mps_youtube.mpris
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.paths.rst
================================================
mps_youtube.paths module
========================

.. automodule:: mps_youtube.paths
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.player.rst
================================================
mps_youtube.player module
=========================

.. automodule:: mps_youtube.player
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.playlist.rst
================================================
mps_youtube.playlist module
===========================

.. automodule:: mps_youtube.playlist
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.playlists.rst
================================================
mps_youtube.playlists module
============================

.. automodule:: mps_youtube.playlists
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.rst
================================================
mps_youtube package
===================

Subpackages
-----------

.. toctree::

    mps_youtube.commands

Submodules
----------

.. toctree::

   mps_youtube.c
   mps_youtube.cache
   mps_youtube.config
   mps_youtube.content
   mps_youtube.g
   mps_youtube.helptext
   mps_youtube.history
   mps_youtube.init
   mps_youtube.main
   mps_youtube.mpris
   mps_youtube.paths
   mps_youtube.player
   mps_youtube.playlist
   mps_youtube.playlists
   mps_youtube.screen
   mps_youtube.streams
   mps_youtube.terminalsize
   mps_youtube.util

Module contents
---------------

.. automodule:: mps_youtube
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.screen.rst
================================================
mps_youtube.screen module
=========================

.. automodule:: mps_youtube.screen
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.streams.rst
================================================
mps_youtube.streams module
==========================

.. automodule:: mps_youtube.streams
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.terminalsize.rst
================================================
mps_youtube.terminalsize module
===============================

.. automodule:: mps_youtube.terminalsize
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: doc/mps_youtube.util.rst
================================================
mps_youtube.util module
=======================

.. automodule:: mps_youtube.util
    :members:
    :undoc-members:
    :show-inheritance:


================================================
FILE: docs/changelog.md
================================================
--8<-- "CHANGELOG.md"


================================================
FILE: docs/contributing.md
================================================
--8<-- "CONTRIBUTING.md"


================================================
FILE: docs/css/mkdocstrings.css
================================================
/* Indentation. */
div.doc-contents:not(.first) {
  padding-left: 25px;
  border-left: 4px solid rgba(230, 230, 230);
  margin-bottom: 80px;
}

/* Don't capitalize names. */
h5.doc-heading {
  text-transform: none !important;
}

/* Don't use vertical space on hidden ToC entries. */
.hidden-toc::before {
  margin-top: 0 !important;
  padding-top: 0 !important;
}

/* Don't show permalink of hidden ToC entries. */
.hidden-toc a.headerlink {
  display: none;
}

/* Avoid breaking parameters name, etc. in table cells. */
td code {
  word-break: normal !important;
}

/* For pieces of Markdown rendered in table cells. */
td p {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}


================================================
FILE: docs/gen_ref_nav.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate the code reference pages and navigation."""

from pathlib import Path

import mkdocs_gen_files

nav = mkdocs_gen_files.Nav()

skip_files = [
    (Path("mps_youtube") / "config.py"),
    (Path("mps_youtube") / "mpris.py"),
]
skip_files.extend((Path("mps_youtube") / "test").glob("*.py"))
for path in sorted(Path("mps_youtube").glob("**/*.py")):
    if path in skip_files:
        continue
    module_path = path.with_suffix("")
    doc_path = path.relative_to("mps_youtube").with_suffix(".md")
    full_doc_path = Path("reference", doc_path)

    parts = list(module_path.parts)
    parts[-1] = f"{parts[-1]}.py"
    nav[parts] = doc_path

    with mkdocs_gen_files.open(full_doc_path, "w") as fd:
        ident = ".".join(module_path.parts)
        print("::: " + ident, file=fd)

    mkdocs_gen_files.set_edit_path(full_doc_path, path)

with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file:
    nav_file.writelines(nav.build_literate_nav())


================================================
FILE: docs/index.md
================================================
--8<-- "README.md"


================================================
FILE: docs/license.md
================================================
```
--8<-- "LICENSE"
```


================================================
FILE: mkdocs.yml
================================================
site_name: Yewtube
site_description: Terminal based YouTube player and downloader.
site_url: https://iamtalhaasghar.github.io/yewtube
repo_url: https://github.com/iamtalhaasghar/yewtube
repo_name: iamtalhaasghar/yewtube

nav:
- Home:
  - Overview: index.md
  - Changelog: changelog.md
  - License: license.md
- Code Reference: reference/
- Development:
  - Contributing: contributing.md

theme:
  name: material
  features:
  - navigation.tabs
  palette:
    scheme: slate
    primary: teal
    accent: purple

extra_css:
- css/mkdocstrings.css

markdown_extensions:
- admonition
- pymdownx.emoji
- pymdownx.magiclink
- pymdownx.snippets:
    check_paths: true
- pymdownx.superfences
- pymdownx.tabbed
- pymdownx.tasklist
- toc:
    permalink: true

plugins:
- search
- mkdocstrings:
    watch:
    - mps_youtube
- gen-files:
    scripts:
    - docs/gen_ref_nav.py
- literate-nav:
    nav_file: SUMMARY.md


================================================
FILE: mps_youtube/__init__.py
================================================
from pip._vendor import pkg_resources

__version__ = next((p.version for p in pkg_resources.working_set if p.project_name.lower() == 'yewtube'), "unable to determine")
__author__ = "iamtalhaasghar"
__license__ = "GPLv3"
__url__ = "https://github.com/iamtalhaasghar/yewtube"



================================================
FILE: mps_youtube/c.py
================================================
""" Module for holding colour code values. """

import os
import re
import sys


if sys.stdout.isatty():
    white = "\x1b[%sm" % 0
    ul = "\x1b[%sm" * 3 % (2, 4, 33)
    cols = ["\x1b[%sm" % n for n in range(91, 96)]
    red, green, yellow, blue, pink = cols
else:
    ul = red = green = yellow = blue = pink = white = ""

r, g, y, b, p, w = red, green, yellow, blue, pink, white

ansirx = re.compile(r'\x1b\[\d*m', re.UNICODE)

def c(colour, text):
    """ Return coloured text. """
    colours = {'r': r, 'g': g, 'y': y, 'b':b, 'p':p}
    return colours[colour] + text + w

def charcount(s):
    """ Return number of characters in string, with ANSI color codes excluded. """
    return len(ansirx.sub('', s))


================================================
FILE: mps_youtube/cache.py
================================================
import os
import pickle


from . import g, c, streams
from .util import dbg


# Updated every time incompatible changes are made to cache format,
# So old cache can be dropped
CACHE_VERSION = 1

def load():
    """ Import cache file. """
    if os.path.isfile(g.CACHEFILE):

        try:

            with open(g.CACHEFILE, "rb") as cf:
                cached = pickle.load(cf)

            # Note: will be none for yewtube 0.2.5 or earlier
            version = cached.get('version')

            if 'streams' in cached:
                if version and version >= 1:
                    g.streams = cached['streams']
                    g.username_query_cache = cached['userdata']
            else:
                g.streams = cached

            if 'pafy' in cached:
                pass
                #pafy.load_cache(cached['pafy'])

            dbg(c.g + "%s cached streams imported%s", str(len(g.streams)), c.w)

        except (EOFError, IOError):
            dbg(c.r + "Cache file failed to open" + c.w)

        streams.prune()


def save():
    """ Save stream cache. """
    caches = dict(
        version=CACHE_VERSION,
        streams=g.streams,
        userdata=g.username_query_cache
        #,pafy=pafy.dump_cache()
    )

    with open(g.CACHEFILE, "wb") as cf:
        pickle.dump(caches, cf, protocol=2)

    dbg(c.p + "saved cache file: " + g.CACHEFILE + c.w)


================================================
FILE: mps_youtube/commands/__init__.py
================================================
import collections
import re

from .. import g
from ..main import completer

Command = collections.namedtuple('Command', 'regex category usage function')

# input types
WORD = r'[^\W\d][-\w\s]{,100}'
RS = r'(?:(?:repeat|shuffle|-[avfw])\s*)'
PL = r'\S*?((?:RD|PL|LL|UU|FL|OL)[-_0-9a-zA-Z]+)\s*'

## @command decorator
##
## The @command decorator takes a single regex followed by one or more
## strings that corresponds to command names that will be added to
## the tab completion.
##
## If your command has short-forms, only register the longer
## forms.
## If you use several functions and regexes for the same command but different
## arguments, append the completion string on EACH function, not only
## the first time you register it.
def command(regex, *commands):
    """ Decorator to register an mps-youtube command. """
    for command in commands:
        completer.add_cmd(command)
    def decorator(function):
        cmd = Command(re.compile(regex), None, None, function)
        g.commands.append(cmd)
        return function
    return decorator


# Placed at bottom to deal with cyclic imports
from . import download, search, album_search, spotify_playlist, misc, config, local_playlist
from . import play, songlist, generate_playlist, lastfm


================================================
FILE: mps_youtube/commands/album_search.py
================================================
import re
import time
import difflib
from urllib.request import build_opener
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from xml.etree import ElementTree as ET


from .. import c, g, screen, __version__, __url__, config, util, pafy
from .. import content as content_py
from . import command
from .songlist import paginatesongs
from .search import get_tracks_from_json


def show_message(message, col=c.r, update=False):
    """ Show message using col, update screen if required. """
    g.content = content_py.generate_songlist_display()
    g.message = col + message + c.w

    if update:
        screen.update()


def _do_query(url, query, err='query failed', report=False):
    """ Perform http request using yewtube user agent header.

    if report is True, return whether response is from memo

    """
    # create url opener
    ua = "mps-youtube/%s ( %s )" % (__version__, __url__)
    mpsyt_opener = build_opener()
    mpsyt_opener.addheaders = [('User-agent', ua)]

    # convert query to sorted list of tuples (needed for consistent url_memo)
    query = [(k, query[k]) for k in sorted(query.keys())]
    url = "%s?%s" % (url, urlencode(query))

    try:
        wdata = mpsyt_opener.open(url).read().decode()

    except (URLError, HTTPError) as e:
        g.message = "%s: %s (%s)" % (err, e, url)
        g.content = content_py.logo(c.r)
        return None if not report else (None, False)

    return wdata if not report else (wdata, False)


def _best_song_match(songs, title, duration, titleweight, durationweight):
    """ Select best matching song based on title, length.

    Score from 0 to 1 where 1 is best. titleweight and durationweight
    parameters added to enable function usage when duration can't be guessed

    """
    # pylint: disable=R0914
    seqmatch = difflib.SequenceMatcher

    def variance(a, b):
        """ Return difference ratio. """
        return float(abs(a - b)) / max(a, b)

    candidates = []

    ignore = "music video lyrics new lyrics video audio".split()
    extra = "official original vevo".split()

    for song in songs:
        dur, tit = int(song.length), song.title
        util.dbg("Title: %s, Duration: %s", tit, dur)

        for word in extra:
            if word in tit.lower() and word not in title.lower():
                pattern = re.compile(word, re.I)
                tit = pattern.sub("", tit)

        for word in ignore:
            if word in tit.lower() and word not in title.lower():
                pattern = re.compile(word, re.I)
                tit = pattern.sub("", tit)

        replacechars = re.compile(r"[\]\[\)\(\-]")
        tit = replacechars.sub(" ", tit)
        multiple_spaces = re.compile(r"(\s)(\s*)")
        tit = multiple_spaces.sub(r"\1", tit)

        title_score = seqmatch(None, title.lower(), tit.lower()).ratio()
        duration_score = 1 - variance(duration, dur)
        util.dbg("Title score: %s, Duration score: %s", title_score,
                 duration_score)

        # apply weightings
        score = duration_score * durationweight + title_score * titleweight
        candidates.append((score, song))

    best_score, best_song = max(candidates, key=lambda x: x[0])
    percent_score = int(100 * best_score)
    return best_song, percent_score


def _match_tracks(artist, title, mb_tracks):
    """ Match list of tracks in mb_tracks by performing multiple searches. """
    # pylint: disable=R0914
    util.dbg("artists is %s", artist)
    util.dbg("title is %s", title)
    title_artist_str = c.g + title + c.w, c.g + artist + c.w
    util.xprint("\nSearching for %s by %s\n\n" % title_artist_str)

    def dtime(x):
        """ Format time to M:S. """
        return time.strftime('%M:%S', time.gmtime(int(x)))

    # do matching
    for track in mb_tracks:
        ttitle = track['title']
        length = track['length']
        util.xprint("Search :  %s%s - %s%s - %s" % (c.y, artist, ttitle, c.w,
                                                    dtime(length)))
        q = "%s %s" % (artist, ttitle)
        w = q = ttitle if artist == "Various Artists" else q
        query = w#generate_search_qs(w, 0)
        util.dbg(query)

        # perform fetch
        wdata = pafy.search_videos(q, int(config.PAGES.get))  # pafy.call_gdata('search', query)
        results = get_tracks_from_json(wdata)

        if not results:
            util.xprint(c.r + "Nothing matched :(\n" + c.w)
            continue

        s, score = _best_song_match(
            results, artist + " " + ttitle, length, .5, .5)
        cc = c.g if score > 85 else c.y
        cc = c.r if score < 75 else cc
        util.xprint("Matched:  %s%s%s - %s \n[%sMatch confidence: "
                    "%s%s]\n" % (c.y, s.title, c.w, util.fmt_time(s.length),
                                 cc, score, c.w))
        yield s


def _get_mb_tracks(albumid):
    """ Get track listing from MusicBraiz by album id. """
    ns = {'mb': 'http://musicbrainz.org/ns/mmd-2.0#'}
    url = "http://musicbrainz.org/ws/2/release/" + albumid
    query = {"inc": "recordings"}
    wdata = _do_query(url, query, err='album search error')

    if not wdata:
        return None

    root = ET.fromstring(wdata)
    tlist = root.find("./mb:release/mb:medium-list/mb:medium/mb:track-list",
                      namespaces=ns)
    mb_songs = tlist.findall("mb:track", namespaces=ns)
    tracks = []
    path = "./mb:recording/mb:"

    for track in mb_songs:

        try:
            title, length, rawlength = "unknown", 0, 0
            title = track.find(path + "title", namespaces=ns).text
            rawlength = track.find(path + "length", namespaces=ns).text
            length = int(round(float(rawlength) / 1000))

        except (ValueError, AttributeError):
            util.xprint("not found")

        tracks.append(dict(title=title, length=length, rawlength=rawlength))

    return tracks


def _get_mb_album(albumname, **kwa):
    """ Return artist, album title and track count from MusicBrainz. """
    url = "http://musicbrainz.org/ws/2/release/"
    qargs = dict(
        release='"%s"' % albumname,
        primarytype=kwa.get("primarytype", "album"),
        status=kwa.get("status", "official"))
    qargs.update({k: '"%s"' % v for k, v in kwa.items()})
    qargs = ["%s:%s" % item for item in qargs.items()]
    qargs = {"query": " AND ".join(qargs)}
    g.message = "Album search for '%s%s%s'" % (c.y, albumname, c.w)
    wdata = _do_query(url, qargs)

    if not wdata:
        return None

    ns = {'mb': 'http://musicbrainz.org/ns/mmd-2.0#'}
    root = ET.fromstring(wdata)
    rlist = root.find("mb:release-list", namespaces=ns)

    if int(rlist.get('count')) == 0:
        return None

    album = rlist.find("mb:release", namespaces=ns)
    artist = album.find("./mb:artist-credit/mb:name-credit/mb:artist",
                        namespaces=ns).find("mb:name", namespaces=ns).text
    title = album.find("mb:title", namespaces=ns).text
    aid = album.get('id')
    return dict(artist=artist, title=title, aid=aid)


@command(r'album\s*(.{0,500})', 'album')
def search_album(term):
    """Search for albums. """
    # pylint: disable=R0914,R0912
    if not term:
        show_message("Enter album name:", c.g, update=True)
        term = input("> ")

        if not term or len(term) < 2:
            g.message = c.r + "Not enough input!" + c.w
            g.content = content_py.generate_songlist_display()
            return

    album = _get_mb_album(term)

    if not album:
        show_message("Album '%s' not found!" % term)
        return

    prompt = "Artist? [%s] > " % album['artist']
    util.xprint(prompt, end="")
    artistentry = input().strip()

    if artistentry:

        if artistentry == "q":
            show_message("Album search abandoned!")
            return

        album = _get_mb_album(term, artist=artistentry)

        if not album:
            show_message("Album '%s' by '%s' not found!" % (term, artistentry))
            return

    title, artist = album['title'], album['artist']
    mb_tracks = _get_mb_tracks(album['aid'])

    if not mb_tracks:
        show_message("Album '%s' by '%s' has 0 tracks!" % (title, artist))
        return

    msg = "%s%s%s by %s%s%s\n\n" % (c.g, title, c.w, c.g, artist, c.w)
    msg += "Enter to begin matching or [q] to abort"
    g.message = msg
    g.content = "Tracks:\n"
    for n, track in enumerate(mb_tracks, 1):
        g.content += "%02s  %s" % (n, track['title'])
        g.content += "\n"

    screen.update()
    entry = input("Continue? [Enter] > ")

    if entry == "":
        pass

    else:
        show_message("Album search abandoned!")
        return

    songs = []
    screen.clear()
    itt = _match_tracks(artist, title, mb_tracks)

    stash = config.SEARCH_MUSIC.get, config.ORDER.get
    config.SEARCH_MUSIC.value = True
    config.ORDER.value = "relevance"

    try:
        songs.extend(itt)

    except KeyboardInterrupt:
        util.xprint("%sHalted!%s" % (c.r, c.w))

    finally:
        config.SEARCH_MUSIC.value, config.ORDER.value = stash

    if songs:
        util.xprint("\n%s / %s songs matched" % (len(songs), len(mb_tracks)))
        input("Press Enter to continue")
        if g.lastfm_network:
            g.artist = artist
            g.album = title
            g.scrobble = True
            # Fill up queue with all the track names
            g.scrobble_queue = [t['title'] for t in mb_tracks]

    msg = "Contents of album %s%s - %s%s %s(%d/%d)%s:" % (
        c.y, artist, title, c.w, c.b, len(songs), len(mb_tracks), c.w)
    failmsg = "Found no album tracks for %s%s%s" % (c.y, title, c.w)

    paginatesongs(songs, msg=msg, failmsg=failmsg)


================================================
FILE: mps_youtube/commands/config.py
================================================
from .. import g, c, config, util
from . import command


@command(r'set|showconfig', 'set', 'showconfig')
def showconfig():
    """ Dump config data. """
    width = util.getxy().width
    longest_key = 17
    longest_val = 0
    has_temps = False

    for setting in config:
        val = config[setting]
        longest_val = max(longest_val, len(str(val.display)))
        has_temps = has_temps or val.temp_value is not None

    width -= 27
    s = "  %s%-{0}s%s : %-{1}s".format(longest_key, longest_val+1)

    if has_temps:
        width -= longest_val + 5
        out = "  %s%-{}s   %-{}s %s%s%s\n".format(longest_key, longest_val) % (
            c.ul, "Key", "Value", "Temporary", " " * width, c.w)
    else:
        out = "  %s%-{}s   %s%s%s\n".format(longest_key) % (c.ul, "Key", "Value", " " * width, c.w)

    for setting in config:
        val = config[setting]

        # don't show player specific settings if unknown player
        if not util.is_known_player(config.PLAYER.get) and \
                val.require_known_player:
            continue

        # don't show max_results if auto determined
        if g.detectable_size and setting == "MAX_RESULTS":
            continue

        if g.detectable_size and setting == "CONSOLE_WIDTH":
            continue

        out += s % (c.g, setting.lower(), c.w, val.display)

        if has_temps:
            out += "%s%s" % (c.w, val.display_temp)

        out += "\n"

    g.content = out
    g.message = "Enter %sset <key> <value>%s to change\n" % (c.g, c.w)
    g.message += "Enter %sset all default%s to reset all" % (c.g, c.w)


@command(r'set\s+-t\s*([-\w]+)\s*(.*)')
def setconfigtemp(key, val):
    setconfig(key, val, is_temp=True)


@command(r'set\s+([-\w]+)\s*(.*)')
def setconfig(key, val, is_temp=False):
    """ Set configuration variable. """
    key = key.replace("-", "_")
    if key.upper() == "ALL" and val.upper() == "DEFAULT":

        for ci in config:
            config[ci].value = config[ci].default

        config.save()
        message = "Default configuration reinstated"

    elif not key.upper() in config:
        message = "Unknown config item: %s%s%s" % (c.r, key, c.w)

    elif val.upper() == "DEFAULT":
        att = config[key.upper()]
        att.value = att.default
        att.temp_value = None
        message = "%s%s%s set to %s%s%s (default)"
        dispval = att.display or "None"
        message = message % (c.y, key, c.w, c.y, dispval, c.w)
        config.save()

    else:
        # config.save() will be called by config.set() method
        message = config[key.upper()].set(val, is_temp=is_temp)

    showconfig()
    g.message = message


@command(r'encoders?', 'encoder')
def show_encs():
    """ Display available encoding presets. """
    out = "%sEncoding profiles:%s\n\n" % (c.ul, c.w)

    for x, e in enumerate(g.encoders):
        sel = " (%sselected%s)" % (c.y, c.w) if config.ENCODER.get == x else ""
        out += "%2d. %s%s\n" % (x, e['name'], sel)

    g.content = out
    message = "Enter %sset encoder <num>%s to select an encoder"
    g.message = message % (c.g, c.w)


================================================
FILE: mps_youtube/commands/download.py
================================================
import os
import re
import sys
import time
import shlex
import random
import subprocess
from urllib.request import urlopen
from urllib.error import HTTPError

from .. import g, c, screen, streams, content, config, util, pafy
from . import command, PL
from .search import yt_url, user_pls
from .songlist import dump, plist


@command(r'(dv|da|d|dl|download)\s*(\d{1,4})', 'da', 'dv', 'd', 'dl', 'download')
def download(dltype, num):
    """ Download a track or playlist by menu item number. """
    # This function needs refactoring!
    # pylint: disable=R0912
    # pylint: disable=R0914
    if g.browse_mode == "ytpl" and dltype in ("da", "dv"):
        plid = g.ytpls[int(num) - 1]["link"]
        down_plist(dltype, plid)
        return

    elif g.browse_mode == "ytpl":
        g.message = "Use da or dv to specify audio / video playlist download"
        g.message = c.y + g.message + c.w
        g.content = content.generate_songlist_display()
        return

    elif g.browse_mode != "normal":
        g.message = "Download must refer to a specific video item"
        g.message = c.y + g.message + c.w
        g.content = content.generate_songlist_display()
        return

    screen.writestatus("Fetching video info...")
    song = (g.model[int(num) - 1])

    # best = dltype.startswith("dv") or dltype.startswith("da")
    #
    # if not best:
    #
    #     try:
    #         # user prompt for download stream
    #         url, ext, url_au, ext_au = prompt_dl(song)
    #
    #     except KeyboardInterrupt:
    #         g.message = c.r + "Download aborted!" + c.w
    #         g.content = content.generate_songlist_display()
    #         return
    #
    #     if not url or ext_au == "abort":
    #         # abort on invalid stream selection
    #         g.content = content.generate_songlist_display()
    #         g.message = "%sNo download selected / invalid input%s" % (c.y, c.w)
    #         return
    #
    #     else:
    #         # download user selected stream(s)
    #         filename = _make_fname(song, ext)
    #         args = (song, filename, url)
    #
    #         if url_au and ext_au:
    #             # downloading video and audio stream for muxing
    #             audio = False
    #             filename_au = _make_fname(song, ext_au)
    #             args_au = (song, filename_au, url_au)
    #
    #         else:
    #             audio = ext in ("m4a", "ogg")
    #
    #         kwargs = dict(audio=audio)
    #
    # elif best:
    #     # set updownload without prompt
    #     url_au = None
    #     av = "audio" if dltype.startswith("da") else "video"
    #     audio = av == "audio"
    #     filename = _make_fname(song, None, av=av)
    #     args = (song, filename)
    #     kwargs = dict(url=None, audio=audio)

    try:
        # perform download(s)
        # dl_filenames = [args[1]]
        # f = _download(*args, **kwargs)
        success = pafy.download_video(song.ytid, config.DDIR.get, True if dltype.startswith("da") else False)
        if success:
            g.message = "Saved \'" + song.title + "\' to " + c.g + config.DDIR.get + c.w

        # if url_au:
        #     dl_filenames += [args_au[1]]
        #     _download(*args_au, allow_transcode=False, **kwargs)

    except KeyboardInterrupt:
        g.message = c.r + "Download halted!" + c.w

        # try:
        #     for downloaded in dl_filenames:
        #         os.remove(downloaded)
        #
        # except IOError:
        #     pass

    # if url_au:
    #     # multiplex
    #     name, ext = os.path.splitext(args[1])
    #     tmpvideoname = name + '.' +str(random.randint(10000, 99999)) + ext
    #     os.rename(args[1], tmpvideoname)
    #     mux_cmd = [g.muxapp, "-i", tmpvideoname, "-i", args_au[1], "-c",
    #                "copy", name + ".mp4"]
    #
    #     try:
    #         subprocess.call(mux_cmd)
    #         g.message = "Saved to :" + c.g + mux_cmd[7] + c.w
    #         os.remove(tmpvideoname)
    #         os.remove(args_au[1])
    #
    #     except KeyboardInterrupt:
    #         g.message = "Audio/Video multiplex aborted!"

    g.content = content.generate_songlist_display()


@command(r'(da|dv)\s+((?:\d+\s\d+|-\d+|\d+-|\d+,)(?:[\d\s,-]*))', 'da', 'dv')
def down_many(dltype, choice, subdir=None):
    """ Download multiple items. """
    choice = util.parse_multi(choice)
    choice = list(set(choice))
    downsongs = [g.model[int(x) - 1] for x in choice]
    temp = g.model[::]
    g.model.songs = downsongs[::]
    count = len(downsongs)
    av = "audio" if dltype.startswith("da") else "video"
    msg = ""

    def handle_error(message):
        """ Handle error in download. """
        g.message = message
        g.content = disp
        screen.update()
        time.sleep(2)
        g.model.songs.pop(0)

    try:
        for song in downsongs:
            g.result_count = len(g.model)
            disp = content.generate_songlist_display()
            title = "Download Queue (%s):%s\n\n" % (av, c.w)
            disp = re.sub(r"(Num\s*?Title.*?\n)", title, disp)
            g.content = disp
            screen.update()

            try:
                filename = _make_fname(song, None, av=av, subdir=subdir)

            except IOError as e:
                handle_error("Error for %s: %s" % (song.title, str(e)))
                count -= 1
                continue

            except KeyError:
                handle_error("No audio track for %s" % song.title)
                count -= 1
                continue

            try:
                _download(song, filename, url=None, audio=av == "audio")

            except HTTPError:
                handle_error("HTTP Error for %s" % song.title)
                count -= 1
                continue

            g.model.songs.pop(0)
            msg = "Downloaded %s items" % count
            g.message = "Saved to " + c.g + song.title + c.w

    except KeyboardInterrupt:
        msg = "Downloads interrupted!"

    finally:
        g.model.songs = temp[::]
        g.message = msg
        g.result_count = len(g.model)
        g.content = content.generate_songlist_display()


@command(r'(da|dv)pl\s+%s' % PL, 'dapl', 'dvpl')
def down_plist(dltype, parturl):
    """ Download YouTube playlist. """

    plist(parturl)
    dump(False)
    title = g.pafy_pls[parturl][0].title
    # Remove double quotes for convenience
    subdir = util.sanitize_filename(title.replace('"', ''))
    down_many(dltype, "1-", subdir=subdir)
    msg = g.message
    plist(parturl)
    g.message = msg


@command(r'(da|dv)upl\s+(.*)', 'daupl', 'dvupl')
def down_user_pls(dltype, user):
    """ Download all user playlists. """
    user_pls(user)
    for i in g.ytpls:
        down_plist(dltype, i.get('link'))

    return


def _make_fname(song, ext=None, av=None, subdir=None):
    """" Create download directory, generate filename. """
    # pylint: disable=E1103
    # Instance of 'bool' has no 'extension' member (some types not inferable)
    ddir = os.path.join(config.DDIR.get, subdir) if subdir else config.DDIR.get
    if not os.path.exists(ddir):
        os.makedirs(ddir)

    if not ext:
        stream = streams.select(streams.get(song),
                audio=av == "audio", m4a_ok=True)
        ext = stream['ext']

    # filename = song.title[:59] + "." + ext
    filename = song.title + "." + ext
    # Remove double quotes for convenience
    filename = filename.replace('"', '')
    filename = os.path.join(ddir, util.sanitize_filename(filename))
    return filename


def extract_metadata(name):
    """ Try to determine metadata from video title. """
    seps = name.count(" - ")
    artist = title = None

    if seps == 1:

        pos = name.find(" - ")
        artist = name[:pos].strip()
        title = name[pos + 3:].strip()

    else:
        title = name.strip()

    return dict(artist=artist, title=title)


def remux_audio(filename, title):
    """ Remux audio file. Insert limited metadata tags. """
    util.dbg("starting remux")
    temp_file = filename + "." + str(random.randint(10000, 99999))
    os.rename(filename, temp_file)
    meta = extract_metadata(title)
    metadata = ["title=%s" % meta["title"]]

    if meta["artist"]:
        metadata = ["title=%s" % meta["title"], "-metadata",
                    "artist=%s" % meta["artist"]]

    cmd = [g.muxapp, "-y", "-i", temp_file, "-acodec", "copy", "-metadata"]
    cmd += metadata + ["-vn", filename]
    util.dbg(cmd)

    try:
        with open(os.devnull, "w") as devnull:
            subprocess.call(cmd, stdout=devnull, stderr=subprocess.STDOUT)

    except OSError:
        util.dbg("Failed to remux audio using %s", g.muxapp)
        os.rename(temp_file, filename)

    else:
        os.unlink(temp_file)
        util.dbg("remuxed audio file using %s" % g.muxapp)


def transcode(filename, enc_data):
    """ Re encode a download. """
    base = os.path.splitext(filename)[0]
    exe = g.muxapp if g.transcoder_path == "auto" else g.transcoder_path

    # ensure valid executable
    if not exe or not os.path.exists(exe) or not os.access(exe, os.X_OK):
        util.xprint("Encoding failed. Couldn't find a valid encoder :(\n")
        time.sleep(2)
        return filename

    command = shlex.split(enc_data['command'])
    newcom, outfn = command[::], ""

    for n, d in enumerate(command):

        if d == "ENCODER_PATH":
            newcom[n] = exe

        elif d == "IN":
            newcom[n] = filename

        elif d == "OUT":
            newcom[n] = outfn = base

        elif d == "OUT.EXT":
            newcom[n] = outfn = base + "." + enc_data['ext']

    returncode = subprocess.call(newcom)

    if returncode == 0 and g.delete_orig:
        os.unlink(filename)

    return outfn


def external_download(song, filename, url):
    """ Perform download using external application. """
    cmd = config.DOWNLOAD_COMMAND.get
    ddir, basename = config.DDIR.get, os.path.basename(filename)
    cmd_list = shlex.split(cmd)

    def list_string_sub(orig, repl, lst):
        """ Replace substrings for items in a list. """
        return [x if orig not in x else x.replace(orig, repl) for x in lst]

    cmd_list = list_string_sub("%F", filename, cmd_list)
    cmd_list = list_string_sub("%d", ddir, cmd_list)
    cmd_list = list_string_sub("%f", basename, cmd_list)
    cmd_list = list_string_sub("%u", url, cmd_list)
    cmd_list = list_string_sub("%i", song.ytid, cmd_list)
    util.dbg("Downloading using: %s", " ".join(cmd_list))
    subprocess.call(cmd_list)


def _download(song, filename, url=None, audio=False, allow_transcode=True):
    """ Download file, show status.

    Return filename or None in case of user specified download command.

    """
    # pylint: disable=R0914
    # too many local variables
    # Instance of 'bool' has no 'url' member (some types not inferable)

    if not url:
        stream = streams.select(streams.get(song), audio=audio, m4a_ok=True)
        url = stream['url']

    # if an external download command is set, use it
    if config.DOWNLOAD_COMMAND.get:
        title = c.y + os.path.splitext(os.path.basename(filename))[0] + c.w
        util.xprint("Downloading %s using custom command" % title)
        external_download(song, filename, url)
        return None

    if not config.OVERWRITE.get:
        if os.path.exists(filename):
            util.xprint("File exists. Skipping %s%s%s ..\n" %
                    (c.r, filename, c.w))
            time.sleep(0.2)
            return filename

    util.xprint("Downloading to %s%s%s .." % (c.r, filename, c.w))
    status_string = ('  {0}{1:,}{2} Bytes [{0}{3:.2%}{2}] received. Rate: '
                     '[{0}{4:4.0f} kbps{2}].  ETA: [{0}{5:.0f} secs{2}]')

    resp = urlopen(url)
    total = int(resp.info()['Content-Length'].strip())
    chunksize, bytesdone, t0 = 16384, 0, time.time()
    outfh = open(filename, 'wb')

    while True:
        chunk = resp.read(chunksize)
        outfh.write(chunk)
        elapsed = time.time() - t0
        bytesdone += len(chunk)
        rate = 0
        if elapsed != 0:
            rate = (bytesdone / 1024) / elapsed
        if rate:
            eta = (total - bytesdone) / (rate * 1024)
        else:
            eta = 0
        stats = (c.y, bytesdone, c.w, bytesdone * 1.0 / total, rate, eta)

        if not chunk:
            outfh.close()
            break

        status = status_string.format(*stats)
        sys.stdout.write("\r" + status + ' ' * 4 + "\r")
        sys.stdout.flush()

    active_encoder = g.encoders[config.ENCODER.get]
    ext = filename.split(".")[-1]
    valid_ext = ext in active_encoder['valid'].split(",")

    if audio and g.muxapp:
        remux_audio(filename, song.title)

    if config.ENCODER.get != 0 and valid_ext and allow_transcode:
        filename = transcode(filename, active_encoder)

    return filename


def menu_prompt(model, prompt=" > ", rows=None, header=None, theading=None,
                footer=None, force=0):
    """ Generate a list of choice, returns item from model. """
    content = ""

    for x in header, theading, rows, footer:
        if isinstance(x, list):

            for line in x:
                content += line + "\n"

        elif isinstance(x, str):
            content += x + "\n"

    g.content = content
    screen.update()

    choice = input(prompt)

    if choice in model:
        return model[choice]

    elif force:
        return menu_prompt(model, prompt, rows, header, theading, footer,
                           force)

    elif not choice.strip():
        return False, False

    else:  # unrecognised input
        return False, "abort"


def prompt_dl(song):
    """ Prompt user do choose a stream to dl.  Return (url, extension). """
    # pylint: disable=R0914
    dl_data, p = get_dl_data(song)
    dl_text = gen_dl_text(dl_data, song, p)

    model = [x['url'] for x in dl_data]
    ed = enumerate(dl_data)
    model = {str(n + 1): (x['url'], x['ext']) for n, x in ed}
    url, ext = menu_prompt(model, "Download number: ", *dl_text)
    url2 = ext2 = None
    mediatype = [i for i in dl_data if i['url'] == url][0]['mediatype']

    if mediatype == "video" and g.muxapp and not config.DOWNLOAD_COMMAND.get:
        # offer mux if not using external downloader
        dl_data, p = get_dl_data(song, mediatype="audio")
        dl_text = gen_dl_text(dl_data, song, p)
        au_choices = "1" if len(dl_data) == 1 else "1-%s" % len(dl_data)
        footer = [util.F('-audio') % ext, util.F('select mux') % au_choices]
        dl_text = tuple(dl_text[0:3]) + (footer,)
        aext = ("ogg", "m4a")
        model = [x['url'] for x in dl_data if x['ext'] in aext]
        ed = enumerate(dl_data)
        model = {str(n + 1): (x['url'], x['ext']) for n, x in ed}
        prompt = "Audio stream: "
        url2, ext2 = menu_prompt(model, prompt, *dl_text)

    return url, ext, url2, ext2


def gen_dl_text(ddata, song, p):
    """ Generate text for dl screen. """
    hdr = []
    hdr.append("  %s%s%s" % (c.r, song.title, c.w))
    author = p.author
    hdr.append(c.r + "  Uploaded by " + author + c.w)
    hdr.append("  [" + util.fmt_time(song.length) + "]")
    hdr.append("")

    heading = tuple("Item Format Quality Media Size Notes".split())
    fmt = "  {0}%-6s %-8s %-13s %-7s   %-5s   %-16s{1}"
    heading = [fmt.format(c.w, c.w) % heading]
    heading.append("")

    content = []

    for n, d in enumerate(ddata):
        row = (n + 1, d['ext'], d['quality'], d['mediatype'], d['size'],
               d['notes'])
        fmt = "  {0}%-6s %-8s %-13s %-7s %5s Mb   %-16s{1}"
        row = fmt.format(c.g, c.w) % row
        content.append(row)

    content.append("")

    footer = "Select [%s1-%s%s] to download or [%sEnter%s] to return"
    footer = [footer % (c.y, len(content) - 1, c.w, c.y, c.w)]
    return(content, hdr, heading, footer)


def get_dl_data(song, mediatype="any"):
    """ Get filesize and metadata for all streams, return dict. """
    def mbsize(x):
        """ Return size in MB. """
        return str(int(x / (1024 ** 2)))

    p = util.get_pafy(song)
    dldata = []
    text = " [Fetching stream info] >"
    streamlist = [x for x in p.allstreams]

    if mediatype == "audio":
        streamlist = [x for x in p.audiostreams]

    l = len(streamlist)
    for n, stream in enumerate(streamlist):
        sys.stdout.write(text + "-" * n + ">" + " " * (l - n - 1) + "<\r")
        sys.stdout.flush()

        try:
            size = mbsize(stream.get_filesize())

        except TypeError:
            util.dbg(c.r + "---Error getting stream size" + c.w)
            size = 0

        item = {'mediatype': stream.mediatype,
                'size': size,
                'ext': stream.extension,
                'quality': stream.quality,
                'notes': stream.notes,
                'url': stream.url}

        dldata.append(item)

    screen.writestatus("")
    return dldata, p


@command(r'dlurl\s(.*[-_a-zA-Z0-9]{11}.*)', 'dlurl')
def dl_url(url):
    """ Open and prompt for download of youtube video url. """
    g.browse_mode = "normal"
    yt_url(url)

    if len(g.model) == 1:
        download("download", "1")

    if g.command_line:
        sys.exit()


@command(r'daurl\s(.*[-_a-zA-Z0-9]{11}.*)', 'daurl')
def da_url(url):
    """ Open and prompt for download of youtube best audio from url. """
    g.browse_mode = "normal"
    yt_url(url)

    if len(g.model) == 1:
        download("da", "1")

    if g.command_line:
        sys.exit()


================================================
FILE: mps_youtube/commands/generate_playlist.py
================================================
"""
    Playlist Generation
"""
from os import path
from random import choice
import string

from .. import content, g, playlists, screen, util, listview
from ..playlist import Playlist
from . import command, search, album_search


@command(r'mkp\s*(.{1,100})', 'mkp')
def generate_playlist(sourcefile):
    """Generate a playlist from video titles in sourcefile"""

    # Hooks into this, check if the argument --description is present
    if "--description" in sourcefile or "-d" in sourcefile:
        description_generator(sourcefile)
        return

    expanded_sourcefile = path.expanduser(sourcefile)
    if not check_sourcefile(expanded_sourcefile):
        g.message = util.F('mkp empty') % expanded_sourcefile
    else:
        queries = read_sourcefile(expanded_sourcefile)
        g.message = util.F('mkp parsed') % (len(queries), sourcefile)
        if queries:
            create_playlist(queries)
            g.message = util.F('pl help')
            g.content = content.playlists_display()


def read_sourcefile(filename):
    """Read each line as a query from filename"""
    with open(filename) as srcfl:
        queries = list()
        for item in srcfl.readlines():
            clean_item = str(item).strip()
            if not clean_item:
                continue
            queries.append(clean_item)
        return queries


def check_sourcefile(filename):
    """Check if filename exists and has a non-zero size"""
    return path.isfile(filename) and path.getsize(filename) > 0


def create_playlist(queries, title=''):
    """Add a new playlist

    Create playlist with a random name, get the first
    match for each title in queries and append it to the playlist
    """
    plname = title.replace(" ", "-") or random_plname()
    if not g.userpl.get(plname):
        g.userpl[plname] = Playlist(plname)
    for query in queries:
        g.message = util.F('mkp finding') % query
        screen.update()
        qresult = find_best_match(query)
        if qresult:
            g.userpl[plname].songs.append(qresult)
    if g.userpl[plname]:
        playlists.save()


def find_best_match(query):
    """Find the best(first)"""
    # This assumes that the first match is the best one
    qs = search.generate_search_qs(query)
    wdata = pafy.call_gdata('search', qs)
    results = search.get_tracks_from_json(wdata)
    if results:
        res, score = album_search._best_song_match(
            results, query, 0.1, 1.0, 0.0)
        return res


def random_plname():
    """Generates a random alphanumeric string of 6 characters"""
    n_chars = 6
    return ''.join(choice(string.ascii_lowercase + string.digits)
                   for _ in range(n_chars))


def description_generator(text):
    """ Fetches a videos description and parses it for
        <artist> - <track> combinations
    """
    if not isinstance(g.model, Playlist):
        g.message = util.F("mkp desc unknown")
        return

    # Use only the first result, for now
    num = text.replace("--description", "")
    num = num.replace("-d", "")
    num = util.number_string_to_list(num)[0]

    query = {}
    query['id'] = g.model[num].ytid
    query['part'] = 'snippet'
    query['maxResults'] = '1'
    data = pafy.call_gdata('videos', query)['items'][0]['snippet']
    title = "mkp %s" % data['title']
    data = util.fetch_songs(data['description'], data['title'])

    columns = [
        {"name": "idx", "size": 3, "heading": "Num"},
        {"name": "artist", "size": 30, "heading": "Artist"},
        {"name": "title", "size": "remaining", "heading": "Title"},
    ]

    def run_m(idx):
        """ Create playlist based on the
            results selected
        """
        create_playlist(idx, title)

    if data:
        data = [listview.ListSongtitle(x) for x in data]
        g.content = listview.ListView(columns, data, run_m)
        g.message = util.F("mkp desc which data")
    else:
        g.message = util.F("mkp no valid")

    return


================================================
FILE: mps_youtube/commands/lastfm.py
================================================
import time
import datetime

try:
    import pylast
    has_pylast = True
except ImportError:
    has_pylast = False

from .. import g, util, config
from . import command

@command(r'lastfm_connect', 'lastfm_connect')
def init_network(verbose=True):
    """ Initialize the global pylast network variable """
    if not has_pylast :
        if verbose:
            pylast_url = 'https://github.com/pylast/pylast'
            g.message = '"pylast" module not found\n see %s' % (pylast_url)
        return

    # TODO: Add option to read lastfm config from file or env variable
    key = config.LASTFM_API_KEY.get
    secret = config.LASTFM_API_SECRET.get
    password = config.LASTFM_PASSWORD.get # already hashed
    username = config.LASTFM_USERNAME.get

    if not (key and secret and password and username):
        if verbose:
            util.xprint("Not all Last.fm credentials were set.")
        return

    try:
        g.lastfm_network = pylast.LastFMNetwork(api_key=key, api_secret=secret,
                                                username=username,
                                                password_hash=password)
        if verbose:
            g.message = "Last.fm authentication successful!"
    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError) as e:
        if verbose:
            g.message = "Last.fm connection error: %s" % (str(e))

def scrobble_track(artist, album, track):
    """ Scrobble a track to the user's Last.fm account """
    if not g.lastfm_network:
        return
    unix_timestamp = int(time.mktime(datetime.datetime.now().timetuple()))
    try:
        g.lastfm_network.scrobble(artist=artist, title=track, album=album,
                                  timestamp=unix_timestamp)
    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError):
        return

def set_now_playing(artist, track):
    """ Set the current track as "now playing" on the user's Last.fm account """
    if not g.lastfm_network:
        return
    try:
        g.lastfm_network.update_now_playing(artist=artist, title=track)
    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError):
        return


================================================
FILE: mps_youtube/commands/local_playlist.py
================================================
import re

from .. import g, c, playlists, content, util
from ..playlist import Playlist, Video
from . import command, WORD
from .songlist import paginatesongs, songlist_rm_add
from ..util import parse_video_length


@command(r'rmp\s*(\d+|%s)' % WORD, 'rmp')
def playlist_remove(name):
    """ Delete a saved playlist by name - or purge working playlist if *all."""
    if name.isdigit() or g.userpl.get(name):

        if name.isdigit():
            name = int(name) - 1
            name = sorted(g.userpl)[name]

        playlists.delete(name)
        g.message = "Deleted playlist %s%s%s" % (c.y, name, c.w)
        g.content = content.playlists_display()
        #playlists.save()

    else:
        g.message = util.F('pl not found advise ls') % name
        g.content = content.playlists_display()


@command(r'add\s*(-?\d[-,\d\s]{1,250})(%s)' % WORD, 'add')
def playlist_add(nums, playlist):
    """ Add selected song nums to saved playlist. """
    nums = util.parse_multi(nums)
    # Replacing spaces with hyphens before checking if playlist already exist.
    # See https://github.com/mps-youtube/mps-youtube/issues/1046.
    playlist = playlist.replace(" ", "-")

    if not g.userpl.get(playlist):
        g.userpl[playlist] = Playlist(playlist)

    for songnum in nums:
        g.userpl[playlist].songs.append(g.model[songnum - 1])
        dur = g.userpl[playlist].duration
        f = (len(nums), playlist, len(g.userpl[playlist]), dur)
        g.message = util.F('added to saved pl') % f

    if nums:
        playlists.save()

    g.content = content.generate_songlist_display()


@command(r'mv\s*(\d{1,3})\s*(%s)' % WORD, 'mv')
def playlist_rename_idx(_id, name):
    """ Rename a playlist by ID. """
    _id = int(_id) - 1
    playlist_rename(sorted(g.userpl)[_id] + " " + name)


@command(r'mv\s*(%s\s+%s)' % (WORD, WORD), 'mv')
def playlist_rename(playlists_):
    """ Rename a playlist using mv command. """
    # Deal with old playlist names that permitted spaces
    a, b = "", playlists_.split(" ")
    while a not in g.userpl:
        a = (a + " " + (b.pop(0))).strip()
        if not b and a not in g.userpl:
            g.message = util.F('no pl match for rename')
            g.content = g.content or content.playlists_display()
            return

    b = "-".join(b)
    g.userpl[b] = Playlist(b)
    g.userpl[b].songs = list(g.userpl[a].songs)
    playlist_remove(a)
    g.message = util.F('pl renamed') % (a, b)
    playlists.save()


@command(r'(rm|add)\s(?:\*|all)', 'rm', 'add')
def add_rm_all(action):
    """ Add all displayed songs to current playlist.

    remove all displayed songs from view.

    """
    if action == "rm":
        g.model.songs.clear()
        msg = c.b + "Cleared all songs" + c.w
        g.content = content.generate_songlist_display(zeromsg=msg)

    elif action == "add":
        size = len(g.model)
        songlist_rm_add("add", "-" + str(size))


@command(r'save', 'save')
def save_last():
    """ Save command with no playlist name. """
    if g.last_opened:
        open_save_view("save", g.last_opened)

    else:
        saveas = ""

        # save using artist name in postion 1
        if g.model:
            if g.selected_pafy_pls_id: # if a playlist was selected
                saveas = g.pafy_pls[g.selected_pafy_pls_id][0].info['info']['title']
            else: # user didn't selected a playlist
                saveas = g.model[0].title[:18].strip()
            saveas = re.sub(r"[^-\w]", "-", saveas, flags=re.UNICODE)

        # loop to find next available name
        post = 0

        while g.userpl.get(saveas):
            post += 1
            saveas = g.model[0].title[:18].strip() + "-" + str(post)

        # Playlists are not allowed to start with a digit
        # TODO: Possibly change this, but ban purely numerical names
        saveas = saveas.lstrip("0123456789")

        open_save_view("save", saveas)


@command(r'(open|save|view)\s*(%s)' % WORD, 'open', 'save', 'view')
def open_save_view(action, name):
    """ Open, save or view a playlist by name.  Get closest name match. """
    name = name.replace(" ", "-")
    if action == "open" or action == "view":
        saved = g.userpl.get(name)

        if not saved:
            name = util.get_near_name(name, g.userpl)
            saved = g.userpl.get(name)

        elif action == "open":
            g.active.songs = list(saved.songs)
            g.last_opened = name
            msg = util.F("pl loaded") % name
            paginatesongs(g.active, msg=msg)

        elif action == "view":
            g.last_opened = ""
            msg = util.F("pl viewed") % name
            paginatesongs(list(saved.songs), msg=msg)

        elif not saved and action in "view open".split():
            g.message = util.F("pl not found") % name
            g.content = content.playlists_display()

    elif action == "save":
        if not g.model:
            g.message = "Nothing to save. " + util.F('advise search')
            g.content = content.generate_songlist_display()

        else:
            if g.selected_pafy_pls_id: # if a playlist was selected by user:
                g.userpl[name] = Playlist(name, [Video(i['id'], i['title'], parse_video_length(i['duration'])) for i in g.pafy_pls[g.selected_pafy_pls_id][0].videos])
            else: # user created custom playlist and never opened it and now wants to save it
                g.userpl[name] = Playlist(name, list(g.model.songs))
            g.message = util.F('pl saved') % name
            playlists.save()
            g.content = content.generate_songlist_display()


@command(r'(open|view)\s*(\d{1,4})', 'open', 'view')
def open_view_bynum(action, num):
    """ Open or view a saved playlist by number. """
    srt = sorted(g.userpl)
    name = srt[int(num) - 1]
    open_save_view(action, name)


@command(r'ls', 'ls')
def ls():
    """ List user saved playlists. """
    if not g.userpl:
        g.message = util.F('no playlists')
        g.content = g.content or \
                content.generate_songlist_display(zeromsg=g.message)

    else:
        g.content = content.playlists_display()
        g.message = util.F('pl help')


@command(r'vp', 'vp')
def vp():
    """ View current working playlist. """

    msg = util.F('current pl')
    txt = util.F('advise add') if g.model else util.F('advise search')
    failmsg = util.F('pl empty') + " " + txt

    paginatesongs(g.active, msg=msg, failmsg=failmsg)


================================================
FILE: mps_youtube/commands/misc.py
================================================
import re
from datetime import datetime, timedelta
import socket
import traceback
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from .. import player

try:
    # pylint: disable=F0401
    import pyperclip
    has_pyperclip = True

except ImportError:
    has_pyperclip = False

try:
    import readline
    has_readline = True
except ImportError:
    has_readline = False

from .. import g, c, __version__, content, screen, cache, pafy
from .. import streams, history, config, util
from ..helptext import get_help
from ..content import generate_songlist_display, logo, qrcode_display
from . import command
from .songlist import paginatesongs


@command(r'clearcache')
def clearcache():
    """ Clear cached items - for debugging use. """
    g.pafs = {}
    g.streams = {}
    util.dbg("%scache cleared%s", c.p, c.w)
    g.message = "cache cleared"


@command(r'(?:help|h)(?:\s+([-_a-zA-Z]+))?', 'help')
def show_help(choice):
    """ Print help message. """

    g.content = get_help(choice)


@command(r'(?:q|quit|exit)', 'quit', 'exit')
def quits(showlogo=True):
    """ Exit the program. """
    if has_readline and config.INPUT_HISTORY.get:
        readline.write_history_file(g.READLINE_FILE)
        util.dbg("Saved history file")

    cache.save()

    screen.clear()
    msg = logo(c.r, version=__version__) if showlogo else ""
    msg += util.F("exitmsg", 2)

    if config.CHECKUPDATE.get and showlogo:

        try:
            url = "https://raw.githubusercontent.com/iamtalhaasghar/yewtube/master/setup.py"
            v = urlopen(url, timeout=1).read().decode()
            v = re.search(r'__version__\s*=\s*"\s*([\d\.]+)\s*"\s*', v, re.MULTILINE)

            if v:
                v = v.group(1)

                if v > __version__:
                    msg += "\n\nA newer version is available (%s). Use `help new` command to check what's changed.\n" % v

        except (URLError, HTTPError, socket.timeout):
            util.dbg("check update timed out")

    screen.msgexit(msg)

def _format_comment(n, qnt, author_name, published_date, content, reply=False):
    # poster = snippet.get('authorDisplayName')
    # shortdate = util.yt_datetime(snippet.get('publishedAt', ''))[1]
    # text = snippet.get('textDisplay', '')
    cid = ("%s%s/%s %s" % ('└── ' if reply else '', n, qnt, c.c("g", author_name)))
    return ("%-39s %s\n" % (cid, published_date)) + \
            c.c("y", content.strip()) + '\n\n'

def _fetch_commentreplies(parentid):
    # return pafy.call_gdata('comments', {
    #     'parentId': parentid,
    #     'part': 'snippet',
    #     'textFormat': 'plainText',
    #     'maxResults': 50}).get('items', [])
    return None
def fetch_comments(item):
    """ Fetch comments for item using gdata. """
    # pylint: disable=R0912
    # pylint: disable=R0914
    ytid, title = item.ytid, item.title
    util.dbg("Fetching comments for %s", c.c("y", ytid))
    screen.writestatus("Fetching comments for %s" % c.c("y", title[:55]))
    # qs = {'textFormat': 'plainText',
    #       'videoId': ytid,
    #       'maxResults': 50,
    #       'part': 'snippet'}

    # jsdata = None
    try:
        all_comments = pafy.get_comments(ytid)
    except Exception:
        raise
    # coms = [x.get('snippet', {}) for x in jsdata.get('items', [])]

    # skip blanks
    # coms = [x for x in coms
    #         if len(x.get('topLevelComment', {}).get('snippet', {}).get('textDisplay', '').strip())]

    if not len(all_comments):
        g.message = "No comments for %s" % item.title[:50]
        g.content = generate_songlist_display()
        return

    commentstext = ''

    for n, com in enumerate(all_comments, 1):
        # snippet = com.get('topLevelComment', {}).get('snippet', {})
        commentstext += _format_comment(n, len(all_comments), com['author']['name'], com['published'], com['content'])
        # todo fetch comment replies
        # if com.get('replyCount') > 0:
        #     replies = _fetch_commentreplies(com.get('topLevelComment').get('id'))
        #     for n, com in enumerate(reversed(replies), 1):
        #         commentstext += _format_comment(com.get('snippet', {}),
        #                                         n, len(replies), True)

    g.current_page = 0
    g.content = content.StringContent(commentstext)


@command(r'c\s?(\d{1,4})', 'c')
def comments(number):
    """ Receive use request to view comments. """
    if g.browse_mode == "normal":
        item = g.model[int(number) - 1]
        fetch_comments(item)

    else:
        g.content = generate_songlist_display()
        g.message = "Comments only available for video items"


@command(r'x\s*(\d+)', 'x')
def clipcopy_video(num):
    """ Copy video/playlist url to clipboard. """
    if g.browse_mode == "ytpl":

        p = g.ytpls[int(num) - 1]
        link = "https://youtube.com/playlist?list=%s" % p['link']

    elif g.browse_mode == "normal":
        item = (g.model[int(num) - 1])
        link = "https://youtube.com/watch?v=%s" % item.ytid

    else:
        g.message = "clipboard copy not valid in this mode"
        g.content = generate_songlist_display()
        return

    if has_pyperclip:

        try:
            pyperclip.copy(link)
            g.message = c.y + link + c.w + " copied"
            g.content = generate_songlist_display()

        except Exception as e:
            g.content = generate_songlist_display()
            g.message = link + "\nError - couldn't copy to clipboard.\n" + \
                    ''.join(traceback.format_exception_only(type(e), e))

    else:
        g.message = "pyperclip module must be installed for clipboard support\n"
        g.message += "see https://pypi.python.org/pypi/pyperclip/"
        g.content = generate_songlist_display()


@command(r'X\s*(\d+)', 'X')
def clipcopy_stream(num):
    """ Copy content stream url to clipboard. """
    if g.browse_mode == "normal":

        item = (g.model[int(num) - 1])
        details = player.stream_details(item)[1]
        stream = details['url']

    else:
        g.message = "clipboard copy not valid in this mode"
        g.content = generate_songlist_display()
        return

    if has_pyperclip:

        try:
            pyperclip.copy(stream)
            g.message = c.y + stream + c.w + " copied"
            g.content = generate_songlist_display()

        except Exception as e:
            g.content = generate_songlist_display()
            g.message = stream + "\nError - couldn't copy to clipboard.\n" + \
                    ''.join(traceback.format_exception_only(type(e), e))

    else:
        g.message = "pyperclip module must be installed for clipboard support\n"
        g.message += "see https://pypi.python.org/pypi/pyperclip/"
        g.content = generate_songlist_display()


@command(r'i\s*(\d{1,4})', 'i')
def video_info(num):
    """ Get video information. """
    if g.browse_mode == "ytpl":
        p = g.ytpls[int(num) - 1]

        # fetch the playlist item as it has more metadata
        if p['link'] in g.pafy_pls:
            ytpl = g.pafy_pls[p['link']][0]
        else:
            g.content = logo(col=c.g)
            g.message = "Fetching playlist info.."
            screen.update()
            util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
            ytpl = pafy.get_playlist2(p['link'])
            g.pafy_pls[p['link']] = (ytpl, util.IterSlicer(ytpl))

        ytpl_desc = ytpl.description
        g.content = generate_songlist_display()
        created = util.yt_datetime_local(p['created'])
        updated = util.yt_datetime_local(p['updated'])
        out = c.ul + "Playlist Info" + c.w + "\n\n"
        out += p['title']
        out += "\n" + ytpl_desc
        out += ("\n\nAuthor     : " + p['author'])
        out += "\nSize       : " + str(p['size']) + " videos"
        out += "\nCreated    : " + created[1] + " " + created[2]
        out += "\nUpdated    : " + updated[1] + " " + updated[2]
        out += "\nID         : " + str(p['link'])
        out += ("\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w))
        g.content = out

    elif g.browse_mode == "normal":
        g.content = logo(c.b)
        screen.update()
        screen.writestatus("Fetching video metadata..")
        item = (g.model[int(num) - 1])
        streams.get(item)
        p = pafy.get_video_info(item.ytid)
        #pub = datetime.strptime(str(p.published), "%Y-%m-%d %H:%M:%SZ")
        #pub = util.utc2local(pub)
        screen.writestatus("Fetched")
        out = c.ul + "Video Info" + c.w + "\n\n"
        out += p['title'] or ""
        out += "\n\nDescription:\n\n" + str(p.get('description', "")) + "\n"
        out += "\nKeywords: " + str(p['keywords']) + "\n"
        out += "\nIs Live Now    : " + str(p['isLiveNow'])
        out += "\nDuration       : " + str(timedelta(seconds=int(p['duration']['secondsText'])))
        out += "\nView count     : " + "{:,}".format(int(p['viewCount']['text']))
        out += "\nAuthor         : " + str(p['channel']['name'] + ' ~ ' + p['channel']['link'])
        out += "\nPublished Date : " + str(p['publishDate'])
        out += "\nUploaded Date  : " + str(p['uploadDate'])
        out += "\nRating         : " + str(p['averageRating'])
        out += "\nLikes          : " + "{:,}".format(p.get('likes', 0))
        out += "\nDislikes       : " + "{:,}".format(p.get('dislikes', 0))
        out += "\nCategory       : " + str(p['category'])
        out += "\nFamily Safe    : " + str(p['isFamilySafe'])
        out += "\nLink           : " + str(p['link'])
        if config.SHOW_QRCODE.get:
            out += "\n" + qrcode_display(
                "https://youtube.com/watch?v=%s" % p.videoid)

        out += "\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w)
        g.content = out


@command(r's\s*(\d{1,4})', 's')
def stream_info(num):
    """ Get stream information. """
    if g.browse_mode == "normal":
        g.content = logo(c.b)
        screen.update()
        screen.writestatus("Fetching stream metadata..")
        item = (g.model[int(num) - 1])
        streams.get(item)
        p = util.get_pafy(item)
        setattr(p, 'ytid', p.videoid)
        details = player.stream_details(p)[1]
        screen.writestatus("Fetched")
        out = "\n\n" + c.ul + "Stream Info" + c.w + "\n"
        out += "\nExtension   : " + details['ext']
        out += "\nSize        : " + str(details['size'])
        out += "\nQuality     : " + details['quality']
        out += "\nRaw bitrate : " + str(details['rawbitrate'])
        out += "\nMedia type  : " + details['mtype']
        out += "\nLink        : " + details['url']
        out += "\n\n%s[%sPress enter to go back%s]%s" % (c.y, c.w, c.y, c.w)
        g.content = out


@command(r'history', 'history')
def view_history(duplicates=True):
    """ Display the user's play history """
    history = g.userhist.get('history')
    #g.last_opened = ""
    try:
        hist_list = list(reversed(history.songs))
        message = "Viewing play history"
        if not duplicates:
            # List unique elements and preserve order.
            seen = set()
            seen_add = seen.add  # it makes calls to add() faster
            hist_list = [x for x in hist_list if not (x.ytid in seen or seen_add(x.ytid))]
            message = "Viewing recent played songs"
        paginatesongs(hist_list)
        g.message = message

    except AttributeError:
        g.content = logo(c.r)
        g.message = "History empty"


    if not config.HISTORY.get:
        g.message += "\t{1}History recording is currently off{0}".format(c.w,c.y)



@command(r'history recent', 'history recent')
def recent_history():
    """ Display the recent user's played songs """
    view_history(duplicates=False)


@command(r'history clear', 'history clear')
def clear_history():
    """ Clears the user's play history """
    g.userhist['history'].songs = []
    history.save()
    g.message = "History cleared"
    g.content = logo()


================================================
FILE: mps_youtube/commands/play.py
================================================
import random
import sys
import typing as T
import webbrowser
from urllib.error import HTTPError, URLError

from .. import c, config, content, g, streams, util
from . import RS, WORD, command
from .search import related, yt_url
from .songlist import plist

@command(r'play all', 'play all')
def play_loaded():
    g.model.songs = content.get_last_query()
    if g.model.songs:
        play_all("", "", "")

@command(r'play\s+(%s|\d+)' % WORD, 'play')
def play_pl(name):
    """ Play a playlist by name. """
    if name.isdigit():
        name = int(name)
        name = sorted(g.userpl)[name - 1]

    saved = g.userpl.get(name)

    if not saved:
        name = util.get_near_name(name, g.userpl)
        saved = g.userpl.get(name)

    if saved:
        g.model.songs = list(saved.songs)
        play_all("", "", "")

    else:
        g.message = util.F("pl not found") % name
        g.content = content.playlists_display()


@command(r'(%s{0,3})([-,\d\s\[\]]{1,250})\s*(%s{0,3})$' %
         (RS, RS))
def play(pre, choice, post=""):
    """ Play choice.  Use repeat/random if appears in pre/post. """
    # pylint: disable=R0914
    # too many local variables

    # Im just highjacking this if g.content is a
    # content.Content class
    if isinstance(g.content, content.Content):
        play_call = getattr(g.content, "_play", None)
        if callable(play_call):
            play_call(pre, choice, post)
        return

    if g.browse_mode == "ytpl":

        if choice.isdigit():
            g.selected_pafy_pls_id = g.ytpls[int(choice)-1]['link']
            return plist(g.selected_pafy_pls_id)
        else:
            g.message = "Invalid playlist selection: %s" % c.y + choice + c.w
            g.content = content.generate_songlist_display()
            return

    if not g.model:
        g.message = c.r + "There are no tracks to select" + c.w
        g.content = g.content or content.generate_songlist_display()

    else:
        shuffle = "shuffle" in pre + post
        repeat = "repeat" in pre + post
        novid = "-a" in pre + post
        fs = "-f" in pre + post
        nofs = "-w" in pre + post
        forcevid = "-v" in pre + post

        if ((novid and fs) or (novid and nofs) or (nofs and fs)
           or (novid and forcevid)):
            raise IOError("Conflicting override options specified")

        override = False
        override = "audio" if novid else override
        override = "fullscreen" if fs else override
        override = "window" if nofs else override

        if (not fs) and (not nofs):
            override = "forcevid" if forcevid else override

        selection = util.parse_multi(choice)
        songlist = [g.model[x - 1] for x in selection]

        # cache next result of displayed items
        # when selecting a single item
        if len(songlist) == 1:
            chosen = selection[0] - 1

            if len(g.model) > chosen + 1:
                streams.preload(g.model[chosen + 1], override=override)

        if g.scrobble:
            old_queue = g.scrobble_queue
            g.scrobble_queue = [g.scrobble_queue[x - 1] for x in selection]

        try:
            if not config.PLAYER.get or not util.has_exefile(config.PLAYER.get):
                g.message = "Player not configured! Enter %sset player <player_app> "\
                            "%s to set a player" % (c.g, c.w)
                return
            g.PLAYER_OBJ.play(songlist, shuffle, repeat, override)
        except KeyboardInterrupt:
            return
        finally:
            g.content = content.generate_songlist_display()

        if g.scrobble:
            g.scrobble_queue = old_queue

        if config.AUTOPLAY.get:
            related(selection.pop())
            play(pre, str(random.randint(1, 15)), post="")


@command(r'(%s{0,3})(?:\*|all)\s*(%s{0,3})' %
        (RS, RS))
def play_all(pre, choice, post=""):
    """ Play all tracks in model (last displayed). shuffle/repeat if req'd."""
    options = pre + choice + post
    play(options, "1-" + str(len(g.model)))


@command(r'playurl\s(.*[-_a-zA-Z0-9]{11}[^\s]*)(\s-(?:f|a|w))?', 'playurl')
def play_url(url: str, override: T.Any):
    """Open and play a youtube video url.

    Args:
        url: url to be played
        override: override

    Raises:
        SystemExit: If run from command line
    """
    # @fixme check override type hint
    override = override if override else "_"
    g.browse_mode = "normal"
    yt_url(url, print_title=True)

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

    if g.command_line:
        sys.exit()


@command(r'browserplay\s(\d{1,50})', 'browserplay')
def browser_play(number):
    """Open a previously searched result in the browser."""
    if (len(g.model) == 0):
        g.message = c.r + "No previous search." + c.w
        g.content = content.logo(c.r)
        return

    try:
        index = int(number) - 1

        if (0 <= index < len(g.model)):
            base_url = "https://www.youtube.com/watch?v="
            video = g.model[index]
            url = base_url + video.ytid
            webbrowser.open(url)
            g.content = g.content or content.generate_songlist_display()

        else:
            g.message = c.r + "Out of range." + c.w
            g.content = g.content or content.generate_songlist_display()
            return

    except (HTTPError, URLError, Exception) as e:
        g.message = c.r + str(e) + c.w
        g.content = g.content or content.generate_songlist_display()
        return


================================================
FILE: mps_youtube/commands/search.py
================================================
import base64
import json
import logging
import math
import re
import typing as T
from argparse import ArgumentParser
from datetime import datetime, timedelta
from urllib import parse

from .. import pafy

parser = ArgumentParser()
parser.add_argument('-d', '--duration', choices=('any', 'short', 'medium', 'long'))
parser.add_argument('-a', '--after')
parser.add_argument('-l', '--live', nargs="?", const=True)
parser.add_argument('-c', '--category', nargs=1)
parser.add_argument('search', nargs='+')


from .. import c, config, content, contentquery, g, listview, screen, util
from ..playlist import Playlist, Video
from . import command
from .songlist import paginatesongs, plist

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

DAYS = dict(day = 1,
            week = 7,
            month = 30,
            year = 365)


def _display_search_results(progtext, wdata, msg=None, failmsg=None):
    """ Perform memoized url fetch, display progtext. """

    loadmsg = "Searching for '%s%s%s'" % (c.y, progtext, c.w)

    def iter_songs():
        wdata2 = wdata
        while True:
            for song in get_tracks_from_json(wdata2):
                yield song

            if type(wdata2) is list or not wdata2.get('nextPageToken'):
                break
            query = None#wdata2['nextPageToken']
            wdata2 = None#pafy.call_gdata('search', qs)

    # The youtube search api returns a maximum of 500 results
    length = len(wdata)
    slicer = util.IterSlicer(iter_songs(), length)

    paginatesongs(slicer, length=length, msg=msg, failmsg=failmsg,
            loadmsg=loadmsg)


def token(page):
    """ Returns a page token for a given start index. """
    index = (page or 0) * util.getxy().max_results
    k = index//128 - 1
    index -= 128 * k
    f = [8, index]
    if k > 0 or index > 127:
        f.append(k+1)
    f += [16, 0]
    b64 = base64.b64encode(bytes(f)).decode('utf8')
    return b64.strip('=')


# def generate_search_qs(term, match='term', videoDuration='any', after=None, category=None, is_live=False):
#     """ Return query string. """
#
#     aliases = dict(views='viewCount')
#     qs = {
#         'q': term,
#         'maxResults': 50,
#         'safeSearch': "none",
#         'order': aliases.get(config.ORDER.get, config.ORDER.get),
#         'part': 'id,snippet',
#         'type': 'video',
#         'videoDuration': videoDuration
#         #,'key': config.API_KEY.get
#     }
#
#     if after:
#         after = after.lower()
#         qs['publishedAfter'] = '%sZ' % (datetime.utcnow() - timedelta(days=DAYS[after])).isoformat() \
#                                 if after in DAYS.keys() else '%s%s' % (after, 'T00:00:00Z' * (len(after) == 10))
#
#     if match == 'related':
#         qs['relatedToVideoId'] = term
#         del qs['q']
#
#     if config.SEARCH_MUSIC.get:
#         qs['videoCategoryId'] = 10
#
#     if category:
#         qs['videoCategoryId'] = category
#
#     if is_live:
#         qs['eventType'] = "live"
#
#     return qs


def userdata_cached(userterm):
    """ Check if user name search term found in cache """
    userterm = ''.join([t.strip().lower() for t in userterm.split(' ')])
    return g.username_query_cache.get(userterm)


def cache_userdata(userterm, username, channel_id):
    """ Cache user name and channel id tuple """
    userterm = ''.join([t.strip().lower() for t in userterm.split(' ')])
    g.username_query_cache[userterm] = (username, channel_id)
    util.dbg('Cache data for username search query "{}": {} ({})'.format(
        userterm, username, channel_id))

    while len(g.username_query_cache) > 300:
        g.username_query_cache.popitem(last=False)
    return (username, channel_id)


def channelfromname(user):
    """ Query channel id from username. """

    cached = userdata_cached(user)
    if cached:
        return cached

    try:
        channel_id, channel_name = pafy.channel_id_from_name(user)
        return cache_userdata(user, channel_name, channel_id)

    except Exception as e:
        import traceback
        traceback.print_exception(type(e), e, e.__traceback__)
        g.message = "Could not retrieve information for user {}\n{}".format(
            c.y + user + c.w, e)
        util.dbg('Error during channel request for user {}:\n{}'.format(
            user, e))

    # at this point, we know the channel id associated to a user name
    return None


@command(r'channels\s+(.+)')
def channelsearch(q_user):

    # qs = {'part': 'id,snippet',
    #       'q': q_user,
    #       'maxResults': 50,
    #       'type': 'channel',
    #       'order': "relevance"
    #       }

    QueryObj = contentquery.ContentQuery(listview.ListUser, 'search', q_user)
    columns = [
        {"name": "idx", "size": 3, "heading": "Num"},
        {"name": "name", "size": 30, "heading": "Username"},
        {"name": "description", "size": "remaining", "heading": "Description"},
        ]

    def run_m(user_id):
        """ Search ! """
        usersearch_id(*(user_id[0]))
    del g.content

    g.content = listview.ListView(columns, QueryObj, run_m)
    g.message = "Results for channel search: '%s'" % q_user


@command(r'user\s+(.+)', 'user')
def usersearch(q_user, identify='forUsername'):
    """ Fetch uploads by a YouTube user. """

    user, _, term = (x.strip() for x in q_user.partition("/"))
    if identify == 'forUsername':
        ret = channelfromname(user)
        if not ret:  # Error
            return
        user, channel_id = ret

    else:
        channel_id = user

    # at this point, we know the channel id associated to a user name
    usersearch_id(user, channel_id, term)


def usersearch_id(user, channel_id, term):
    """ Performs a search within a user's (i.e. a channel's) uploads
    for an optional search term with the user (i.e. the channel)
    identified by its ID """

    #query = generate_search_qs(term)
    aliases = dict(views='viewCount')  # The value of the config item is 'views' not 'viewCount'
    if config.USER_ORDER.get:
        pass
        #query['order'] = aliases.get(config.USER_ORDER.get,
        #        config.USER_ORDER.get)
    #query['channelId'] = channel_id

    termuser = tuple([c.y + x + c.w for x in (term, user)])
    if term:
        msg = "Results for {1}{3}{0} (by {2}{4}{0})"
        progtext = "%s by %s" % termuser
        failmsg = "No matching results for %s (by %s)" % termuser
    else:
        msg = "Video uploads by {2}{4}{0}"
        progtext = termuser[1]
        if config.SEARCH_MUSIC:
            failmsg = """User %s not found or has no videos in the Music category.
Use 'set search_music False' to show results not in the Music category.""" % termuser[1]
        else:
            failmsg = "User %s not found or has no videos."  % termuser[1]
    msg = str(msg).format(c.w, c.y, c.y, term, user)
    results = pafy.all_videos_from_channel(channel_id)
    _display_search_results(progtext, results, msg, failmsg)


def related_search(vitem):
    """ Fetch videos related to vitem
    vitem = {'description': str, 'length': int, 'title': str, 'ytid': str}
    """

    t = vitem.title
    ttitle = t[:48].strip() + ".." if len(t) > 49 else t

    msg = "Videos related to %s%s%s" % (c.y, ttitle, c.w)
    failmsg = "Related to %s%s%s not found" % (c.y, vitem.ytid, c.w)

    # todo: implement realted search in pafy
    #_search(ttitle, vitem.title, msg, failmsg)


# Livestream category search
@command(r'live\s+(.+)', 'live')
def livestream_category_search(term):
    sel_category = g.categories.get(term, None)

    if not sel_category:
        g.message = ("That is not a valid category. Valid categories are: ")
        g.message += (", ".join(g.categories.keys()))
        return

    query = {
        "part": "id,snippet",
        "eventType": "live",
        "maxResults": 50,
        "type": "video",
        "videoCategoryId": sel_category
    }

    query_obj = contentquery.ContentQuery(listview.ListLiveStream, 'search', query)
    columns = [
              {"name": "idx", "size": 3, "heading": "Num"},
              {"name": "title", "size": 40, "heading": "Title"},
              {"name": "description", "size": "remaining", "heading": "Description"},
              ]

    def start_stream(returned):
        songs = Playlist("Search Results", [Video(*x) for x in returned])
        if not config.PLAYER.get or not util.has_exefile(config.PLAYER.get):
            g.message = "Player not configured! Enter %sset player <player_app> "\
                        "%s to set a player" % (c.g, c.w)
            return
        g.PLAYER_OBJ.play(songs, False, False, False)

    g.content = listview.ListView(columns, query_obj, start_stream)
    g.message = "Livestreams in category: '%s'" % term


# Note: [^./] is to prevent overlap with playlist search command
@command(r'(?:search|\.|/)\s*([^./].{1,500})', 'search')
def search(term):
    """ Perform search. """
    try:  # TODO make use of unknowns
        args, unknown = parser.parse_known_args(term.split())
        video_duration = args.duration if args.duration else 'any'
        if args.category:
            if not args.category[0].isdigit():
                args.category = g.categories.get(args.category[0])
            else:
                args.category = "".join(args.category)
        after = args.after
        term = ' '.join(args.search)
    except SystemExit:  # <------ argsparse calls exit()
        g.message = c.b + "Bad syntax. Enter h for help" + c.w
        return

    if not term or len(term) < 2:
        g.message = c.r + "Not enough input" + c.w
        g.content = content.generate_songlist_display()
        return

    logging.info("search for %s", term)
    #query = generate_search_qs(term, videoDuration=video_duration, after=after, category=args.category, is_live=args.live)

    msg = "Search results for %s%s%s" % (c.y, term, c.w)
    failmsg = "Found nothing for %s%s%s" % (c.y, term, c.w)
    wdata = pafy.search_videos(term, int(config.PAGES.get))
    _display_search_results(term, wdata, msg, failmsg)


@command(r'u(?:ser)?pl\s(.*)', 'userpl', 'upl')
def user_pls(user):
    """ Retrieve user playlists. """
    return pl_search(user, is_user=True)


@command(r'(?:\.\.|\/\/|pls(?:earch)?\s)\s*(.*)', 'plsearch')
def pl_search(term, page=0, splash=True, is_user=False):
    """ Search for YouTube playlists.

    term can be query str or dict indicating user playlist search.

    """
    if not term or len(term) < 2:
        g.message = c.r + "Not enough input" + c.w
        g.content = content.generate_songlist_display()
        return

    if splash:
        g.content = content.logo(c.g)
        prog = "user: " + term if is_user else term
        g.message = "Searching playlists for %s" % c.y + prog + c.w
        screen.update()

    logging.info("playlist search for %s", prog)
    if is_user:
        ret = channelfromname(term)
        if not ret:
            return
        user, channel_id = ret
        pldata = pafy.all_playlists_from_channel(channel_id)
    else:
        pldata = pafy.playlist_search(term)

    playlists = get_pl_from_json(pldata)[:util.getxy().max_results]

    if playlists:
        g.last_search_query = (pl_search, {"term": term, "is_user": is_user})
        g.browse_mode = "ytpl"
        g.current_page = page
        g.result_count = len(pldata)
        g.ytpls = playlists
        g.message = "Playlist results for %s" % c.y + prog + c.w
        g.content = content.generate_playlist_display()

    else:
        g.message = "No playlists found for: %s" % c.y + prog + c.w
        g.current_page = 0
        g.content = content.generate_songlist_display(zeromsg=g.message)


def get_pl_from_json(pldata):
    """ Process json playlist data. """

    try:
        items = pldata

    except KeyError:
        items = []

    results = []

    for item in items:
        results.append(dict(
            link=item["id"],
            size=item["videoCount"],
            title=item["title"],
            author= item['channel']["name"] if 'channel' in item.keys()  else None,
            created=item.get("publishedAt"),
            updated=item.get('publishedAt'), #XXX Not available in API?
            description=item.get("description")))

    return results


def get_track_id_from_json(item):
    """ Try to extract video Id from various response types """
    fields = ['contentDetails/videoId',
              'snippet/resourceId/videoId',
              'id/videoId',
              'id']
    for field in fields:
        node = item
        for p in field.split('/'):
            if node and isinstance(node, dict):
                node = node.get(p)
        if node:
            return node
    return ''


def get_tracks_from_json(jsons):
    """ Get search results from API response """

    if len(jsons) == 0:
        util.dbg("got unexpected data or no search results")
        return ()

    # populate list of video objects
    songs = []
    for item in jsons:
        try:
            ytid = get_track_id_from_json(item)
            duration = util.parse_video_length(item.get('duration'))
            #stats = item.get('statistics', {})
            #snippet = item.get('snippet', {})
            title = item.get('title', '').strip()
            # instantiate video representation in local model
            cursong = Video(ytid=ytid, title=title, length=duration)
            dislike_data = {'likes': 0, 'dislikes':0, 'rating':0}#pafy.return_dislikes(ytid)
            likes = int(dislike_data['likes'])
            dislikes = int(dislike_data['dislikes'])
            # this is a very poor attempt to calculate a rating value
            rating = int(dislike_data['rating'])#5.*likes/(likes+dislikes) if (likes+dislikes) > 0 else 0
            category = '?'#snippet.get('categoryId')
            publishedlocaldatetime = item.get('publishedTime','?')#util.yt_datetime_local(snippet.get('publishedAt', ''))

            # cache video information in custom global variable store
            g.meta[ytid] = dict(
                # tries to get localized title first, fallback to normal title
                title=title,
                length=str(util.fmt_time(cursong.length)),
                rating=rating,#str('{}'.format(rating))[:4].ljust(4, "0"),
                uploader=item['channel']['id'],
                uploaderName=item['channel']['name'],
                category=category,
                aspect="custom", #XXX
                uploaded=publishedlocaldatetime,#publishedlocaldatetime[1] if publishedlocaldatetime is not None else None,
                uploadedTime=publishedlocaldatetime,#,publishedlocaldatetime[2] if publishedlocaldatetime is not None else None,
                likes=str(num_repr(likes)),
                dislikes=str(num_repr(dislikes)),
                commentCount='?',#str(num_repr(int(stats.get('commentCount', 0)))),
                viewCount= item['viewCount']['text'] if 'viewCount' in item.keys() else '?')#str(num_repr(int(stats.get('viewCount', 0)))))
            songs.append(cursong)

        except Exception as e:
            import traceback
            traceback.print_exception(type(e), e, e.__traceback__)
            input('Press any key to continue...')
            util.dbg(json.dumps(item, indent=2))
            util.dbg('Error during metadata extraction/instantiation of ' +
                'search result {}\n{}'.format(ytid, e))



    # return video objects
    return songs


def num_repr(num):
    """ Return up to four digit string representation of a number, eg 2.6m. """
    if num <= 9999:
        return str(num)

    def digit_count(x):
        """ Return number of digits. """
        return int(math.floor(math.log10(x)) + 1)

    digits = digit_count(num)
    sig = 3 if digits % 3 == 0 else 2
    rounded = int(round(num, int(sig - digits)))
    digits = digit_count(rounded)
    suffix = "_kmBTqXYX"[(digits - 1) // 3]
    front = 3 if digits % 3 == 0 else digits % 3

    if not front == 1:
        return str(rounded)[0:front] + suffix

    return str(rounded)[0] + "." + str(rounded)[1] + suffix


@command(r'u\s?([\d]{1,4})', 'u')
def user_more(num):
    """ Show more videos from user of vid num. """
    if g.browse_mode != "normal":
        g.message = "User uploads must refer to a specific video item"
        g.message = c.y + g.message + c.w
        g.content = content.generate_songlist_display()
        return

    g.current_page = 0
    item = g.model[int(num) - 1]

    #TODO: Cleaner way of doing this?
    if item.ytid in g.meta:
        channel_id = g.meta.get(item.ytid, {}).get('uploader')
        user = g.meta.get(item.ytid, {}).get('uploaderName')
    else:
        paf = util.get_pafy(item)
        user, channel_id = channelfromname(paf.author)

    usersearch_id(user, channel_id, '')


@command(r'r\s?(\d{1,4})', 'r')
def related(num):
    """ Show videos related to to vid num. """
    if g.browse_mode != "normal":
        g.message = "Related items must refer to a specific video item"
        g.message = c.y + g.message + c.w
        g.content = content.generate_songlist_display()
        return

    g.current_page = 0
    item = g.model[int(num) - 1]
    related_search(item)


@command(r'mix\s*(\d{1,4})', 'mix')
def mix(num):
    """ Retrieves the YouTube mix for the selected video. """
    g.content = g.content or content.generate_songlist_display()
    if g.browse_mode != "normal":
        g.message = util.F('mix only videos')
    else:
        item = (g.model[int(num) - 1])
        if item is None:
            g.message = util.F('invalid item')
            return
        item = util.get_pafy(item)
        # Mix playlists are made up of 'RD' + video_id
        try:
            plist("RD" + item.videoid)
        except OSError:
            g.message = util.F('no mix')


@command(r"url\s(.*[-_a-zA-Z0-9]{11}.*)", "url")
def yt_url(url: str, print_title: bool = False):
    """
    Acess videos by urls.

    If `print_title` is true only last title from unique parsed id will be printed.

    If for example `vid1` and `vid2` have title `title1` and `title2`, respectively,
    `yt_url('vid1 vid2 vid1', True)`
    will print `title2` from `vid2` instead `title1` from last entry `vid1`.

    Args:
        url: youtube url
        print_title: print title or not
    """
    url_list = url.split()

    g.model.songs = []

    v_ids = set()
    v_title = None
    for url in url_list:
        try:
            v_id = pafy.extract_video_id(url)
            if v_id in v_ids:
                continue
            p = pafy.get_video_info(v_id)
        except (IOError, ValueError) as e:
            g.message = c.r + str(e) + c.w
            g.content = g.content or content.generate_songlist_display(
                    zeromsg=g.message)
            return

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

    if not g.command_line:
        g.content = content.generate_songlist_display()

    if print_title and v_title:
        util.xprint(v_title)


@command(r'url_file\s(\S+)', 'url_file')
def yt_url_file(file_name):
    """ Access a list of urls in a text file """

    #Open and read the file
    try:
        with open(file_name, "r") as fo:
            output = ' '.join([line.strip() for line in fo if line.strip()])

    except (IOError):
        g.message = c.r + 'Error while opening the file, check the validity of the path' + c.w
        g.content = g.content or content.generate_songlist_display(
                zeromsg=g.message)
        return

    #Finally pass the input to yt_url
    yt_url(output)


================================================
FILE: mps_youtube/commands/songlist.py
================================================
import math
import random


from .. import g, c, screen, streams, content, util, pafy
from ..playlist import Video
from . import command, PL


def paginatesongs(func, page=0, splash=True, dumps=False,
        length=None, msg=None, failmsg=None, loadmsg=None):
    """
    A utility function for handling lists of songs, so that
    the pagination and the dump command will work properly.

    :param func: Either a function taking a start and end index,
        or a slicable object. Either way, it should produce an iterable
        of :class:`mps_youtube.playlist.Video` objects.
    :param page: The page number to display
    :param splash: Whether or not to display a splash screen while
        loading.
    :param dumps: Used by :func:`dump` command to load all songs, instead
        of only those that fit on a page
    :param length: The total number of songs. It it is not provided,
        ``len(func)`` will be used instead.
    :param msg: Message to display after loading successfully
    :param failmsg: Message to display on failure (if no songs are
        returned by func
    :param loadmsg: Message to display while loading
    :type page: int
    :type splash: bool
    :type dumps: bool
    :type length: int
    :type msg: str
    :type failmsg: str
    :type loadmsg: str
    """
    if splash:
        g.message = loadmsg or ''
        g.content = content.logo(col=c.b)
        screen.update()

    max_results = util.getxy().max_results

    if dumps:
        s = 0
        e = None
    else:
        s = page * max_results
        e = (page + 1) * max_results

    if callable(func):
        songs = func(s, e)
    else:
        songs = func[s:e]

    if length is None:
        length = len(func)

    args = {'func':func, 'length':length, 'msg':msg,
            'failmsg':failmsg, 'loadmsg': loadmsg}
    g.last_search_query = (paginatesongs, args)
    g.browse_mode = "normal"
    g.current_page = page
    g.result_count = length
    g.model.songs = songs
    g.content = content.generate_songlist_display()
    g.last_opened = ""
    g.message = msg or ''
    if not songs:
        g.message = failmsg or g.message

    if songs:
        # preload first result url
        streams.preload(songs[0], delay=0)


@command(r'pl\s+%s' % PL, 'pl')
def plist(parturl):
    """ Retrieve YouTube playlist. """

    if parturl in g.pafy_pls:
        ytpl, plitems = g.pafy_pls[parturl]
    else:
        util.dbg("%sFetching playlist using pafy%s", c.y, c.w)
        ytpl = pafy.get_playlist(parturl)
        plitems = util.IterSlicer(ytpl.videos)
        g.pafy_pls[parturl] = (ytpl, plitems)

    def pl_seg(s, e):
        return [Video(i['id'], i['title'], util.parse_video_length(i['duration'])) for i in plitems[s:e]]

    msg = "Showing YouTube playlist %s" % (c.y + ytpl.info['info']['title'] + c.w)
    loadmsg = "Retrieving YouTube playlist"
    paginatesongs(pl_seg, length=len(ytpl.videos), msg=msg, loadmsg=loadmsg)


@command(r'(rm|add)\s*(-?\d[-,\d\s]{,250})', 'rm', 'add')
def songlist_rm_add(action, songrange):
    """ Remove or add tracks. works directly on user input. """
    selection = util.parse_multi(songrange)

    if action == "add":
        duplicate_songs = []
        for songnum in selection:
            if g.model[songnum - 1] in g.active:
                duplicate_songs.append(str(songnum))
            g.active.songs.append(g.model[songnum - 1])

        d = g.active.duration
        g.message = util.F('added to pl') % (len(selection), len(g.active), d)
        if duplicate_songs:
            duplicate_songs = ', '.join(sorted(duplicate_songs))
            g.message += '\n'
            g.message += util.F('duplicate tracks') % duplicate_songs

    elif action == "rm":
        selection = sorted(set(selection), reverse=True)
        removed = str(tuple(reversed(selection))).replace(",", "")

        for x in selection:
            g.model.songs.pop(x - 1)
            try:
                g.active.songs.pop(g.current_page * util.getxy().max_results + x - 1)
            except IndexError:
                pass

        g.message = util.F('songs rm') % (len(selection), removed)

    g.content = content.generate_songlist_display()


@command(r'(mv|sw)\s*(\d{1,4})\s*[\s,]\s*(\d{1,4})', 'mv', 'sw')
def songlist_mv_sw(action, a, b):
    """ Move a song or swap two songs. """
    i, j = int(a) - 1, int(b) - 1

    if action == "mv":
        g.model.songs.insert(j, g.model.songs.pop(i))
        g.message = util.F('song move') % (g.model[j].title, b)

    elif action == "sw":
        g.model[i], g.model[j] = g.model[j], g.model[i]
        g.message = util.F('song sw') % (min(a, b), max(a, b))

    g.content = content.generate_songlist_display()


@command(r'(n|p)\s*(\d{1,2})?')
def nextprev(np, page=None):
    """ Get next / previous search results. """
    if isinstance(g.content, content.PaginatedContent):
        page_count = g.content.numPages()
        function = g.content.getPage
        args = {}
    else:
        page_count = math.ceil(g.result_count/util.getxy().max_results)
        function, args = g.last_search_query

    good = False

    if function:
        if np == "n":
            if g.current_page + 1 < page_count:
                g.current_page += 1
                good = True

        elif np == "p":
            if page and int(page) in range(1,20):
                g.current_page = int(page)-1
                good = True

            elif g.current_page > 0:
                g.current_page -= 1
                good = True

    if good:
        function(page=g.current_page, **args)

    else:
        norp = "next" if np == "n" else "previous"
        g.message = "No %s items to display" % norp

    if not isinstance(g.content, content.PaginatedContent):
        g.content = content.generate_songlist_display()
    return good


@command(r'(un)?dump', 'dump', 'undump')
def dump(un):
    """ Show entire playlist. """
    func, args = g.last_search_query

    if func is paginatesongs:
        paginatesongs(dumps=(not un), **args)

    else:
        un = "" if not un else un
        g.message = "%s%sdump%s may only be used on an open YouTube playlist"
        g.message = g.message % (c.y, un, c.w)
        g.content = content.generate_songlist_display()


@command(r'shuffle', 'shuffle')
def shuffle_fn():
    """ Shuffle displayed items. """
    random.shuffle(g.model.songs)
    g.message = c.y + "Items shuffled" + c.w
    g.content = content.generate_songlist_display()

@command(r'shuffle all', 'shuffle all')
def shuffle_playlist():
    """ Shuffle entire loaded playlist. """
    songs = content.get_last_query()

    if songs: 
        random.shuffle(songs)
        paginatesongs(list(songs))
        g.message = c.y + "Shuffled entire playlist" + c.w
        g.content = content.generate_songlist_display()

@command(r'reverse', 'reverse')
def reverse_songs():
    """ Reverse order of displayed items. """
    g.model.songs = g.model.songs[::-1]
    g.message = c.y + "Reversed displayed songs" + c.w
    g.content = content.generate_songlist_display()


@command(r'reverse\s*(\d{1,4})\s*-\s*(\d{1,4})\s*', 'reverse')
def reverse_songs_range(lower, upper):
    """ Reverse the songs within a specified range. """
    lower, upper = int(lower), int(upper)
    if lower > upper: lower, upper = upper, lower
    
    g.model.songs[lower-1:upper] = reversed(g.model.songs[lower-1:upper])
    g.message = c.y + "Reversed range: " + str(lower) + "-" + str(upper) + c.w
    g.content = content.generate_songlist_display()
    

@command(r'reverse all', 'reverse all')
def reverse_playlist():
    """ Reverse order of entire loaded playlist. """
    songs = content.get_last_query()

    if songs:   
        paginatesongs(list(reversed(songs)))
        g.message = c.y + "Reversed entire playlist" + c.w
        g.content = content.generate_songlist_display()


================================================
FILE: mps_youtube/commands/spotify_playlist.py
================================================
import re
import time
import difflib

try:
    # pylint: disable=F0401
    import spotipy
    import spotipy.oauth2 as oauth2
    has_spotipy = True

except ImportError:
    has_spotipy = False


from .. import c, g, screen, __version__, __url__, content, config, util
from . import command
from .songlist import paginatesongs
from .search import get_tracks_from_json


def generate_credentials():
    """Generate the token. Please respect these credentials :)"""
    credentials = oauth2.SpotifyClientCredentials(
        client_id='6451e12933bb49ed8543d41e3296a88d',
        client_secret='40ef54678fe441bd9acd66f5d5c34e69')
    return credentials


def grab_playlist(spotify, playlist):
    if '/' in playlist:
        if playlist.endswith('/'):
            playlist = playlist[:-1]
        splits = playlist.split('/')
    else:
        splits = playlist.split(':')

    username = splits[-3]
    playlist_id = splits[-1]
    results = spotify.user_playlist(username, playlist_id,
                                    fields='tracks,next,name,owner')

    all_tracks = []
    tracks = results['tracks']
    while True:
        for item in tracks['items']:
            track = item['track']
            try:
                all_tracks.append(track)
            except KeyError:
                pass
        # 1 page = 50 results
        # check if there are more pages
        if tracks['next']:
            tracks = spotify.next(tracks)
        else:
            break

    return (results, all_tracks)


def show_message(message, col=c.r, update=False):
    """ Show message using col, update screen if required. """
    g.content = content.generate_songlist_display()
    g.message = col + message + c.w

    if update:
        screen.update()


def _best_song_match(songs, title, duration, titleweight, durationweight):
    """ Select best matching song based on title, length.

    Score from 0 to 1 where 1 is best. titleweight and durationweight
    parameters added to enable function usage when duration can't be guessed

    """
    # pylint: disable=R0914
    seqmatch = difflib.SequenceMatcher

    def variance(a, b):
        """ Return difference ratio. """
        return float(abs(a - b)) / max(a, b)

    candidates = []

    ignore = "music video lyrics new lyrics video audio".split()
    extra = "official original vevo".split()

    for song in songs:
        dur, tit = int(song.length), song.title
        util.dbg("Title: %s, Duration: %s", tit, dur)

        for word in extra:
            if word in tit.lower() and word not in title.lower():
                pattern = re.compile(word, re.I)
                tit = pattern.sub("", tit)

        for word in ignore:
            if word in tit.lower() and word not in title.lower():
                pattern = re.compile(word, re.I)
                tit = pattern.sub("", tit)

        replacechars = re.compile(r"[\]\[\)\(\-]")
        tit = replacechars.sub(" ", tit)
        multiple_spaces = re.compile(r"(\s)(\s*)")
        tit = multiple_spaces.sub(r"\1", tit)

        title_score = seqmatch(None, title.lower(), tit.lower()).ratio()
        duration_score = 1 - variance(duration, dur)
        util.dbg("Title score: %s, Duration score: %s", title_score,
                 duration_score)

        # apply weightings
        score = duration_score * durationweight + title_score * titleweight
        candidates.append((score, song))

    best_score, best_song = max(candidates, key=lambda x: x[0])
    percent_score = int(100 * best_score)
    return best_song, percent_score


def _match_tracks(tracks):
    """ Match list of tracks by performing multiple searches. """
    # pylint: disable=R0914

    def dtime(x):
        """ Format time to M:S. """
        return time.strftime('%M:%S', time.gmtime(int(x)))

    # do matching
    for track in tracks:
        ttitle = track['name']
        artist = track['artists'][0]['name']
        length = track['duration_ms']/1000
        util.xprint("Search :  %s%s - %s%s - %s" % (c.y, artist, ttitle, c.w,
                                                    dtime(length)))
        q = "%s %s" % (artist, ttitle)
        w = q = ttitle if artist == "Various Artists" else q
        query = w#generate_search_qs(w, 0)
        util.dbg(query)

        # perform fetch
        wdata = None#pafy.call_gdata('search', query)
        results = get_tracks_from_json(wdata)

        if not results:
            util.xprint(c.r + "Nothing matched :(\n" + c.w)
            continue

        s, score = _best_song_match(
            results, artist + " " + ttitle, length, .5, .5)
        cc = c.g if score > 85 else c.y
        cc = c.r if score < 75 else cc
        util.xprint("Matched:  %s%s%s - %s \n[%sMatch confidence: "
                    "%s%s]\n" % (c.y, s.title, c.w, util.fmt_time(s.length),
                                 cc, score, c.w))
        yield s


@command(r'suser\s*(.*[-_a-zA-Z0-9].*)?', 'suser')
def search_user(term):
    """Search for Spotify user playlists. """
    # pylint: disable=R0914,R0912
    if has_spotipy:

        if not term:
            show_message("Enter username:", c.g, update=True)
            term = input("> ")

            if not term or len(term) < 2:
                g.message = c.r + "Not enough input!" + c.w
                g.content = None#content.generate_songlist_display()
                return

        credentials = generate_credentials()
        token = credentials.get_access_token()
        spotify = spotipy.Spotify(auth=token)

        playlists = spotify.user_playlists(term)
        links = []
        check = 1

        g.content = "Playlists:\n"

        while True:
            for playlist in playlists['items']:
                if playlist['name'] is not None:
                    g.content += (u'{0:>2}. {1:<30}  ({2} tracks)'.format(
                        check, playlist['name'],
                        playlist['tracks']['total']))
                    g.content += "\n"
                    links.append(playlist)
                    check += 1
            if playlists['next']:
                playlists = spotify.next(playlists)
            else:
                break

        g.message = c.g + "Choose your playlist:" + c.w
        screen.update()

        choice = int(input("> "))
        playlist = links[choice-1]

        search_playlist(playlist['external_urls']['spotify'], spotify=spotify)

    else:
        g.message = "spotipy module must be installed for Spotify support\n"
        g.message += "see https://pypi.python.org/pypi/spotipy/"



@command(r'splaylist\s*(.*[-_a-zA-Z0-9].*)?', 'splaylist')
def search_playlist(term, spotify=None):
    """Search for Spotify playlist. """
    # pylint: disable=R0914,R0912
    if has_spotipy:

        if not term:
            show_message("Enter playlist url:", c.g, update=True)
            term = input("> ")

            if not term or len(term) < 2:
                g.message = c.r + "Not enough input!" + c.w
                g.content = None#content.generate_songlist_display()
                return

        if not spotify:
            credentials = generate_credentials()
            token = credentials.get_access_token()
            spotify = spotipy.Spotify(auth=token)

        try:
            playlist, tracks = grab_playlist(spotify, term)
        except TypeError:
            tracks = None

        if not tracks:
            show_message("Playlist '%s' not found!" % term)
            return

        if not playlist['tracks']['total']:
            show_message("Playlist '%s' by '%s' has 0 tracks!" % (playlist['name'], playlist['owner']['id']))
            return

        msg = "%s%s%s by %s%s%s\n\n" % (c.g, playlist['name'], c.w, c.g, playlist['owner']['id'], c.w)
        msg += "Enter to begin matching or [q] to abort"
        g.message = msg
        g.content = "Tracks:\n"
        for n, track in enumerate(tracks, 1):
            trackname = '{0:<20} - {1}'.format(track['artists'][0]['name'], track['name'])
            g.content += "%03s  %s" % (n, trackname)
            g.content += "\n"

        screen.update()
        entry = input("Continue? [Enter] > ")

        if entry == "":
            pass

        else:
            show_message("Playlist search abandoned!")
            return

        songs = []
        screen.clear()
        itt = _match_tracks(tracks)

        stash = config.SEARCH_MUSIC.get, config.ORDER.get
        config.SEARCH_MUSIC.value = True
        config.ORDER.value = "relevance"

        try:
            songs.extend(itt)

        except KeyboardInterrupt:
            util.xprint("%sHalted!%s" % (c.r, c.w))

        finally:
            config.SEARCH_MUSIC.value, config.ORDER.value = stash

        if songs:
            util.xprint("\n%s / %s songs matched" % (len(songs), len(tracks)))
            input("Press Enter to continue")

        msg = "Contents of playlist %s%s - %s%s %s(%d/%d)%s:" % (
            c.y, playlist['owner']['id'], playlist['name'], c.w, c.b, len(songs), len(tracks), c.w)
        failmsg = "Found no playlist tracks for %s%s%s" % (c.y, playlist['name'], c.w)

        paginatesongs(songs, msg=msg, failmsg=failmsg)

    else:
        g.message = "spotipy module must be installed for Spotify support\n"
        g.message += "see https://pypi.python.org/pypi/spotipy/"


================================================
FILE: mps_youtube/config.py
================================================
import os
import re
import sys
import copy
import pickle
import json
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.parse import urlencode

try:
    import pylast
    has_pylast = True
except ImportError:
    has_pylast = False

from . import g, c, paths, util


mswin = os.name == "nt"

class ConfigItem:

    """ A configuration item. """

    def __init__(self, name, value, minval=None, maxval=None, check_fn=None,
            require_known_player=False, allowed_values=None):
        """ If specified, the check_fn should return a dict.

        {valid: bool, message: success/fail mesage, value: value to set}

        """
        self.default = self.value = value
        self.temp_value = None
        self.name = name
        self.type = type(value)
        self.maxval, self.minval = maxval, minval
        self.check_fn = check_fn
        self.require_known_player = require_known_player
        self.allowed_values = []
        if allowed_values:
            self.allowed_values = allowed_values

    @property
    def get(self):
        """ Return value. """
        if self.temp_value is None:
            return self.value
        else:
            return self.temp_value

    @property
    def display(self):
        """ Return value in a format suitable for display. """
        return self.display_helper(self.value)

    @property
    def display_temp(self):
        if self.temp_value is None: return ""
        return self.display_helper(self.temp_value)

    def display_helper(self, retval):
        if self.name == "max_res":
            retval = str(retval) + "p"

        if self.name == "encoder":
            retval = str(retval) + " [%s]" % (str(g.encoders[retval]['name']))

        return retval

    def set(self, value, is_temp=False):
        """ Set value with checks. """
        # note: fail_msg should contain %s %s for self.name, value
        #       success_msg should not
        # pylint: disable=R0912
        # too many branches

        success_msg = fail_msg = ""
        value = value.strip()
        value_orig = value

        # handle known player not set

        if self.allowed_values and value not in self.allowed_values:
            fail_msg = "%s must be one of * - not %s"
            allowed_values = copy.copy(self.allowed_values)
            if '' in allowed_values:
                allowed_values[allowed_values.index('')] = "<nothing>"
            fail_msg = fail_msg.replace("*", ", ".join(allowed_values))

        if self.require_known_player and \
                not util.is_known_player(Config.PLAYER.get):
            fail_msg = "%s requires mpv or mplayer, can't set to %s"

        # handle true / false values

        elif self.type == bool:

            if value.upper() in "0 OFF NO DISABLED FALSE".split():
           
Download .txt
gitextract_ckd9x4df/

├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Dockerfile
├── ISSUE_TEMPLATE.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── RELEASING.md
├── _config.yml
├── doc/
│   ├── conf.py
│   ├── index.rst
│   ├── modules.rst
│   ├── mps_youtube.c.rst
│   ├── mps_youtube.cache.rst
│   ├── mps_youtube.commands.album_search.rst
│   ├── mps_youtube.commands.config.rst
│   ├── mps_youtube.commands.download.rst
│   ├── mps_youtube.commands.local_playlist.rst
│   ├── mps_youtube.commands.misc.rst
│   ├── mps_youtube.commands.play.rst
│   ├── mps_youtube.commands.rst
│   ├── mps_youtube.commands.search.rst
│   ├── mps_youtube.commands.songlist.rst
│   ├── mps_youtube.config.rst
│   ├── mps_youtube.content.rst
│   ├── mps_youtube.g.rst
│   ├── mps_youtube.helptext.rst
│   ├── mps_youtube.history.rst
│   ├── mps_youtube.init.rst
│   ├── mps_youtube.main.rst
│   ├── mps_youtube.mpris.rst
│   ├── mps_youtube.paths.rst
│   ├── mps_youtube.player.rst
│   ├── mps_youtube.playlist.rst
│   ├── mps_youtube.playlists.rst
│   ├── mps_youtube.rst
│   ├── mps_youtube.screen.rst
│   ├── mps_youtube.streams.rst
│   ├── mps_youtube.terminalsize.rst
│   └── mps_youtube.util.rst
├── docs/
│   ├── changelog.md
│   ├── contributing.md
│   ├── css/
│   │   └── mkdocstrings.css
│   ├── gen_ref_nav.py
│   ├── index.md
│   └── license.md
├── mkdocs.yml
├── mps_youtube/
│   ├── __init__.py
│   ├── c.py
│   ├── cache.py
│   ├── commands/
│   │   ├── __init__.py
│   │   ├── album_search.py
│   │   ├── config.py
│   │   ├── download.py
│   │   ├── generate_playlist.py
│   │   ├── lastfm.py
│   │   ├── local_playlist.py
│   │   ├── misc.py
│   │   ├── play.py
│   │   ├── search.py
│   │   ├── songlist.py
│   │   └── spotify_playlist.py
│   ├── config.py
│   ├── content.py
│   ├── contentquery.py
│   ├── description_parser.py
│   ├── g.py
│   ├── helptext.py
│   ├── history.py
│   ├── init.py
│   ├── listview/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── livestream.py
│   │   ├── songtitle.py
│   │   └── user.py
│   ├── main.py
│   ├── mpris.py
│   ├── pafy.py
│   ├── paths.py
│   ├── player.py
│   ├── players/
│   │   ├── GenericPlayer.py
│   │   ├── __init__.py
│   │   ├── mplayer.py
│   │   ├── mpv.py
│   │   └── vlc.py
│   ├── playlist.py
│   ├── playlists.py
│   ├── screen.py
│   ├── streams.py
│   ├── terminalsize.py
│   ├── test/
│   │   ├── test_main.py
│   │   ├── test_mpris.py
│   │   ├── test_players_mplayer.py
│   │   └── test_util.py
│   └── util.py
├── requirements.txt
├── setup.cfg
├── setup.py
├── wheel_recipe.sh
├── yewtube.desktop
└── yt
Download .txt
SYMBOL INDEX (416 symbols across 45 files)

FILE: mps_youtube/c.py
  function c (line 20) | def c(colour, text):
  function charcount (line 25) | def charcount(s):

FILE: mps_youtube/cache.py
  function load (line 13) | def load():
  function save (line 44) | def save():

FILE: mps_youtube/commands/__init__.py
  function command (line 25) | def command(regex, *commands):

FILE: mps_youtube/commands/album_search.py
  function show_message (line 17) | def show_message(message, col=c.r, update=False):
  function _do_query (line 26) | def _do_query(url, query, err='query failed', report=False):
  function _best_song_match (line 52) | def _best_song_match(songs, title, duration, titleweight, durationweight):
  function _match_tracks (line 104) | def _match_tracks(artist, title, mb_tracks):
  function _get_mb_tracks (line 145) | def _get_mb_tracks(albumid):
  function _get_mb_album (line 178) | def _get_mb_album(albumname, **kwa):
  function search_album (line 210) | def search_album(term):

FILE: mps_youtube/commands/config.py
  function showconfig (line 6) | def showconfig():
  function setconfigtemp (line 56) | def setconfigtemp(key, val):
  function setconfig (line 61) | def setconfig(key, val, is_temp=False):
  function show_encs (line 93) | def show_encs():

FILE: mps_youtube/commands/download.py
  function download (line 18) | def download(dltype, num):
  function down_many (line 130) | def down_many(dltype, choice, subdir=None):
  function down_plist (line 194) | def down_plist(dltype, parturl):
  function down_user_pls (line 209) | def down_user_pls(dltype, user):
  function _make_fname (line 218) | def _make_fname(song, ext=None, av=None, subdir=None):
  function extract_metadata (line 239) | def extract_metadata(name):
  function remux_audio (line 256) | def remux_audio(filename, title):
  function transcode (line 285) | def transcode(filename, enc_data):
  function external_download (line 321) | def external_download(song, filename, url):
  function _download (line 340) | def _download(song, filename, url=None, audio=False, allow_transcode=True):
  function menu_prompt (line 412) | def menu_prompt(model, prompt=" > ", rows=None, header=None, theading=None,
  function prompt_dl (line 445) | def prompt_dl(song):
  function gen_dl_text (line 475) | def gen_dl_text(ddata, song, p):
  function get_dl_data (line 505) | def get_dl_data(song, mediatype="any"):
  function dl_url (line 545) | def dl_url(url):
  function da_url (line 558) | def da_url(url):

FILE: mps_youtube/commands/generate_playlist.py
  function generate_playlist (line 14) | def generate_playlist(sourcefile):
  function read_sourcefile (line 34) | def read_sourcefile(filename):
  function check_sourcefile (line 46) | def check_sourcefile(filename):
  function create_playlist (line 51) | def create_playlist(queries, title=''):
  function find_best_match (line 70) | def find_best_match(query):
  function random_plname (line 82) | def random_plname():
  function description_generator (line 89) | def description_generator(text):

FILE: mps_youtube/commands/lastfm.py
  function init_network (line 14) | def init_network(verbose=True):
  function scrobble_track (line 43) | def scrobble_track(artist, album, track):
  function set_now_playing (line 54) | def set_now_playing(artist, track):

FILE: mps_youtube/commands/local_playlist.py
  function playlist_remove (line 11) | def playlist_remove(name):
  function playlist_add (line 30) | def playlist_add(nums, playlist):
  function playlist_rename_idx (line 53) | def playlist_rename_idx(_id, name):
  function playlist_rename (line 60) | def playlist_rename(playlists_):
  function add_rm_all (line 80) | def add_rm_all(action):
  function save_last (line 97) | def save_last():
  function open_save_view (line 128) | def open_save_view(action, name):
  function open_view_bynum (line 169) | def open_view_bynum(action, num):
  function ls (line 177) | def ls():
  function vp (line 190) | def vp():

FILE: mps_youtube/commands/misc.py
  function clearcache (line 32) | def clearcache():
  function show_help (line 41) | def show_help(choice):
  function quits (line 48) | def quits(showlogo=True):
  function _format_comment (line 78) | def _format_comment(n, qnt, author_name, published_date, content, reply=...
  function _fetch_commentreplies (line 86) | def _fetch_commentreplies(parentid):
  function fetch_comments (line 93) | def fetch_comments(item):
  function comments (line 138) | def comments(number):
  function clipcopy_video (line 150) | def clipcopy_video(num):
  function clipcopy_stream (line 185) | def clipcopy_stream(num):
  function video_info (line 217) | def video_info(num):
  function stream_info (line 283) | def stream_info(num):
  function view_history (line 307) | def view_history(duplicates=True):
  function recent_history (line 334) | def recent_history():
  function clear_history (line 340) | def clear_history():

FILE: mps_youtube/commands/play.py
  function play_loaded (line 13) | def play_loaded():
  function play_pl (line 19) | def play_pl(name):
  function play (line 42) | def play(pre, choice, post=""):
  function play_all (line 125) | def play_all(pre, choice, post=""):
  function play_url (line 132) | def play_url(url: str, override: T.Any):
  function browser_play (line 155) | def browser_play(number):

FILE: mps_youtube/commands/search.py
  function _display_search_results (line 34) | def _display_search_results(progtext, wdata, msg=None, failmsg=None):
  function token (line 58) | def token(page):
  function userdata_cached (line 107) | def userdata_cached(userterm):
  function cache_userdata (line 113) | def cache_userdata(userterm, username, channel_id):
  function channelfromname (line 125) | def channelfromname(user):
  function channelsearch (line 149) | def channelsearch(q_user):
  function usersearch (line 175) | def usersearch(q_user, identify='forUsername'):
  function usersearch_id (line 192) | def usersearch_id(user, channel_id, term):
  function related_search (line 223) | def related_search(vitem):
  function livestream_category_search (line 240) | def livestream_category_search(term):
  function search (line 277) | def search(term):
  function user_pls (line 308) | def user_pls(user):
  function pl_search (line 314) | def pl_search(term, page=0, splash=True, is_user=False):
  function get_pl_from_json (line 358) | def get_pl_from_json(pldata):
  function get_track_id_from_json (line 382) | def get_track_id_from_json(item):
  function get_tracks_from_json (line 398) | def get_tracks_from_json(jsons):
  function num_repr (line 456) | def num_repr(num):
  function user_more (line 479) | def user_more(num):
  function related (line 502) | def related(num):
  function mix (line 516) | def mix(num):
  function yt_url (line 535) | def yt_url(url: str, print_title: bool = False):
  function yt_url_file (line 582) | def yt_url_file(file_name):

FILE: mps_youtube/commands/songlist.py
  function paginatesongs (line 10) | def paginatesongs(func, page=0, splash=True, dumps=False,
  function plist (line 79) | def plist(parturl):
  function songlist_rm_add (line 99) | def songlist_rm_add(action, songrange):
  function songlist_mv_sw (line 134) | def songlist_mv_sw(action, a, b):
  function nextprev (line 150) | def nextprev(np, page=None):
  function dump (line 190) | def dump(un):
  function shuffle_fn (line 205) | def shuffle_fn():
  function shuffle_playlist (line 212) | def shuffle_playlist():
  function reverse_songs (line 223) | def reverse_songs():
  function reverse_songs_range (line 231) | def reverse_songs_range(lower, upper):
  function reverse_playlist (line 242) | def reverse_playlist():

FILE: mps_youtube/commands/spotify_playlist.py
  function generate_credentials (line 21) | def generate_credentials():
  function grab_playlist (line 29) | def grab_playlist(spotify, playlist):
  function show_message (line 61) | def show_message(message, col=c.r, update=False):
  function _best_song_match (line 70) | def _best_song_match(songs, title, duration, titleweight, durationweight):
  function _match_tracks (line 122) | def _match_tracks(tracks):
  function search_user (line 161) | def search_user(term):
  function search_playlist (line 214) | def search_playlist(term, spotify=None):

FILE: mps_youtube/config.py
  class ConfigItem (line 22) | class ConfigItem:
    method __init__ (line 26) | def __init__(self, name, value, minval=None, maxval=None, check_fn=None,
    method get (line 45) | def get(self):
    method display (line 53) | def display(self):
    method display_temp (line 58) | def display_temp(self):
    method display_helper (line 62) | def display_helper(self, retval):
    method set (line 71) | def set(self, value, is_temp=False):
  function set_save (line 168) | def set_save(self, value, is_temp):
  function check_console_width (line 176) | def check_console_width(val):
  function check_ddir (line 202) | def check_ddir(d):
  function check_win_pos (line 214) | def check_win_pos(pos):
  function check_win_size (line 233) | def check_win_size(size):
  function check_encoder (line 249) | def check_encoder(option):
  function check_player (line 264) | def check_player(player):
  function check_lastfm_password (line 293) | def check_lastfm_password(password):
  class _Config (line 301) | class _Config:
    method __getitem__ (line 353) | def __getitem__(self, key):
    method __getattr__ (line 360) | def __getattr__(self, name):
    method __iter__ (line 368) | def __iter__(self):
    method save (line 371) | def save(self):
    method convert_old_cf_to_json (line 380) | def convert_old_cf_to_json(self):
    method load (line 392) | def load(self):

FILE: mps_youtube/content.py
  class Content (line 18) | class Content:
  class PaginatedContent (line 22) | class PaginatedContent(Content):
    method getPage (line 23) | def getPage(self, page):
    method numPages (line 26) | def numPages(self):
  class LineContent (line 30) | class LineContent(PaginatedContent):
    method getPage (line 31) | def getPage(self, page):
    method numPages (line 37) | def numPages(self):
    method get_text (line 40) | def get_text(self, s, e):
    method get_count (line 43) | def get_count(self):
  class StringContent (line 47) | class StringContent(LineContent):
    method __init__ (line 48) | def __init__(self, string):
    method get_text (line 51) | def get_text(self, s, e):
    method get_count (line 54) | def get_count(self):
  function page_msg (line 60) | def page_msg(page=0):
  function generate_songlist_display (line 77) | def generate_songlist_display(song=False, zeromsg=None):
  function generate_playlist_display (line 141) | def generate_playlist_display():
  function _get_user_columns (line 168) | def _get_user_columns():
  function logo (line 205) | def logo(col=None, version=""):
  function playlists_display (line 231) | def playlists_display():
  function qrcode_display (line 253) | def qrcode_display(url):
  function get_last_query (line 263) | def get_last_query():

FILE: mps_youtube/contentquery.py
  class ContentQuery (line 12) | class ContentQuery:
    method __init__ (line 24) | def __init__(self, datatype, api, query):
    method __getitem__ (line 36) | def __getitem__(self, iid):
    method count (line 46) | def count(self):
    method __len__ (line 50) | def __len__(self):
    method _perform_api_call (line 53) | def _perform_api_call(self):

FILE: mps_youtube/description_parser.py
  function calculate_certainty (line 8) | def calculate_certainty(line):
  function has_artist (line 27) | def has_artist(text):
  function strip_string (line 33) | def strip_string(text, single=False):
  function long_substr (line 55) | def long_substr(data):
  function is_substr (line 66) | def is_substr(find, data):
  function artist_from_title (line 76) | def artist_from_title(title):
  function parse (line 117) | def parse(text, title="Unknown"):

FILE: mps_youtube/helptext.py
  function helptext (line 14) | def helptext():
  function get_help (line 334) | def get_help(choice):
  function get_changelog (line 409) | def get_changelog():
  function get_changelog_local (line 419) | def get_changelog_local():
  function check_tor (line 427) | def check_tor():

FILE: mps_youtube/history.py
  function add (line 10) | def add(song):
  function load (line 20) | def load():
  function save (line 33) | def save():
  function _convert_to_m3u (line 44) | def _convert_to_m3u():

FILE: mps_youtube/init.py
  function init (line 33) | def init():
  function _init_transcode (line 107) | def _init_transcode():
  function _init_readline (line 208) | def _init_readline():
  function _process_cl_args (line 221) | def _process_cl_args():
  function _get_version_info (line 267) | def _get_version_info():

FILE: mps_youtube/listview/__init__.py
  class ListView (line 14) | class ListView(content.PaginatedContent):
    method __init__ (line 47) | def __init__(self, columns, objects, function_call=None):
    method numPages (line 63) | def numPages(self):
    method getPage (line 67) | def getPage(self, page):
    method _page_slice (line 71) | def _page_slice(self):
    method content (line 75) | def content(self):
    method _play (line 141) | def _play(self, _, choice, __):  # pre, choice, post
    method views_per_page (line 159) | def views_per_page(self):

FILE: mps_youtube/listview/base.py
  class ListViewItem (line 1) | class ListViewItem:
    method __init__ (line 7) | def __init__(self, data):
    method __getattr__ (line 10) | def __getattr__(self, key):
    method length (line 13) | def length(self, _=0):

FILE: mps_youtube/listview/livestream.py
  class ListLiveStream (line 5) | class ListLiveStream(ListViewItem):
    method ytid (line 8) | def ytid(self, lngt=10):
    method ret (line 12) | def ret(self):
    method title (line 16) | def title(self, lngt=10):
    method description (line 19) | def description(self, lngt=10):
    method return_field (line 24) | def return_field():

FILE: mps_youtube/listview/songtitle.py
  class ListSongtitle (line 5) | class ListSongtitle(ListViewItem):
    method __init__ (line 12) | def __init__(self, data, certainty=1.0):
    method artist (line 17) | def artist(self, l=10):
    method title (line 21) | def title(self, l=10):
    method checked (line 25) | def checked(self, l=10):
    method certainty (line 29) | def certainty(self):
    method is_checked (line 33) | def is_checked(self):
    method toggle (line 37) | def toggle(self):
    method ret (line 41) | def ret(self):
    method return_field (line 46) | def return_field():

FILE: mps_youtube/listview/user.py
  class ListUser (line 4) | class ListUser(ListViewItem):
    method id (line 8) | def id(self, length=0):
    method name (line 12) | def name(self, length=10):
    method description (line 16) | def description(self, length=10):
    method kind (line 20) | def kind(self, length=10):
    method ret (line 26) | def ret(self):
    method return_field (line 31) | def return_field():

FILE: mps_youtube/main.py
  function matchfunction (line 56) | def matchfunction(func, regex, userinput):
  function prompt_for_exit (line 102) | def prompt_for_exit():
  function main (line 117) | def main():

FILE: mps_youtube/mpris.py
  class Mpris2Controller (line 44) | class Mpris2Controller:
    method __init__ (line 50) | def __init__(self):
    method release (line 62) | def release(self):
    method acquire (line 72) | def acquire(self):
    method run (line 79) | def run(self, connection):
    method listenstatus (line 89) | def listenstatus(self, conn):
    method _acquire_bus (line 111) | def _acquire_bus(self):
    method _add_interfaces (line 121) | def _add_interfaces(self):
    method _run_main_loop (line 127) | def _run_main_loop(self):
  class Mpris2MediaPlayer (line 138) | class Mpris2MediaPlayer(dbus.service.Object):
    method __init__ (line 147) | def __init__(self, bus):
    method bindmpv (line 193) | def bindmpv(self, sockpath):
    method bindfifo (line 233) | def bindfifo(self, fifopath, mpv=False):
    method setproperty (line 246) | def setproperty(self, name: str, val: T.Optional[T.Any]):
    method _sendcommand (line 322) | def _sendcommand(self, command):
    method Raise (line 345) | def Raise(self):
    method Quit (line 353) | def Quit(self):
    method Next (line 364) | def Next(self):
    method Previous (line 371) | def Previous(self):
    method Pause (line 378) | def Pause(self):
    method PlayPause (line 390) | def PlayPause(self):
    method Stop (line 401) | def Stop(self):
    method Play (line 408) | def Play(self):
    method Seek (line 419) | def Seek(self, offset):
    method SetPosition (line 430) | def SetPosition(self, track_id, position):
    method OpenUri (line 445) | def OpenUri(self, uri):
    method Seeked (line 455) | def Seeked(self, position):
    method Get (line 471) | def Get(self, interface_name, property_name):
    method GetAll (line 479) | def GetAll(self, interface_name):
    method Set (line 496) | def Set(self, interface_name, property_name, new_value):
    method PropertiesChanged (line 514) | def PropertiesChanged(self, interface_name, changed_properties,
  class MprisConnection (line 523) | class MprisConnection(object):
    method __init__ (line 529) | def __init__(self, connection):
    method send (line 533) | def send(self, obj):
  function main (line 545) | def main(connection):

FILE: mps_youtube/pafy.py
  class MyLogger (line 12) | class MyLogger:
    method debug (line 13) | def debug(self, msg):
    method info (line 21) | def info(self, msg):
    method warning (line 24) | def warning(self, msg):
    method error (line 27) | def error(self, msg):
  function get_video_streams (line 31) | def get_video_streams(ytid):
  function download_video (line 41) | def download_video(ytid, folder, audio_only=False):
  function search_videos (line 62) | def search_videos(query, pages):
  function channel_search (line 76) | def channel_search(query):
  function playlist_search (line 85) | def playlist_search(query):
  function get_playlist (line 94) | def get_playlist(playlist_id):
  function get_video_title_suggestions (line 105) | def get_video_title_suggestions(query):
  function channel_id_from_name (line 110) | def channel_id_from_name(query):
  function all_videos_from_channel (line 116) | def all_videos_from_channel(channel_id):
  function search_videos_from_channel (line 120) | def search_videos_from_channel(channel_id, query):
  function get_comments (line 124) | def get_comments(video_id):
  function get_video_info (line 128) | def get_video_info(video_id):
  function return_dislikes (line 136) | def return_dislikes(video_id):
  function extract_video_id (line 140) | def extract_video_id(url: str) -> str:
  function all_playlists_from_channel (line 181) | def all_playlists_from_channel(channel_id):

FILE: mps_youtube/paths.py
  function get_default_ddir (line 6) | def get_default_ddir():
  function get_config_dir (line 41) | def get_config_dir():

FILE: mps_youtube/player.py
  class BasePlayer (line 19) | class BasePlayer:
    method PlaybackStatus (line 24) | def PlaybackStatus(self):
    method PlaybackStatus (line 28) | def PlaybackStatus(self, value):
    method play (line 36) | def play(self, songlist, shuffle=False, repeat=False, override=False):
    method next (line 106) | def next(self):
    method previous (line 109) | def previous(self):
    method stop (line 112) | def stop(self):
    method seek (line 116) | def seek(self):
    method _playsong (line 119) | def _playsong(self, failcount=0, softrepeat=False):
    method _launch_player (line 143) | def _launch_player(self):
    method send_metadata_mpris (line 147) | def send_metadata_mpris(self):
    method _playback_progress (line 163) | def _playback_progress(self, idx, allsongs, repeat=False):
    method make_status_line (line 202) | def make_status_line(self, elapsed_s, prefix, songlength=0, volume=None):
    method _make_status_line (line 210) | def _make_status_line(self, elapsed_s, prefix, songlength=0, volume=No...
  class CmdPlayer (line 246) | class CmdPlayer(BasePlayer):
    method next (line 248) | def next(self):
    method previous (line 255) | def previous(self):
    method stop (line 262) | def stop(self):
    method terminate_process (line 266) | def terminate_process(self):
    method _generate_real_playerargs (line 272) | def _generate_real_playerargs(self):
    method clean_up (line 275) | def clean_up(self):
    method launch_player (line 278) | def launch_player(self, cmd):
    method _help (line 281) | def _help(self, short=True):
    method _launch_player (line 284) | def _launch_player(self):
  function stream_details (line 314) | def stream_details(song, failcount=0, override=False, softrepeat=False):

FILE: mps_youtube/players/GenericPlayer.py
  class GenericPlayer (line 17) | class GenericPlayer(CmdPlayer):
    method __init__ (line 18) | def __init__(self, player):
    method _generate_real_playerargs (line 21) | def _generate_real_playerargs(self):
    method clean_up (line 34) | def clean_up(self):
    method launch_player (line 40) | def launch_player(self, cmd):
    method _help (line 54) | def _help(self, short=True):

FILE: mps_youtube/players/mplayer.py
  class mplayer (line 15) | class mplayer(CmdPlayer):
    method __init__ (line 16) | def __init__(self, player):
    method _generate_real_playerargs (line 20) | def _generate_real_playerargs(self):
    method clean_up (line 75) | def clean_up(self):
    method launch_player (line 79) | def launch_player(self, cmd):
    method _player_status (line 114) | def _player_status(self, prefix, songlength=0):
    method _help (line 173) | def _help(self, short=True):
  function _get_input_file (line 194) | def _get_input_file():
  function _get_mplayer_version (line 230) | def _get_mplayer_version(exename: str) -> T.Union[int, T.Tuple[int, ...]]:

FILE: mps_youtube/players/mpv.py
  class mpv (line 17) | class mpv(CmdPlayer):
    method __init__ (line 18) | def __init__(self, player):
    method _generate_real_playerargs (line 33) | def _generate_real_playerargs(self):
    method clean_up (line 103) | def clean_up(self):
    method launch_player (line 113) | def launch_player(self, cmd):
    method _player_status (line 150) | def _player_status(self, prefix, songlength=0):
    method _help (line 257) | def _help(self, short=True):
  function _get_input_file (line 278) | def _get_input_file():
  function _get_mpv_version (line 314) | def _get_mpv_version(exename):

FILE: mps_youtube/players/vlc.py
  class vlc (line 8) | class vlc(CmdPlayer):
    method __init__ (line 9) | def __init__(self, player):
    method _generate_real_playerargs (line 12) | def _generate_real_playerargs(self):
    method clean_up (line 28) | def clean_up(self):
    method launch_player (line 31) | def launch_player(self, cmd):
    method _help (line 37) | def _help(self, short=True):
    method _kill_instance (line 40) | def _kill_instance(self):

FILE: mps_youtube/playlist.py
  class Playlist (line 1) | class Playlist:
    method __init__ (line 5) | def __init__(self, name=None, songs=None):
    method __len__ (line 10) | def __len__(self):
    method __getitem__ (line 14) | def __getitem__(self, sliced):
    method __setitem__ (line 17) | def __setitem__(self, position, item):
    method __iter__ (line 20) | def __iter__(self):
    method duration (line 25) | def duration(self):
  class Video (line 34) | class Video:
    method __init__ (line 38) | def __init__(self, ytid, title, length):

FILE: mps_youtube/playlists.py
  function save (line 9) | def save():
  function load (line 21) | def load():
  function delete (line 53) | def delete(name):
  function read_m3u (line 59) | def read_m3u(m3u):
  function _convert_playlist_to_v2 (line 92) | def _convert_playlist_to_v2():
  function _convert_playlist_to_m3u (line 133) | def _convert_playlist_to_m3u():

FILE: mps_youtube/screen.py
  function update (line 11) | def update(fill_blank=True):
  function clear (line 34) | def clear():
  function reset_terminal (line 42) | def reset_terminal():
  function writestatus (line 48) | def writestatus(text, mute=False):
  function _writeline (line 54) | def _writeline(text):
  function msgexit (line 67) | def msgexit(msg, code=0):

FILE: mps_youtube/streams.py
  function prune (line 8) | def prune():
  function get (line 38) | def get(vid, force=False, callback=None, threeD=False):
  function select (line 86) | def select(slist, q=0, audio=False, m4a_ok=True, maxres=None):
  function get_size (line 139) | def get_size(ytid, url, preloading=False):
  function _get_content_length (line 157) | def _get_content_length(url, preloading=False):
  function preload (line 167) | def preload(song, delay=2, override=False):
  function _preload (line 175) | def _preload(song, delay, override):

FILE: mps_youtube/terminalsize.py
  function get_terminal_size (line 14) | def get_terminal_size():
  function _get_terminal_size_windows (line 45) | def _get_terminal_size_windows():
  function _get_terminal_size_tput (line 70) | def _get_terminal_size_tput():
  function _get_terminal_size_linux (line 82) | def _get_terminal_size_linux():

FILE: mps_youtube/test/test_main.py
  class TestMain (line 8) | class TestMain(unittest.TestCase):
    method test_fmt_time (line 9) | def test_fmt_time(self):
    method test_num_repr (line 18) | def test_num_repr(self):

FILE: mps_youtube/test/test_mpris.py
  function test_mprsi2controller_init (line 11) | def test_mprsi2controller_init():
  function test_mpris2mediaplayer_init (line 15) | def test_mpris2mediaplayer_init():
  function test_mpris2mediaplayer_set_property_time_pos (line 72) | def test_mpris2mediaplayer_set_property_time_pos(val):
  function test_mpris2mediaplayer_set_property_time_pos_seeked (line 98) | def test_mpris2mediaplayer_set_property_time_pos_seeked(val1, val2):

FILE: mps_youtube/test/test_players_mplayer.py
  function test_get_mplayer_version_no_mplayer (line 17) | def test_get_mplayer_version_no_mplayer(exename, exp_err):
  function test_get_mplayer_version_invalid_input (line 22) | def test_get_mplayer_version_invalid_input():
  function test_get_mplayer_version (line 38) | def test_get_mplayer_version(output, exp_res):

FILE: mps_youtube/test/test_util.py
  function test_uea_pad (line 15) | def test_uea_pad(num, t, exp_res):

FILE: mps_youtube/util.py
  class IterSlicer (line 29) | class IterSlicer():
    method __init__ (line 33) | def __init__(self, iterable, length=None):
    method __getitem__ (line 43) | def __getitem__(self, sliced):
    method __len__ (line 59) | def __len__(self):
  function has_exefile (line 65) | def has_exefile(filename):
  function dbg (line 88) | def dbg(*args):
  function utf8_replace (line 94) | def utf8_replace(txt):
  function xenc (line 109) | def xenc(stuff):
  function xprint (line 114) | def xprint(stuff, end=None):
  function mswinfn (line 119) | def mswinfn(filename):
  function sanitize_filename (line 128) | def sanitize_filename(filename, ignore_slashes=False):
  function set_window_title (line 141) | def set_window_title(title):
  function list_update (line 149) | def list_update(item, lst, remove=False):
  function get_near_name (line 158) | def get_near_name(begin, items):
  function F (line 166) | def F(key, nb=0, na=0, textlib=None):
  function get_pafy (line 192) | def get_pafy(item, force=False, callback=None):
  function getxy (line 239) | def getxy():
  function fmt_time (line 259) | def fmt_time(seconds):
  function correct_truncate (line 275) | def correct_truncate(text, max_len):
  function uea_pad (line 291) | def uea_pad(num, t, direction="<", notrunc=False):
  function real_len (line 324) | def real_len(u, alt=False):
  function yt_datetime (line 343) | def yt_datetime(yt_date_time):
  function yt_datetime_local (line 355) | def yt_datetime_local(yt_date_time):
  function utc2local (line 366) | def utc2local(utc):
  function parse_multi (line 370) | def parse_multi(choice, end=None):
  function _bi_range (line 406) | def _bi_range(start, end):
  function is_known_player (line 423) | def is_known_player(player):
  function load_player_info (line 438) | def load_player_info(player):
  function fetch_songs (line 456) | def fetch_songs(text, title="Unknown"):
  function number_string_to_list (line 460) | def number_string_to_list(text):
  function _get_mpv_version (line 476) | def _get_mpv_version(exename):
  function _get_mplayer_version (line 493) | def _get_mplayer_version(exename):
  function _get_metadata (line 511) | def _get_metadata(song_title):
  function _get_metadata_from_lastfm (line 540) | def _get_metadata_from_lastfm(artist, track):
  function assign_player (line 563) | def assign_player(player):
  class CommandCompleter (line 581) | class CommandCompleter:
    method __init__ (line 585) | def __init__(self):
    method complete_command (line 589) | def complete_command(self, text, state):
    method add_cmd (line 595) | def add_cmd(self, val):
  function parse_video_length (line 599) | def parse_video_length(duration):
Condensed preview — 102 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (400K chars).
[
  {
    "path": ".gitignore",
    "chars": 148,
    "preview": "*.py[cod]\notherstuff/\npafy\nvi.py\nMANIFEST\n.dev\n.vscode\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\ntags\n.e"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 22221,
    "preview": "# Changelog\n\n<!--next-version-placeholder-->\n\n## v2.9.2 (2023-01-26)\n### Fix\n* Remove pyreadline dependency (#105) ([#10"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 947,
    "preview": "# Contributing for yewtube\n\nContributions are very much appreciated!\n\n* Pull requests should be based on and submitted t"
  },
  {
    "path": "Dockerfile",
    "chars": 758,
    "preview": "FROM python:3-stretch\n\nLABEL maintainer=\"Justin Garrison <justinleegarrison@gmail.com>\" \\\n    org.label-schema.schema-ve"
  },
  {
    "path": "ISSUE_TEMPLATE.md",
    "chars": 707,
    "preview": "<!--- Provide a general summary of the issue in the Title above -->\n\n## Issue / Suggestion\n<!--- If you're describing a "
  },
  {
    "path": "LICENSE",
    "chars": 35127,
    "preview": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation,"
  },
  {
    "path": "MANIFEST.in",
    "chars": 83,
    "preview": "include mps-youtube.desktop\ninclude LICENSE\ninclude README.md\ninclude CHANGELOG.md\n"
  },
  {
    "path": "README.md",
    "chars": 5902,
    "preview": "\n![](https://img.shields.io/pypi/v/yewtube.svg)  ![](https://img.shields.io/pypi/wheel/yewtube.svg)\n\n<pre>\n             "
  },
  {
    "path": "RELEASING.md",
    "chars": 1849,
    "preview": "Release process for pafy and mps-youtube\n========================================\n\nLooking at the commits and Github rel"
  },
  {
    "path": "_config.yml",
    "chars": 26,
    "preview": "theme: jekyll-theme-hacker"
  },
  {
    "path": "doc/conf.py",
    "chars": 11602,
    "preview": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# mps_youtube documentation build configuration file, created by\n# sphi"
  },
  {
    "path": "doc/index.rst",
    "chars": 424,
    "preview": ".. mps_youtube documentation master file, created by\n   sphinx-quickstart on Mon Apr 18 17:35:31 2016.\n   You can adapt "
  },
  {
    "path": "doc/modules.rst",
    "chars": 70,
    "preview": "mps_youtube\n===========\n\n.. toctree::\n   :maxdepth: 4\n\n   mps_youtube\n"
  },
  {
    "path": "doc/mps_youtube.c.rst",
    "chars": 130,
    "preview": "mps_youtube.c module\n====================\n\n.. automodule:: mps_youtube.c\n    :members:\n    :undoc-members:\n    :show-inh"
  },
  {
    "path": "doc/mps_youtube.cache.rst",
    "chars": 142,
    "preview": "mps_youtube.cache module\n========================\n\n.. automodule:: mps_youtube.cache\n    :members:\n    :undoc-members:\n "
  },
  {
    "path": "doc/mps_youtube.commands.album_search.rst",
    "chars": 190,
    "preview": "mps_youtube.commands.album_search module\n========================================\n\n.. automodule:: mps_youtube.commands."
  },
  {
    "path": "doc/mps_youtube.commands.config.rst",
    "chars": 172,
    "preview": "mps_youtube.commands.config module\n==================================\n\n.. automodule:: mps_youtube.commands.config\n    :"
  },
  {
    "path": "doc/mps_youtube.commands.download.rst",
    "chars": 178,
    "preview": "mps_youtube.commands.download module\n====================================\n\n.. automodule:: mps_youtube.commands.download"
  },
  {
    "path": "doc/mps_youtube.commands.local_playlist.rst",
    "chars": 196,
    "preview": "mps_youtube.commands.local_playlist module\n==========================================\n\n.. automodule:: mps_youtube.comma"
  },
  {
    "path": "doc/mps_youtube.commands.misc.rst",
    "chars": 166,
    "preview": "mps_youtube.commands.misc module\n================================\n\n.. automodule:: mps_youtube.commands.misc\n    :member"
  },
  {
    "path": "doc/mps_youtube.commands.play.rst",
    "chars": 166,
    "preview": "mps_youtube.commands.play module\n================================\n\n.. automodule:: mps_youtube.commands.play\n    :member"
  },
  {
    "path": "doc/mps_youtube.commands.rst",
    "chars": 486,
    "preview": "mps_youtube.commands package\n============================\n\nSubmodules\n----------\n\n.. toctree::\n\n   mps_youtube.commands."
  },
  {
    "path": "doc/mps_youtube.commands.search.rst",
    "chars": 172,
    "preview": "mps_youtube.commands.search module\n==================================\n\n.. automodule:: mps_youtube.commands.search\n    :"
  },
  {
    "path": "doc/mps_youtube.commands.songlist.rst",
    "chars": 178,
    "preview": "mps_youtube.commands.songlist module\n====================================\n\n.. automodule:: mps_youtube.commands.songlist"
  },
  {
    "path": "doc/mps_youtube.config.rst",
    "chars": 145,
    "preview": "mps_youtube.config module\n=========================\n\n.. automodule:: mps_youtube.config\n    :members:\n    :undoc-members"
  },
  {
    "path": "doc/mps_youtube.content.rst",
    "chars": 148,
    "preview": "mps_youtube.content module\n==========================\n\n.. automodule:: mps_youtube.content\n    :members:\n    :undoc-memb"
  },
  {
    "path": "doc/mps_youtube.g.rst",
    "chars": 130,
    "preview": "mps_youtube.g module\n====================\n\n.. automodule:: mps_youtube.g\n    :members:\n    :undoc-members:\n    :show-inh"
  },
  {
    "path": "doc/mps_youtube.helptext.rst",
    "chars": 151,
    "preview": "mps_youtube.helptext module\n===========================\n\n.. automodule:: mps_youtube.helptext\n    :members:\n    :undoc-m"
  },
  {
    "path": "doc/mps_youtube.history.rst",
    "chars": 148,
    "preview": "mps_youtube.history module\n==========================\n\n.. automodule:: mps_youtube.history\n    :members:\n    :undoc-memb"
  },
  {
    "path": "doc/mps_youtube.init.rst",
    "chars": 139,
    "preview": "mps_youtube.init module\n=======================\n\n.. automodule:: mps_youtube.init\n    :members:\n    :undoc-members:\n    "
  },
  {
    "path": "doc/mps_youtube.main.rst",
    "chars": 139,
    "preview": "mps_youtube.main module\n=======================\n\n.. automodule:: mps_youtube.main\n    :members:\n    :undoc-members:\n    "
  },
  {
    "path": "doc/mps_youtube.mpris.rst",
    "chars": 142,
    "preview": "mps_youtube.mpris module\n========================\n\n.. automodule:: mps_youtube.mpris\n    :members:\n    :undoc-members:\n "
  },
  {
    "path": "doc/mps_youtube.paths.rst",
    "chars": 142,
    "preview": "mps_youtube.paths module\n========================\n\n.. automodule:: mps_youtube.paths\n    :members:\n    :undoc-members:\n "
  },
  {
    "path": "doc/mps_youtube.player.rst",
    "chars": 145,
    "preview": "mps_youtube.player module\n=========================\n\n.. automodule:: mps_youtube.player\n    :members:\n    :undoc-members"
  },
  {
    "path": "doc/mps_youtube.playlist.rst",
    "chars": 151,
    "preview": "mps_youtube.playlist module\n===========================\n\n.. automodule:: mps_youtube.playlist\n    :members:\n    :undoc-m"
  },
  {
    "path": "doc/mps_youtube.playlists.rst",
    "chars": 154,
    "preview": "mps_youtube.playlists module\n============================\n\n.. automodule:: mps_youtube.playlists\n    :members:\n    :undo"
  },
  {
    "path": "doc/mps_youtube.rst",
    "chars": 655,
    "preview": "mps_youtube package\n===================\n\nSubpackages\n-----------\n\n.. toctree::\n\n    mps_youtube.commands\n\nSubmodules\n---"
  },
  {
    "path": "doc/mps_youtube.screen.rst",
    "chars": 145,
    "preview": "mps_youtube.screen module\n=========================\n\n.. automodule:: mps_youtube.screen\n    :members:\n    :undoc-members"
  },
  {
    "path": "doc/mps_youtube.streams.rst",
    "chars": 148,
    "preview": "mps_youtube.streams module\n==========================\n\n.. automodule:: mps_youtube.streams\n    :members:\n    :undoc-memb"
  },
  {
    "path": "doc/mps_youtube.terminalsize.rst",
    "chars": 163,
    "preview": "mps_youtube.terminalsize module\n===============================\n\n.. automodule:: mps_youtube.terminalsize\n    :members:\n"
  },
  {
    "path": "doc/mps_youtube.util.rst",
    "chars": 139,
    "preview": "mps_youtube.util module\n=======================\n\n.. automodule:: mps_youtube.util\n    :members:\n    :undoc-members:\n    "
  },
  {
    "path": "docs/changelog.md",
    "chars": 22,
    "preview": "--8<-- \"CHANGELOG.md\"\n"
  },
  {
    "path": "docs/contributing.md",
    "chars": 25,
    "preview": "--8<-- \"CONTRIBUTING.md\"\n"
  },
  {
    "path": "docs/css/mkdocstrings.css",
    "chars": 689,
    "preview": "/* Indentation. */\ndiv.doc-contents:not(.first) {\n  padding-left: 25px;\n  border-left: 4px solid rgba(230, 230, 230);\n  "
  },
  {
    "path": "docs/gen_ref_nav.py",
    "chars": 1015,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Generate the code reference pages and navigation.\"\"\"\n\nfrom pathlib impo"
  },
  {
    "path": "docs/index.md",
    "chars": 19,
    "preview": "--8<-- \"README.md\"\n"
  },
  {
    "path": "docs/license.md",
    "chars": 25,
    "preview": "```\n--8<-- \"LICENSE\"\n```\n"
  },
  {
    "path": "mkdocs.yml",
    "chars": 906,
    "preview": "site_name: Yewtube\nsite_description: Terminal based YouTube player and downloader.\nsite_url: https://iamtalhaasghar.gith"
  },
  {
    "path": "mps_youtube/__init__.py",
    "chars": 275,
    "preview": "from pip._vendor import pkg_resources\n\n__version__ = next((p.version for p in pkg_resources.working_set if p.project_nam"
  },
  {
    "path": "mps_youtube/c.py",
    "chars": 714,
    "preview": "\"\"\" Module for holding colour code values. \"\"\"\n\nimport os\nimport re\nimport sys\n\n\nif sys.stdout.isatty():\n    white = \"\\x"
  },
  {
    "path": "mps_youtube/cache.py",
    "chars": 1381,
    "preview": "import os\nimport pickle\n\n\nfrom . import g, c, streams\nfrom .util import dbg\n\n\n# Updated every time incompatible changes "
  },
  {
    "path": "mps_youtube/commands/__init__.py",
    "chars": 1259,
    "preview": "import collections\nimport re\n\nfrom .. import g\nfrom ..main import completer\n\nCommand = collections.namedtuple('Command',"
  },
  {
    "path": "mps_youtube/commands/album_search.py",
    "chars": 9719,
    "preview": "import re\nimport time\nimport difflib\nfrom urllib.request import build_opener\nfrom urllib.error import HTTPError, URLErro"
  },
  {
    "path": "mps_youtube/commands/config.py",
    "chars": 3110,
    "preview": "from .. import g, c, config, util\nfrom . import command\n\n\n@command(r'set|showconfig', 'set', 'showconfig')\ndef showconfi"
  },
  {
    "path": "mps_youtube/commands/download.py",
    "chars": 17514,
    "preview": "import os\nimport re\nimport sys\nimport time\nimport shlex\nimport random\nimport subprocess\nfrom urllib.request import urlop"
  },
  {
    "path": "mps_youtube/commands/generate_playlist.py",
    "chars": 3968,
    "preview": "\"\"\"\n    Playlist Generation\n\"\"\"\nfrom os import path\nfrom random import choice\nimport string\n\nfrom .. import content, g, "
  },
  {
    "path": "mps_youtube/commands/lastfm.py",
    "chars": 2192,
    "preview": "import time\nimport datetime\n\ntry:\n    import pylast\n    has_pylast = True\nexcept ImportError:\n    has_pylast = False\n\nfr"
  },
  {
    "path": "mps_youtube/commands/local_playlist.py",
    "chars": 6435,
    "preview": "import re\n\nfrom .. import g, c, playlists, content, util\nfrom ..playlist import Playlist, Video\nfrom . import command, W"
  },
  {
    "path": "mps_youtube/commands/misc.py",
    "chars": 11988,
    "preview": "import re\nfrom datetime import datetime, timedelta\nimport socket\nimport traceback\nfrom urllib.request import urlopen\nfro"
  },
  {
    "path": "mps_youtube/commands/play.py",
    "chars": 5519,
    "preview": "import random\nimport sys\nimport typing as T\nimport webbrowser\nfrom urllib.error import HTTPError, URLError\n\nfrom .. impo"
  },
  {
    "path": "mps_youtube/commands/search.py",
    "chars": 19769,
    "preview": "import base64\nimport json\nimport logging\nimport math\nimport re\nimport typing as T\nfrom argparse import ArgumentParser\nfr"
  },
  {
    "path": "mps_youtube/commands/songlist.py",
    "chars": 7877,
    "preview": "import math\nimport random\n\n\nfrom .. import g, c, screen, streams, content, util, pafy\nfrom ..playlist import Video\nfrom "
  },
  {
    "path": "mps_youtube/commands/spotify_playlist.py",
    "chars": 9324,
    "preview": "import re\nimport time\nimport difflib\n\ntry:\n    # pylint: disable=F0401\n    import spotipy\n    import spotipy.oauth2 as o"
  },
  {
    "path": "mps_youtube/config.py",
    "chars": 14401,
    "preview": "import os\nimport re\nimport sys\nimport copy\nimport pickle\nimport json\nfrom urllib.request import urlopen\nfrom urllib.erro"
  },
  {
    "path": "mps_youtube/content.py",
    "chars": 9173,
    "preview": "import math\nimport copy\nimport random\n\n\nfrom . import g, c, config\nfrom .util import getxy, fmt_time, uea_pad, yt_dateti"
  },
  {
    "path": "mps_youtube/contentquery.py",
    "chars": 1956,
    "preview": "\"\"\"\n    ContentQuery is an abstraction layer between the the pafy.call_gdata\n    and the listViews.\n\n    It lets you tre"
  },
  {
    "path": "mps_youtube/description_parser.py",
    "chars": 5016,
    "preview": "\"\"\"\n    Module for trying to parse and retrieve song data from descriptions\n\"\"\"\nimport re\nimport random\n\n\ndef calculate_"
  },
  {
    "path": "mps_youtube/g.py",
    "chars": 6892,
    "preview": "\"\"\" Module for holding globals that are needed throught mps-youtube. \"\"\"\n\nimport collections\nimport os\nimport sys\n\nfrom "
  },
  {
    "path": "mps_youtube/helptext.py",
    "chars": 19115,
    "preview": "\"\"\"\n    Holds all help text\n\"\"\"\nimport pathlib\nimport re\nimport socket\nfrom urllib.error import HTTPError, URLError\nfrom"
  },
  {
    "path": "mps_youtube/history.py",
    "chars": 1409,
    "preview": "import os\nimport pickle\n\nfrom . import g, c\nfrom .util import dbg\nfrom .playlist import Playlist\nfrom .playlists import "
  },
  {
    "path": "mps_youtube/init.py",
    "chars": 9175,
    "preview": "import argparse\nimport logging\nimport multiprocessing\nimport os\nimport platform\nimport re\nimport sys\nimport tempfile\n\ntr"
  },
  {
    "path": "mps_youtube/listview/__init__.py",
    "chars": 5676,
    "preview": "\"\"\"\n    DOCSTING COMES HERE\n\"\"\"\nimport re\nimport math\n\nfrom .. import c, g, util, content\nfrom .base import ListViewItem"
  },
  {
    "path": "mps_youtube/listview/base.py",
    "chars": 455,
    "preview": "class ListViewItem:\n    \"\"\" Base class for items\n        Used by Listview\n    \"\"\"\n    data = None\n\n    def __init__(self"
  },
  {
    "path": "mps_youtube/listview/livestream.py",
    "chars": 817,
    "preview": "from .base import ListViewItem\nfrom .. import util\n\n\nclass ListLiveStream(ListViewItem):\n    \"\"\" Class exposing necessar"
  },
  {
    "path": "mps_youtube/listview/songtitle.py",
    "chars": 1245,
    "preview": "from .base import ListViewItem\nfrom .. import util as u\n\n\nclass ListSongtitle(ListViewItem):\n    \"\"\" Describes a user\n  "
  },
  {
    "path": "mps_youtube/listview/user.py",
    "chars": 1030,
    "preview": "from .base import ListViewItem\nfrom .. import util as u\n\nclass ListUser(ListViewItem):\n    \"\"\" Describes a user\n    \"\"\"\n"
  },
  {
    "path": "mps_youtube/main.py",
    "chars": 5043,
    "preview": "\"\"\"\nmps-youtube.\n\nhttps://github.com/np1/mps-youtube\n\nCopyright (C) 2014, 2015 np1 and contributors\n\nThis program is fre"
  },
  {
    "path": "mps_youtube/mpris.py",
    "chars": 19026,
    "preview": "\"\"\"\nmps-youtube.\n\nhttps://github.com/np1/mps-youtube\n\nCopyright (C) 2014 nagev\n\nThis program is free software: you can r"
  },
  {
    "path": "mps_youtube/pafy.py",
    "chars": 5341,
    "preview": "import json\nimport os\nimport random\nimport re\nfrom urllib.parse import parse_qs, urlparse\n\nimport requests\nimport yt_dlp"
  },
  {
    "path": "mps_youtube/paths.py",
    "chars": 1563,
    "preview": "import os\n\nmswin = os.name == \"nt\"\n\n\ndef get_default_ddir():\n    \"\"\" Get system default Download directory, append mps d"
  },
  {
    "path": "mps_youtube/player.py",
    "chars": 12950,
    "preview": "import logging\nimport math\nimport os\nimport random\nimport shlex\nimport socket\nimport subprocess\nimport sys\nimport time\nf"
  },
  {
    "path": "mps_youtube/players/GenericPlayer.py",
    "chars": 1381,
    "preview": "import os\nimport subprocess\n\nfrom .. import config\n\nfrom ..player import CmdPlayer\n\n#\n# This class can be used as a temp"
  },
  {
    "path": "mps_youtube/players/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "mps_youtube/players/mplayer.py",
    "chars": 8608,
    "preview": "import os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nimport typing as T\n\nfrom .. import c, config, g, paths,"
  },
  {
    "path": "mps_youtube/players/mpv.py",
    "chars": 11354,
    "preview": "import json\nimport os\nimport re\nimport socket\nimport subprocess\nimport sys\nimport tempfile\nimport time\n\nfrom .. import c"
  },
  {
    "path": "mps_youtube/players/vlc.py",
    "chars": 1469,
    "preview": "import os\nimport subprocess\n\nfrom .. import config, g, util\nfrom ..player import CmdPlayer\n\n\nclass vlc(CmdPlayer):\n    d"
  },
  {
    "path": "mps_youtube/playlist.py",
    "chars": 1098,
    "preview": "class Playlist:\n\n    \"\"\" Representation of a playist, has list of songs. \"\"\"\n\n    def __init__(self, name=None, songs=No"
  },
  {
    "path": "mps_youtube/playlists.py",
    "chars": 5350,
    "preview": "import os\nimport sys\nimport pickle\n\nfrom . import g, c, screen, util, pafy\nfrom .playlist import Playlist, Video\n\n\ndef s"
  },
  {
    "path": "mps_youtube/screen.py",
    "chars": 1651,
    "preview": "import subprocess\nimport os\nimport sys\n\nfrom . import g, content, config, util\n\n\nmswin = os.name == \"nt\"\n\n\ndef update(fi"
  },
  {
    "path": "mps_youtube/streams.py",
    "chars": 7145,
    "preview": "import time\nimport threading\nfrom urllib.request import urlopen\nfrom . import pafy\nfrom . import g, c, screen, config, u"
  },
  {
    "path": "mps_youtube/terminalsize.py",
    "chars": 2867,
    "preview": "# https://gist.github.com/jtriley/1108174\n\n\"\"\" Terminal Size. \"\"\"\n\nimport os\nimport sys\nimport shlex\nimport shutil\nimpor"
  },
  {
    "path": "mps_youtube/test/test_main.py",
    "chars": 1072,
    "preview": "import unittest\n\nimport pytest\n\nimport mps_youtube.main as mps\n\n\nclass TestMain(unittest.TestCase):\n    def test_fmt_tim"
  },
  {
    "path": "mps_youtube/test/test_mpris.py",
    "chars": 3511,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom unittest.mock import MagicMock\n\nimport dbus\nimport pytest\n\nfrom mps_y"
  },
  {
    "path": "mps_youtube/test/test_players_mplayer.py",
    "chars": 1255,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom unittest import mock\n\nimport pytest\n\nfrom mps_youtube.players import "
  },
  {
    "path": "mps_youtube/test/test_util.py",
    "chars": 293,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pytest\n\nimport mps_youtube.util as util\n\n\n@pytest.mark.parametrize("
  },
  {
    "path": "mps_youtube/util.py",
    "chars": 17162,
    "preview": "import collections\nimport ctypes\nimport json\nimport logging\nimport os\nimport platform\nimport re\nimport subprocess\nimport"
  },
  {
    "path": "requirements.txt",
    "chars": 134,
    "preview": "requests\npyreadline3 ; platform_system==\"Windows\"\npyperclip\nyoutube-search-python>=1.6.5\nyt-dlp\ncolorama ; platform_syst"
  },
  {
    "path": "setup.cfg",
    "chars": 60,
    "preview": "[semantic_release]\nversion_variable = setup.py:__version__\n\n"
  },
  {
    "path": "setup.py",
    "chars": 3568,
    "preview": "#!/usr/bin/python3\n\n\"\"\" setup.py for yewtube.\n\nhttps://github.com/iamtalhaasghar/yewtube\n\npython setup.py sdist bdist_wh"
  },
  {
    "path": "wheel_recipe.sh",
    "chars": 90,
    "preview": "rm -rf dist/\npython -m build --sdist\npython -m build --wheel\ntwine upload --verbose dist/*"
  },
  {
    "path": "yewtube.desktop",
    "chars": 230,
    "preview": "[Desktop Entry]\nName=yewtube\nGenericName=Music Player\nKeywords=Audio;Song;Podcast;Playlist;youtube.com;\nExec=yt %U\nTermi"
  },
  {
    "path": "yt",
    "chars": 70,
    "preview": "#!/usr/bin/env python3\nimport mps_youtube.main\nmps_youtube.main.main()"
  }
]

About this extraction

This page contains the full source code of the iamtalhaasghar/yewtube GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 102 files (368.6 KB), approximately 98.3k tokens, and a symbol index with 416 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!