[
  {
    "path": ".gitignore",
    "content": "*.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.env\nenv/\n.idea/\nvenv/\ntest.py"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n<!--next-version-placeholder-->\n\n## v2.9.2 (2023-01-26)\n### Fix\n* Remove pyreadline dependency (#105) ([#107](https://github.com/iamtalhaasghar/yewtube/issues/107)) ([`19e4148`](https://github.com/iamtalhaasghar/yewtube/commit/19e4148242380b543a4825962716550114984f11))\n\n## v2.9.1 (2023-01-26)\n### Fix\n* #50 - brought back download audio file ([`b46dab4`](https://github.com/iamtalhaasghar/yewtube/commit/b46dab47e61c68efa0e51836a8cc9141d15d9e87))\n\n## v2.9.0 (2022-10-20)\n### Feature\n* **mplayer:** Set cache ([#93](https://github.com/iamtalhaasghar/yewtube/issues/93)) ([`16d3a18`](https://github.com/iamtalhaasghar/yewtube/commit/16d3a186fb9feb24530e1f07b211062c44a515a0))\n\n### Fix\n* #76 video pops up ([`eaeff58`](https://github.com/iamtalhaasghar/yewtube/commit/eaeff58f94e2fd89706e42fdab6b8e82ef770941))\n\n## v2.8.5 (2022-09-08)\n### Fix\n* #75 program crashes while creating custom playlist and saving it without playing ([`2552eff`](https://github.com/iamtalhaasghar/yewtube/commit/2552eff602683fbd28bc6841768bf6cf585fc960))\n* **main:** Handle error when setting locale ([#86](https://github.com/iamtalhaasghar/yewtube/issues/86)) ([`ecd117c`](https://github.com/iamtalhaasghar/yewtube/commit/ecd117ca1ef753509b78082d6f919c9bc2b1756b))\n* Enable quit-watch-later in mpv #77 ([`079e440`](https://github.com/iamtalhaasghar/yewtube/commit/079e44088260c938dc3ae71cd55146fb51de653e))\n\n### Documentation\n* Added common issues file. ([#91](https://github.com/iamtalhaasghar/yewtube/issues/91)) ([`4b69e5e`](https://github.com/iamtalhaasghar/yewtube/commit/4b69e5ee96ed36efa9a68f6315322ed3d44d1e3d))\n\n## v2.8.4 (2022-05-05)\n### Fix\n* #53 viewing playlists uploaded by a user is back ([`f201cb5`](https://github.com/iamtalhaasghar/yewtube/commit/f201cb5f4cd45b9341ced6b549fc35a57e85eb9f))\n\n## v2.8.3 (2022-04-25)\n### Fix\n* #45 fetch all videos of a playlist ([`261f468`](https://github.com/iamtalhaasghar/yewtube/commit/261f4687668c6c05415102c66587a27518bbac10))\n* Save full playlists by name and all its videos ([`d69a959`](https://github.com/iamtalhaasghar/yewtube/commit/d69a9594c5824d97201774e81444b75aea93e861))\n* #67  vlc dummy Interface does not work with live channels  ([`2d4637b`](https://github.com/iamtalhaasghar/yewtube/commit/2d4637b04b6f738ab832b3beacab1e490e99a518))\n\n## v2.8.2 (2022-03-17)\n### Fix\n* #63 module album search crash ([`3f2fcfb`](https://github.com/iamtalhaasghar/yewtube/commit/3f2fcfb27bb60928282d1a4a68adff22980f5938))\n\n## v2.8.1 (2022-03-08)\n### Fix\n* #54 play video using youtube short link ([`92d1c77`](https://github.com/iamtalhaasghar/yewtube/commit/92d1c776d4bcc47509becadc5ba9248477dc0dcc))\n* Use mkdocs instead of sphinx docs ([`32a2e9c`](https://github.com/iamtalhaasghar/yewtube/commit/32a2e9cdddac3ebb458d7bdcd793ed83ccc2fdf0))\n\n## v2.8.0 (2022-02-28)\n### Feature\n* **helptext:** Help changelog ([`0643941`](https://github.com/iamtalhaasghar/yewtube/commit/06439411d7a78fe6701f7313e9b3b0720248a197))\n* **setup:** Extras dependencies for mpris ([`936e890`](https://github.com/iamtalhaasghar/yewtube/commit/936e8909b5212eda3a64e8b93be79d4353e6d646))\n\n### Fix\n* #37 use `set pages` command to config how many search result pages to show ([`2baec5f`](https://github.com/iamtalhaasghar/yewtube/commit/2baec5fd11c0edf88d3543dd81333c5ecf67c918))\n* #44 dont run init when importing mps_youtube ([`a072c22`](https://github.com/iamtalhaasghar/yewtube/commit/a072c22e2781160bca79d0164e46e49f07ac28e1))\n* **mpris:** Handle no data on time-pos ([`8bb29d3`](https://github.com/iamtalhaasghar/yewtube/commit/8bb29d33825ad826e51d9d8eada32a9b7bd10ffd))\n* #39 key error 'data' ([`834ed5b`](https://github.com/iamtalhaasghar/yewtube/commit/834ed5b0af5f92e1233e8ba327327654f67f61a0))\n* #38 improved help menu responsiveness ([`972b4ef`](https://github.com/iamtalhaasghar/yewtube/commit/972b4efdb5fe8f5d3295b1c3fe607d209e7d39b6))\n* #35 remove api key instructions ([`4f1fee3`](https://github.com/iamtalhaasghar/yewtube/commit/4f1fee3b711b2383b2704fba39bdce772894cc75))\n* #24 colorama support for windows ([`9cf2616`](https://github.com/iamtalhaasghar/yewtube/commit/9cf261615a52f6ac64b6fb28390db2a71a7ab470))\n\n## v2.7.0 (2022-02-19)\n### Feature\n* Use yewtube over tor using torsocks 🔥 ([`1e9c4ce`](https://github.com/iamtalhaasghar/yewtube/commit/1e9c4ce5992528286f552c8b563daef4abf9566a))\n\n## v2.6.9 (2022-02-19)\n### Fix\n* #28 show changelog with `help new` command ([`d52b65d`](https://github.com/iamtalhaasghar/yewtube/commit/d52b65d0c0cd8708020a2d6788102d82d8ebeee5))\n\n## v2.6.8 (2022-02-19)\n### Fix\n* fixed #26 album search working now without youtube api ([`9c3ae03`](https://github.com/iamtalhaasghar/yewtube/commit/9c3ae03b8c0ae006f1b9a917e4330270fec2f929))\n\n## v2.6.7 (2022-02-19)\n### Fix\n* Check for app updates ([`eabfb52`](https://github.com/iamtalhaasghar/yewtube/commit/eabfb5233c7b87c5f300ebc41250a3f52db07411))\n* Don't crash if playlists / history file has invalid youtube id fixed #24 ([`323d5d8`](https://github.com/iamtalhaasghar/yewtube/commit/323d5d822cefc23889665d71cfffe9e40750433b))\n\n## v2.6.6 (2022-02-18)\n### Fix\n* Playlists are working again fixed #18 ([`bfceee4`](https://github.com/iamtalhaasghar/yewtube/commit/bfceee493261d099c85bf2c4c9e79e5710e9799f))\n* Buffersize warning ([`d185c3f`](https://github.com/iamtalhaasghar/yewtube/commit/d185c3fdf8d520bcb4595f5e458d6022a7b6d1aa))\n* **g:** Mpv msglevel ([`062b125`](https://github.com/iamtalhaasghar/yewtube/commit/062b12503a8fa15dc720cf3ac91f001b74a5cf10))\n\n## v2.6.5 (2022-02-17)\n### Fix\n* Default player priority is vlc > mpv > mplayer on first install fixed #16 ([`35409eb`](https://github.com/iamtalhaasghar/yewtube/commit/35409eb31cc67f03c50589e02cdff2ad08fe4911))\n* **mplayer:** _get_mplayer_version ([`ab21c5d`](https://github.com/iamtalhaasghar/yewtube/commit/ab21c5d1bc872ed482bf482ad37949129c1e4f78))\n* Bring back requirements.txt to life ([`ff6e59d`](https://github.com/iamtalhaasghar/yewtube/commit/ff6e59d75834c61d72ec6bbc92f5eb339cc82607))\n* **util.uea_pad:** Handle AttributeError on t.split ([`1643266`](https://github.com/iamtalhaasghar/yewtube/commit/1643266f21ccf7a99481a1615b4a53c4fbabc878))\n\n## v2.6.4 (2022-02-16)\n### Fix\n* Duplicate changelog and readme files ([`0265ef7`](https://github.com/iamtalhaasghar/yewtube/commit/0265ef7507b539791684bdcf40b30ddaafc525e8))\n\n## v2.6.3 (2022-02-16)\n### Fix\n* Welcome from semantic release python ([`c237a68`](https://github.com/iamtalhaasghar/yewtube/commit/c237a6808869062036f5196775352c1504eafe06))\n\n# yewtube was forked from mps-youtube\n### Features\n* was made to work without YouTube API v3\n* play music in vlc with no gui\n<br>\n<br>\n<hr>\n<br>\n<br>\nVersion 0.2.8\n17 February 2018\n\nFeatures:\n---------\n\n- Lastfm scrobbling (@rien333) (#758)\n- `splaylist` and `suser` commands for Spotify (@ritiek) (#678)\n- Autoplay support (@nikhilweee) (#594)\n- `genpl` command (@nishanthkarthik) (#642)\n- `video_format` configuration setting (@Vrihub) (#656)\n- `live` command for live streams (@Razesdark) (#635)\n- Add time column (@akaWolf) (#582)\n- Add video ID column (@Razesdark) (#627)\n- Allow filtering search by duration (@jas32096) (#548)\n- Allow filtering search by date (@jas32096) (#553)\n- Add `history recent` to display history without duplicates (@srvanrell) (#510)\n- `--no-textart` to disable ascii art (for screenreaders) (@Gongreg) (#517)\n- `set_title` option to disable setting window title (@ardrabczyk) (#498)\n- Add `s` command for getting stream information (@ritiek) (#675)\n- Add option to disable mpris (@hrnr) (#728)\n- Generate playlist from video description (@Razesdark) (#649)\n\nEnhancements:\n-------------\n- Store playlists as m3u files instead of binary (@kraetzin) (#682)\n- Show replies when displaying comments (@paulfertser) (#677)\n- Use https urls for album art (@vszakats) (#574)\n- When using \"repeat\" with mpv, keep player running (@ritiek) (#660)\n- Display artist/album in mpris using lastfm (@vn-ki) (#739)\n- Use channel.list API for user search (@Razesdark) (#628)\n- Maintain volume across songs with mpv (@Razesdark) (#720)\n- Prevent mpris from crashing the main process (@hrnr) (#728)\n\nBug fixes:\n----------\n- Fix mpris seeking with recent mpv vesions (@mg6) (#687)\n- Fix removing video from multi-page playlist (@kraetzin) (#695)\n- Skip unavailable tracks (@ritiek) (#734)\n- Correctly display minutes/seconds (@Laxa) (#748)\n- Handle `null` time-pos from mpv (@pritambaral) (#519)\n- Fix da/dv command regex (@Vrihub) (#691)\n- Skip channels in video/playlist searches (@ritiek) (#664)\n- Fix divide by zero error (@ids1024) (#620)\n\nUse `git log v0.2.7.1..v0.2.8` to see all changes, including various minor\nfixes, documentation changes, etc. not included here.\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.7.1\n6 July 2016\n\nBug fixes:\n----------\n- Fix pickle error (@ids1024) (#503)\n- Install LICENSE, README.md, and CHANGELOG as package_data (@ids1024)\n- Update youtube-dl in py2exe build (@ids1024)\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.7\n27 June 2016\n\nFeatures:\n---------\n- Setting for default audio format (@nishanthkarthik) (#71 #466 #467)\n- Search history with `history` command (@kraetzin) (#344 #472)\n- Add syntax for repeating a track several times (@ghallak) (#437 #490)\n- Reverse command (@kraetzin) (#422 #473)\n- New `daurl <url>` command (@maricn) (#402)\n\nEnhancements:\n-------------\n- Pass `--no-ytdl` to mpv (@ids1024) (#492)\n- Do not suppress mpv output in debug mode (@ids1024)\n- Print traceback in debug mode (@ids1024)\n- Speed up `checkupdate` by avoiding redirects (@ids1024) (#454)\n- Pass `--play-and-exit` if vlc is used as a player (@ids1024)`\n\nBug fixes:\n----------\n- Fix error with python 3.3 (@ids1024) (#414)\n- Fix maxres bug (@ids1024) (#430)\n- Fix playlist cache bug in info command (@ids1024) (#468)\n- Fix usersearch argument error (@ids1024) (#469 #482)\n- Fix progress bar with new mpv versions (@ids1024) (#470 #485)\n- Fix syntax error with set command (@ids1024) (#419)\n- Fix syntax error with -w, -f, -a (@ids1024) (#420)\n- Fix clipboard support (@ids1024) (#461)\n- Fix mpv version checking on windows (@ids1024) (#397)\n- Add youtube_dl as dependency to Dockerfile (@PI-Victor) (#481)\n\nInternal api changes:\n---------------------\n- The code is now split between several files (@ids1024) (#208)\n- Add initial content api, for now only used for comments (@ids1024)\n- Begin documenting internal apis using sphinx (@ids1024)\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.6\n1 January 2016\n\nFeatures:\n- Add browserplay command to play video in browser (rjvani) (#355 #390)\n- Make url command support multiple url, and allow loading urls from file\n    (paulnicolet) (#90 #391)\n- Make youtube id available to download command (ids1024) (#375)\n- Make pagination work properly for all lists of songs (local playlists, etc.)\n    and make them all support the dump command (ids1024) (#201)\n- Show warning when adding duplicate track to playlist (BensonQiu) (#374 #383)\n\nBug fixes:\n- Support playlists longer than 200 items (ids1024) (#192)\n- Make dapl download complete playlist (JKatzwinkel) (#294 #325)\n- Use pyperclip instead of xerox, fixing clipboard on linux (ids1024) (#311)\n- Fix error message on windows when video title has & (ids1024) (#321)\n- Run notifier command in background (hrnr) (#339)\n- Correctly handle -v option of play (TimoDritschler) (#352)\n- Make it possible to use a pager with --help (livingBEEF) (#349)\n- Allow mplayer for https streams if version is new enough\n    (ids1024 Evidlo paddatrapper) (#315 #336 #317)\n- Use mpv.com instead of mpv.exe on windows (ids1024)\n\nInternal API changes:\n- Split code into several files (still a work in progress) (ids1024) (#208)\n- Use a python decorator to declare commands (ids1024)\n- Create a paginatesongs() function for handling the pagination and dump\n  command uniformly as mentioned in features (#399) (ids1024)\n- Various others\n\nThere have been various other small bug fixes and internal API changes. Use\n`git log v0.2.5..0.2.6` to see all of them.\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.5\n1 June 2015\n\n- Support python 3 only (will not run with python 2)\n- Fix progress bar bug on Windows (#215, #223)\n- Fix bug in playlist search (#282)\n- Add user_order setting for separate order of user searches (lol768) (#277)\n- Add mix command (lol768) (#241, #283)\n- Add page count with total number of pages and current page (JKatzwinkel)\n- Fix UnicodeEncodeError on non-unicode terminals\n- Install .desktop in setup.py so it does not have to be installed manually\n    required for Ubuntu sound menu support\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.4\n13 May 2015\n\n - Fix issue with rate-limiting in \"album\" command (#217)\n - Implement support for MPRIS (hrnr and ids1024) (#191, #210)\n - Fix display issue with small terminal width (#215)\n - Use version 3 of the youtube api (JKatzwinkel, ids1024, and lol768) (#256)\n     version 2 was disabled by youtube and no longer works\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.3\n17 February 2015\n\n - Fix issue with opening old playlist file (#214)\n - Fix issue with \"set\" command\n - Metadata tagging of downloaded audio files\n     requires ffmpeg or avconv\n     early implementation, uses YouTube video title, needs more work\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.2\n14 February 2015\n\n- Implement skip to previous track (ids1024) #175 #18 #14\n    Use > and < keys for next and prev track, q for quit (was ctrl-c)\n    mpv / mplayer input.conf can be imported to use custom keymappings\n\n- Implement optional external download application (ids1024 and np1) #198 #132\n    enter \"help dl-command\" for more info\n\n- Show stream quality on status line (Brebiche38) #134 #163\n\n- Implement support for creating Windows builds with py2exe (ids1024) #190\n    Use setup.py in py2exe branch\n\n- Fix progress bar for mpv 0.7 (ids1024) #155 #161\n    Resolves issues with playback looping\n\n- Fix mps-youtube does not run on FreeBSD (nivit)\n\n- Fix YouTube comments overshoot window size\n\n- Fix issue with audio remux when using `d` download command\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.1\n27 November 2014\n\n[Bugfix] - Detect installed player on installation (#149)\n\n-------------------------------------------------------------------------------\n\nVersion 0.2.0\n25 November 2014\n\n- Auto detect terminal window size\n\n- Transcode audio to MP3 and other formats (requires ffmpeg or avconv)\n\n- Enabled da and dv commands for playlist search results\n\n- Added dapl and dvpl to download YouTube playlist audio/video\n    by url/id to a separate subdirectory (mtahmed) #110\n\n- Progress indicator now works with mpv (previously only mplayer)\n\n- Added option to show system notifications (Alex Nisnevich) #95\n    (can be used with libnotify - notify-send on linux)\n\n- Added overwrite true/false option for downloads (mtahmed) #93\n    (skips download if downloaded file already exists)\n\n- Added copy to clipboard feature #97\n    (requires python xerox module and xclip on linux or pywin32 on windows)\n\n- Remux audio downloads for better file compatibility (#135)\n\n[Bugfix] - Accept two-character length usernames (#99)\n\n[Bugfix] - Expand ~ character in download directory setting (punchagan)\n\n[Bugfix] - Don't truncate filename (YoussF) #122\n\n[Bugfix] - Exit with correct status code\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.46\nMay 18 2014\n\n - Added c <number> to view comments for a video\n    (first 50 comments, no reply-comments)\n\n - Added feature to match album tracks using MusicBrainz (vixus0)\n    To search albums, enter \"album\" optionally followed by album title\n\n - Custom formatted search result list using \"set columns\" command\n   Optionally shows: rating, likes, dislikes, views, user, date, category\n   and comments (number of) in search results\n\n - Added \"set order <relevance|views|rating|date>\" command for\n     specifying search result ordering\n\n - Added \"set console-width\" for setting output width (default 80)\n\n - Added uploaded date in video info display (request #64)\n\n - Added likes / dislikes in video info display\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.44\nMar 27 2014\n\n - Added max_res config item for selecting video resolution (request 56)\n - Added window_size and window_pos for selecting size / position of player\n - Improved handling of playlist file read/write (issue 66)\n - Revert to lower quality on unavailable/corrupt streams (issue 65)\n - Enabled multiple invocation commands (comma separated) (request 61)\n    Eg: mpsyt //the doors, 1, shuffle, 1-3-a, quit\n - Improved url caching\n - Added shuffle command (no arguments, shuffles displayed items)\n - Handle 'video not available in your country' during multiple downloads\n - Fix UnicodeDecodeError in mplayer progress parsing (issue 58)\n - Fix UnicodeEncodeError under Windows with Python 2.7 (issue 59)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.41\nMar 14 2014\n\n - new configuration option, max_results - sets number of returned results\n    (1 - 50)\n - pl <url> now accepts YouTube playlist id's as well as url's\n - Fix error in download of .m4a files when mplayer is set as player.\n - Added option for downloading multiple items\n     eg. da 1-4 or dv 3,5,6\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.40\nMar 11 2014\n\n - Bugfix release, corrects UnicodeDecode error\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.39\nMar 10 2014\n\nFeatures:\n - Added time / progress bar indicator. Big thanks to Thomas LÉVEIL!\n    (mplayer only)\n - Added command to retrieve YouTube user playlists; \n    userpl {username} or upl {username}\n - Added command to retrieve related videos; r{number}\n - playurl now respects -f, -w, and -a flags (fullscreen, window or audio)\n - Implemented input history persistence (uses readline, linux only)\n - Implemented non-interactive mode for command line invocation with playurl\n - Implemented less interactive mode for command line invocation with dlurl\n\nChanges:\n - // or .. prefix to search for YouTube playlists (was plsearch / pls)\n\nHelp / Documentation:\n - help <command> will show relevant help topic page e.g., help dlurl\n - Documented configuration options (\"set\" commands)\n - Re-authored some help categories\n - Changed help <number> to help <topic>, removed menu from help pages\n\nBugfixes\n - mplayer / mpv window now displays content title instead of url\n - Fixed issue with Python3 terminal output on playback ctrl-c interrupt\n - Fixed issue with debug mode not logging to file\n - Changed year format in YT playlist result screen to last two digits.\n      (Under some environments it was showing 4-digit years)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.38\nMar 5 2014\n\n - Added i<number> for YT playlist information display \n - Added stream url preloading for first item of opened YT playlists\n - Added last-updated date to YT playlist search result list \n - Fixed UnicodeError when run in non-UTF8 environments\n - Added more verbosity to --version command line option\n - Added --debug command line option (logs to <tmpdir>/mpsyt.log)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.37\nMar 2 2014\n\n - Excluded YouTube paid videos from search results\n - Added \"pl <playlist url>\" command to open YouTube playlist url\n - Added \"plsearch <query>\" command to search for YouTube playlists\n - Added \"dump\" command to show entire YT playlist (useful for saving locally)\n - Added \"undump\" command to undo dump (re-paginates YT playlist items)\n - Added \"u <number>\" command to list uploads by uploader of <number>\n - Added \"url <YouTube url>\" command for retrieving a specific YT video\n - Added \"playurl <YouTube url>\" command for directly playing a YT video\n - Added \"dlurl <YouTube url>\" command for directly downloading a YT video\n - Changed command to list user uploads, new syntax is \"user <username>\"\n - Added mpsyt --version flag for printing version info\n - Added mpsyt --help flag for printing help text\n - Fixed indentation bug when scrolling through readline history\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.36\nFeb 27 2014\n\n - Wait for preloading item if it is selected while preloading\n - Fix bug where -a audio override is sometimes ignored\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.35\nFeb 25 2014\n\n - Faster opening of audio streams with mpv \n    (--demuxer-lavf-o=fflags=+ignid argument added for m4a streams)\n\n - Faster opening of audio streams with mplayer \n    (reject m4a streams, prefer ogg streams)\n    (fallback to video stream and suppress video when no ogg available)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.34\nFeb 22 2014\n\n - Fix bug: fails when no playlist file exists\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.33\nFeb 22 2014\n\n - Changed structure of playlist file. Now consumes KB's rather than MB's\n - Same playlist file shared between Python2.7+ and Python3+ (was separate)\n - Improved display alignment for Russian text\n - Preload of url fails silently on unobtainable items (previously crashed)\n - Added prompt to mux audio on m4v download (experimental)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.32\nFeb 17 2014\n\n - Improve display alignment with certain unicode characters\n - Fix crash when using 'set' command on Windows (thomasleveil)\n\n-------------------------------------------------------------------------------\n\nVersion 0.01.31\nFeb 13 2014\n\n - Migrate location of config directory to reflect new name\n   (~/.config/mps-youtube)\n\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing for yewtube\n\nContributions are very much appreciated!\n\n* Pull requests should be based on and submitted to the \"develop\" branch.\n\n* Please raise an issue to discuss what you plan to implement or change before \nyou start if it is going to involve a lot of work on your part.\n\n* Please keep pull requests specific, do not make many disparate changes or\nnew features in one request.  A separate pull request for each feature change\nis preferred.\n\n* Please ensure your changes work in Python 3.3+ and Windows.\n\n\n## Code conventions\n\n* Maximum line length is 80 characters\n\n* Follow the line-spacing style that is already in place.\n\n* Ensure all functions and classes have a PEP257 compliant docstring and the\ncode is PEP8 compliant.\n\n## Documentation\n\nInstall required extra docs package to setup mkdocs: `pip install -e \".[docs]\"`\n\nTo run built-in dev server: `mkdocs serve`\n\nTo deploy documentation to github page: `mkdocs gh-deploy`\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM python:3-stretch\n\nLABEL maintainer=\"Justin Garrison <justinleegarrison@gmail.com>\" \\\n    org.label-schema.schema-version=\"1.0\" \\\n    org.label-schema.name=\"mps-youtube\" \\\n    org.label-schema.description=\"Terminal based YouTube player and downloader \" \\\n    org.label-schema.url=\"https://github.com/mps-youtube/mps-youtube/wiki\" \\\n    org.label-schema.vcs-url=\"https://github.com/mps-youtube/mps-youtube\" \\\n    org.label-schema.docker.cmd=\"docker run -v /dev/snd:/dev/snd -it --rm --privileged --name mpsyt mpsyt\"\n\nRUN DEBIAN_FRONTEND=noninteractive && \\\n    apt-get update && \\\n    apt-get install -y mplayer mpv && \\\n    rm -rf /var/lib/apt/lists/* && \\\n    apt-get clean && apt-get purge\n\nRUN pip install mps-youtube youtube-dl\n\nENTRYPOINT [\"mpsyt\"]\n"
  },
  {
    "path": "ISSUE_TEMPLATE.md",
    "content": "<!--- Provide a general summary of the issue in the Title above -->\n\n## Issue / Suggestion\n<!--- If you're describing a bug, tell us what error you are experiencing -->\n<!--- 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 -->\n<!--- If you're suggesting a change/improvement, tell us how it should work -->\n\n## Your Environment\n<!--- Include as many relevant details about the environment you experienced the bug in -->\n<!--- Run \"mpsyt --version\" and post your version information here --->\n<!-- What version of the OS are you running, any other  -->\n<!-- What music player are you using with mps-youtube, version? -->\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/}\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see {http://www.gnu.org/licenses/}.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n{http://www.gnu.org/licenses/}.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n{http://www.gnu.org/philosophy/why-not-lgpl.html}.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include mps-youtube.desktop\ninclude LICENSE\ninclude README.md\ninclude CHANGELOG.md\n"
  },
  {
    "path": "README.md",
    "content": "\n![](https://img.shields.io/pypi/v/yewtube.svg)  ![](https://img.shields.io/pypi/wheel/yewtube.svg)\n\n<pre>\n                      _         _          \n                     | |       | |         \n  _   _  _____      _| |_ _   _| |__   ___ \n | | | |/ _ \\ \\ /\\ / / __| | | | '_ \\ / _ \\\n | |_| |  __/\\ V  V /| |_| |_| | |_) |  __/\n  \\__, |\\___| \\_/\\_/  \\__|\\__,_|_.__/ \\___|\n   __/ |                                   \n  |___/\n\n\n</pre>\n\n\n Terminal based YouTube player and downloader. No Youtube API key required. Forked from mps-youtube \n\nInstallation\n-----------\n# Stable Version\n\n### Using pip\n1. Install using `pip install yewtube`\n2. Run using, `yt`. Enjoy! \n\n### Using pipx (Recommended)\n1.  Install **_pipx_** using `pip install pipx`\n2.  Install `yewtube` using `pipx install yewtube`\n3.  Now, type `yt` That's it.\n\n# Latest Version\n\n### Using pip\n1. Install using `pip install git+https://github.com/iamtalhaasghar/yewtube.git`\n2. Run using, `yt`. Enjoy! \n\n### Using pipx\n1.  Install **_pipx_** using `pip install pipx`\n2.  Install `yewtube` using `pipx install git+https://github.com/iamtalhaasghar/yewtube.git`\n3.  Now, type `yt` That's it.\n\nWhat's new in yewtube?\n----------------------\n-   **No Youtube API Key required**\n-   **Run audio in VLC with no GUI**\n\nSee complete and up-to-date changelog [here](https://github.com/iamtalhaasghar/yewtube/blob/master/CHANGELOG.md).\n\nThese features are still inherited from [mps-youtube](https://github.com/mps-youtube/mps-youtube).\n-   Search and play audio/video from YouTube\n-   Search tracks of albums by album title\n-   Search and import YouTube playlists\n-   Create and save local playlists\n-   Download audio/video\n-   Convert to mp3 & other formats (requires ffmpeg or avconv)\n-   View video comments\n-   Works with Python 3.x\n-   Works with Windows, Linux and Mac OS X\n-   Requires mplayer, mpv or VLC\n\nThis 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\nimplementation uses YouTube as a source of content and can play and\ndownload video as well as audio. The [pafy](https://github.com/mps-youtube/pafy)  library handles interfacing with YouTube.\n\n[mps-youtube wiki](https://github.com/mps-youtube/mps-youtube/wiki/Troubleshooting) <br>\n[yewtube wiki](https://github.com/iamtalhaasghar/yewtube/wiki/FAQ)\n\nScreenshots\n-----------\n\nSearch:<br>\n![](http://mps-youtube.github.io/mps-youtube/std-search.png)\n\nA standard search is performed by entering `/` followed by search terms.\n\nYou can play all of the search results by giving `1-` as input\n\nRepeating song/songs can be done with `song_number[loop]`, for example:\n`1[3]` or `4-6[2]`\n\nLocal Playlists:<br>\n![](http://mps-youtube.github.io/mps-youtube/local-playlist.png)\n\nSearch result items can easily be stored in local playlists.\n\nYouTube Playlists:<br>\n![](http://mps-youtube.github.io/mps-youtube/playlist-search.png)\n\nYouTube playlists can be searched and played or saved as local\nplaylists.\n\nA playlist search is performed by `//` followed by search term.\n\nDownload:<br>\n![](http://mps-youtube.github.io/mps-youtube/download.png)\n\nContent can be downloaded in various formats and resolutions.\n\nComments:<br>\n![](http://mps-youtube.github.io/mps-youtube/comments.png)\n\nA basic comments browser is available to view YouTube user comments.\n\nMusic Album Matching:<br>\n\n![](http://mps-youtube.github.io/mps-youtube/album-1.png)\n\n![](http://mps-youtube.github.io/mps-youtube/album-2.png)\n\nAn album title can be specified and yewtube will attempt to find\nmatches for each track of the album, based on title and duration. Type\n`help search` for more info.\n\nCustomisation:<br>\n\n![](http://mps-youtube.github.io/mps-youtube/customisation2.png)\n\nSearch results can be customised to display additional fields and\nordered by various criteria.\n\nThis configuration was set up using the following commands\n```\nset order views\nset columns user:14 date comments rating likes dislikes category:9 views\n```\n\nType `help config` for help on configuration options\n\nUpgrading\n---------\n\n### If installed using pipx\n\n` pipx upgrade yewtube `\n\n### If installed using pip\n\n`pip install --upgrade yewtube`\n\nUsage\n-----\n\nyewtube is run on the command line using the command:\n\n   `yt`\n\nEnter `h` from within the program for help.\n\n\nUsing yewtube with mpris\n------------------------\n\n1. Install PyGObject, GTK and their dependencies based on this guide https://pygobject.readthedocs.io/en/latest/getting_started.html\n2. Install yewtube with mpris extra\n\n```shell\n> # recommended\n> pipx install 'yewtube[mpris]'\n> # or\n> pip install 'yewtube[mpris]'\n```\n\n3. check yewtube version\n\n```shell\n> yt --version\nyewtube version    : 2.8.2\nyt_dlp version     : 2022.02.04\nPython version     : 3.9.7 (default, Nov  7 2021, 15:17:57)\n[GCC 11.2.0]\nProcessor          : x86_64\nMachine type       : x86_64\nArchitecture       : 64bit, ELF\nPlatform           : Linux-5.13.0-35-generic-x86_64-with-glibc2.34\nsys.stdout.enc     : utf-8\ndefault enc        : utf-8\nConfig dir         : /home/user/.config/mps-youtube\ndbus               : 1.2.18\nglib               : True\nenv:TERM           : tmux-256color\nenv:SHELL          : /usr/bin/zsh\nenv:LANG           : en_US.UTF-8\n```\n\nIf everything working correctly, dbug and glib would have similar result as above text\n\n4. run `set mpris true` on yewtube\n5. check with `playerctl`\n\n```shell\n> playerctl -l\nmps-youtube.instance567867\n```\n\nCheck also the [common-issue](https://github.com/iamtalhaasghar/yewtube/wiki/Common-issues) if you are having problem with yewtube.\n\nHow to Contribute\n-----------------\n\nContributions are welcomed! However, please check out the [contribution page](https://github.com/iamtalhaasghar/yewtube/blob/master/CONTRIBUTING.md) before making a contribution.\n"
  },
  {
    "path": "RELEASING.md",
    "content": "Release process for pafy and mps-youtube\n========================================\n\nLooking at the commits and Github releases for previous versions can provide an example.\n\nVersion numbers\n---------------\n### pafy\nBump the `__version__` in `__init__.py`.\n\n### mps-youtube\nBump the `version` in `VERSION`, `__version__` and `__notes__` in `__init__.py`, and `VERSION` in `setup.py`.\n\nChangelogs\n----------\nUpdate `CHANGELOG` with a summary of changes since the last release. `git shortlog` can be helpful to see what commits have occurred.\n\n### mps-youtube\nAlso 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.\n\nGithub Release\n--------------\nCreate a release through the Github website, tagging the commit that should be released. The text from the `CHANGELOG` should be copied to the release.\n\npy2exe\n------\nFor 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.\n\nPyPI\n----\nPush 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.\n\nGPG Signatures\n--------------\nThe `.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.\n\nPossible Simplifications to this Process\n----------------------------------------\nThe New Features help text isn't really important, but it is genuinely nice to have if kept up to date.\n\nPerhaps the `CHANGELOG` file isn't really needed, if Github releases includes that information.\n"
  },
  {
    "path": "_config.yml",
    "content": "theme: jekyll-theme-hacker"
  },
  {
    "path": "doc/conf.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# mps_youtube documentation build configuration file, created by\n# sphinx-quickstart on Mon Apr 18 17:35:31 2016.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nimport sys\nimport os\nimport sphinx_rtd_theme\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#sys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    'sphinx.ext.autodoc',\n    'sphinx.ext.todo',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'mps_youtube'\ncopyright = '2016, mps-youtube developers'\nauthor = 'mps-youtube developers'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = ''\n# The full version, including alpha/beta/rc tags.\nrelease = ''\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'en'\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n#keep_warnings = False\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#html_theme = 'alabaster'\nhtml_theme = \"sphinx_rtd_theme\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n#html_theme_path = []\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n# The name for this set of Sphinx documents.\n# \"<project> v<release> documentation\" by default.\n#html_title = 'mps_youtube v'\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (relative to this directory) to use as a favicon of\n# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n#html_extra_path = []\n\n# If not None, a 'Last updated on:' timestamp is inserted at every page\n# bottom, using the given strftime format.\n# The empty string is equivalent to '%b %d, %Y'.\n#html_last_updated_fmt = None\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Language to be used for generating the HTML full-text search index.\n# Sphinx supports the following languages:\n#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'\n#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'\n#html_search_language = 'en'\n\n# A dictionary with options for the search language support, empty by default.\n# 'ja' uses this config value.\n# 'zh' user can custom change `jieba` dictionary path.\n#html_search_options = {'type': 'default'}\n\n# The name of a javascript file (relative to the configuration directory) that\n# implements a search results scorer. If empty, the default will be used.\n#html_search_scorer = 'scorer.js'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'mps_youtubedoc'\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n\n# Latex figure (float) alignment\n#'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, 'mps_youtube.tex', 'mps\\\\_youtube Documentation',\n     'Author', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    (master_doc, 'mps_youtube', 'mps_youtube Documentation',\n     [author], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (master_doc, 'mps_youtube', 'mps_youtube Documentation',\n     author, 'mps_youtube', 'One line description of project.',\n     'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False\n\n\n# -- Options for Epub output ----------------------------------------------\n\n# Bibliographic Dublin Core info.\nepub_title = project\nepub_author = author\nepub_publisher = author\nepub_copyright = copyright\n\n# The basename for the epub file. It defaults to the project name.\n#epub_basename = project\n\n# The HTML theme for the epub output. Since the default themes are not\n# optimized for small screen space, using the same theme for HTML and epub\n# output is usually not wise. This defaults to 'epub', a theme designed to save\n# visual space.\n#epub_theme = 'epub'\n\n# The language of the text. It defaults to the language option\n# or 'en' if the language is not set.\n#epub_language = ''\n\n# The scheme of the identifier. Typical schemes are ISBN or URL.\n#epub_scheme = ''\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n#epub_identifier = ''\n\n# A unique identification for the text.\n#epub_uid = ''\n\n# A tuple containing the cover image and cover page html template filenames.\n#epub_cover = ()\n\n# A sequence of (type, uri, title) tuples for the guide element of content.opf.\n#epub_guide = ()\n\n# HTML files that should be inserted before the pages created by sphinx.\n# The format is a list of tuples containing the path and title.\n#epub_pre_files = []\n\n# HTML files that should be inserted after the pages created by sphinx.\n# The format is a list of tuples containing the path and title.\n#epub_post_files = []\n\n# A list of files that should not be packed into the epub file.\nepub_exclude_files = ['search.html']\n\n# The depth of the table of contents in toc.ncx.\n#epub_tocdepth = 3\n\n# Allow duplicate toc entries.\n#epub_tocdup = True\n\n# Choose between 'default' and 'includehidden'.\n#epub_tocscope = 'default'\n\n# Fix unsupported image types using the Pillow.\n#epub_fix_images = False\n\n# Scale large images.\n#epub_max_image_width = 0\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#epub_show_urls = 'inline'\n\n# If false, no index is generated.\n#epub_use_index = True\n"
  },
  {
    "path": "doc/index.rst",
    "content": ".. mps_youtube documentation master file, created by\n   sphinx-quickstart on Mon Apr 18 17:35:31 2016.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nAPI Documentation for mps_youtube\n=================================\n\nContents:\n\n.. toctree::\n   mps_youtube\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n"
  },
  {
    "path": "doc/modules.rst",
    "content": "mps_youtube\n===========\n\n.. toctree::\n   :maxdepth: 4\n\n   mps_youtube\n"
  },
  {
    "path": "doc/mps_youtube.c.rst",
    "content": "mps_youtube.c module\n====================\n\n.. automodule:: mps_youtube.c\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.cache.rst",
    "content": "mps_youtube.cache module\n========================\n\n.. automodule:: mps_youtube.cache\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.album_search.rst",
    "content": "mps_youtube.commands.album_search module\n========================================\n\n.. automodule:: mps_youtube.commands.album_search\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.config.rst",
    "content": "mps_youtube.commands.config module\n==================================\n\n.. automodule:: mps_youtube.commands.config\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.download.rst",
    "content": "mps_youtube.commands.download module\n====================================\n\n.. automodule:: mps_youtube.commands.download\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.local_playlist.rst",
    "content": "mps_youtube.commands.local_playlist module\n==========================================\n\n.. automodule:: mps_youtube.commands.local_playlist\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.misc.rst",
    "content": "mps_youtube.commands.misc module\n================================\n\n.. automodule:: mps_youtube.commands.misc\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.play.rst",
    "content": "mps_youtube.commands.play module\n================================\n\n.. automodule:: mps_youtube.commands.play\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.rst",
    "content": "mps_youtube.commands package\n============================\n\nSubmodules\n----------\n\n.. toctree::\n\n   mps_youtube.commands.album_search\n   mps_youtube.commands.config\n   mps_youtube.commands.download\n   mps_youtube.commands.local_playlist\n   mps_youtube.commands.misc\n   mps_youtube.commands.play\n   mps_youtube.commands.search\n   mps_youtube.commands.songlist\n\nModule contents\n---------------\n\n.. automodule:: mps_youtube.commands\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.search.rst",
    "content": "mps_youtube.commands.search module\n==================================\n\n.. automodule:: mps_youtube.commands.search\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.commands.songlist.rst",
    "content": "mps_youtube.commands.songlist module\n====================================\n\n.. automodule:: mps_youtube.commands.songlist\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.config.rst",
    "content": "mps_youtube.config module\n=========================\n\n.. automodule:: mps_youtube.config\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.content.rst",
    "content": "mps_youtube.content module\n==========================\n\n.. automodule:: mps_youtube.content\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.g.rst",
    "content": "mps_youtube.g module\n====================\n\n.. automodule:: mps_youtube.g\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.helptext.rst",
    "content": "mps_youtube.helptext module\n===========================\n\n.. automodule:: mps_youtube.helptext\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.history.rst",
    "content": "mps_youtube.history module\n==========================\n\n.. automodule:: mps_youtube.history\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.init.rst",
    "content": "mps_youtube.init module\n=======================\n\n.. automodule:: mps_youtube.init\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.main.rst",
    "content": "mps_youtube.main module\n=======================\n\n.. automodule:: mps_youtube.main\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.mpris.rst",
    "content": "mps_youtube.mpris module\n========================\n\n.. automodule:: mps_youtube.mpris\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.paths.rst",
    "content": "mps_youtube.paths module\n========================\n\n.. automodule:: mps_youtube.paths\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.player.rst",
    "content": "mps_youtube.player module\n=========================\n\n.. automodule:: mps_youtube.player\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.playlist.rst",
    "content": "mps_youtube.playlist module\n===========================\n\n.. automodule:: mps_youtube.playlist\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.playlists.rst",
    "content": "mps_youtube.playlists module\n============================\n\n.. automodule:: mps_youtube.playlists\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.rst",
    "content": "mps_youtube package\n===================\n\nSubpackages\n-----------\n\n.. toctree::\n\n    mps_youtube.commands\n\nSubmodules\n----------\n\n.. toctree::\n\n   mps_youtube.c\n   mps_youtube.cache\n   mps_youtube.config\n   mps_youtube.content\n   mps_youtube.g\n   mps_youtube.helptext\n   mps_youtube.history\n   mps_youtube.init\n   mps_youtube.main\n   mps_youtube.mpris\n   mps_youtube.paths\n   mps_youtube.player\n   mps_youtube.playlist\n   mps_youtube.playlists\n   mps_youtube.screen\n   mps_youtube.streams\n   mps_youtube.terminalsize\n   mps_youtube.util\n\nModule contents\n---------------\n\n.. automodule:: mps_youtube\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.screen.rst",
    "content": "mps_youtube.screen module\n=========================\n\n.. automodule:: mps_youtube.screen\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.streams.rst",
    "content": "mps_youtube.streams module\n==========================\n\n.. automodule:: mps_youtube.streams\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.terminalsize.rst",
    "content": "mps_youtube.terminalsize module\n===============================\n\n.. automodule:: mps_youtube.terminalsize\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "doc/mps_youtube.util.rst",
    "content": "mps_youtube.util module\n=======================\n\n.. automodule:: mps_youtube.util\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "docs/changelog.md",
    "content": "--8<-- \"CHANGELOG.md\"\n"
  },
  {
    "path": "docs/contributing.md",
    "content": "--8<-- \"CONTRIBUTING.md\"\n"
  },
  {
    "path": "docs/css/mkdocstrings.css",
    "content": "/* Indentation. */\ndiv.doc-contents:not(.first) {\n  padding-left: 25px;\n  border-left: 4px solid rgba(230, 230, 230);\n  margin-bottom: 80px;\n}\n\n/* Don't capitalize names. */\nh5.doc-heading {\n  text-transform: none !important;\n}\n\n/* Don't use vertical space on hidden ToC entries. */\n.hidden-toc::before {\n  margin-top: 0 !important;\n  padding-top: 0 !important;\n}\n\n/* Don't show permalink of hidden ToC entries. */\n.hidden-toc a.headerlink {\n  display: none;\n}\n\n/* Avoid breaking parameters name, etc. in table cells. */\ntd code {\n  word-break: normal !important;\n}\n\n/* For pieces of Markdown rendered in table cells. */\ntd p {\n  margin-top: 0 !important;\n  margin-bottom: 0 !important;\n}\n"
  },
  {
    "path": "docs/gen_ref_nav.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Generate the code reference pages and navigation.\"\"\"\n\nfrom pathlib import Path\n\nimport mkdocs_gen_files\n\nnav = mkdocs_gen_files.Nav()\n\nskip_files = [\n    (Path(\"mps_youtube\") / \"config.py\"),\n    (Path(\"mps_youtube\") / \"mpris.py\"),\n]\nskip_files.extend((Path(\"mps_youtube\") / \"test\").glob(\"*.py\"))\nfor path in sorted(Path(\"mps_youtube\").glob(\"**/*.py\")):\n    if path in skip_files:\n        continue\n    module_path = path.with_suffix(\"\")\n    doc_path = path.relative_to(\"mps_youtube\").with_suffix(\".md\")\n    full_doc_path = Path(\"reference\", doc_path)\n\n    parts = list(module_path.parts)\n    parts[-1] = f\"{parts[-1]}.py\"\n    nav[parts] = doc_path\n\n    with mkdocs_gen_files.open(full_doc_path, \"w\") as fd:\n        ident = \".\".join(module_path.parts)\n        print(\"::: \" + ident, file=fd)\n\n    mkdocs_gen_files.set_edit_path(full_doc_path, path)\n\nwith mkdocs_gen_files.open(\"reference/SUMMARY.md\", \"w\") as nav_file:\n    nav_file.writelines(nav.build_literate_nav())\n"
  },
  {
    "path": "docs/index.md",
    "content": "--8<-- \"README.md\"\n"
  },
  {
    "path": "docs/license.md",
    "content": "```\n--8<-- \"LICENSE\"\n```\n"
  },
  {
    "path": "mkdocs.yml",
    "content": "site_name: Yewtube\nsite_description: Terminal based YouTube player and downloader.\nsite_url: https://iamtalhaasghar.github.io/yewtube\nrepo_url: https://github.com/iamtalhaasghar/yewtube\nrepo_name: iamtalhaasghar/yewtube\n\nnav:\n- Home:\n  - Overview: index.md\n  - Changelog: changelog.md\n  - License: license.md\n- Code Reference: reference/\n- Development:\n  - Contributing: contributing.md\n\ntheme:\n  name: material\n  features:\n  - navigation.tabs\n  palette:\n    scheme: slate\n    primary: teal\n    accent: purple\n\nextra_css:\n- css/mkdocstrings.css\n\nmarkdown_extensions:\n- admonition\n- pymdownx.emoji\n- pymdownx.magiclink\n- pymdownx.snippets:\n    check_paths: true\n- pymdownx.superfences\n- pymdownx.tabbed\n- pymdownx.tasklist\n- toc:\n    permalink: true\n\nplugins:\n- search\n- mkdocstrings:\n    watch:\n    - mps_youtube\n- gen-files:\n    scripts:\n    - docs/gen_ref_nav.py\n- literate-nav:\n    nav_file: SUMMARY.md\n"
  },
  {
    "path": "mps_youtube/__init__.py",
    "content": "from pip._vendor import pkg_resources\n\n__version__ = next((p.version for p in pkg_resources.working_set if p.project_name.lower() == 'yewtube'), \"unable to determine\")\n__author__ = \"iamtalhaasghar\"\n__license__ = \"GPLv3\"\n__url__ = \"https://github.com/iamtalhaasghar/yewtube\"\n\n"
  },
  {
    "path": "mps_youtube/c.py",
    "content": "\"\"\" Module for holding colour code values. \"\"\"\n\nimport os\nimport re\nimport sys\n\n\nif sys.stdout.isatty():\n    white = \"\\x1b[%sm\" % 0\n    ul = \"\\x1b[%sm\" * 3 % (2, 4, 33)\n    cols = [\"\\x1b[%sm\" % n for n in range(91, 96)]\n    red, green, yellow, blue, pink = cols\nelse:\n    ul = red = green = yellow = blue = pink = white = \"\"\n\nr, g, y, b, p, w = red, green, yellow, blue, pink, white\n\nansirx = re.compile(r'\\x1b\\[\\d*m', re.UNICODE)\n\ndef c(colour, text):\n    \"\"\" Return coloured text. \"\"\"\n    colours = {'r': r, 'g': g, 'y': y, 'b':b, 'p':p}\n    return colours[colour] + text + w\n\ndef charcount(s):\n    \"\"\" Return number of characters in string, with ANSI color codes excluded. \"\"\"\n    return len(ansirx.sub('', s))\n"
  },
  {
    "path": "mps_youtube/cache.py",
    "content": "import os\nimport pickle\n\n\nfrom . import g, c, streams\nfrom .util import dbg\n\n\n# Updated every time incompatible changes are made to cache format,\n# So old cache can be dropped\nCACHE_VERSION = 1\n\ndef load():\n    \"\"\" Import cache file. \"\"\"\n    if os.path.isfile(g.CACHEFILE):\n\n        try:\n\n            with open(g.CACHEFILE, \"rb\") as cf:\n                cached = pickle.load(cf)\n\n            # Note: will be none for yewtube 0.2.5 or earlier\n            version = cached.get('version')\n\n            if 'streams' in cached:\n                if version and version >= 1:\n                    g.streams = cached['streams']\n                    g.username_query_cache = cached['userdata']\n            else:\n                g.streams = cached\n\n            if 'pafy' in cached:\n                pass\n                #pafy.load_cache(cached['pafy'])\n\n            dbg(c.g + \"%s cached streams imported%s\", str(len(g.streams)), c.w)\n\n        except (EOFError, IOError):\n            dbg(c.r + \"Cache file failed to open\" + c.w)\n\n        streams.prune()\n\n\ndef save():\n    \"\"\" Save stream cache. \"\"\"\n    caches = dict(\n        version=CACHE_VERSION,\n        streams=g.streams,\n        userdata=g.username_query_cache\n        #,pafy=pafy.dump_cache()\n    )\n\n    with open(g.CACHEFILE, \"wb\") as cf:\n        pickle.dump(caches, cf, protocol=2)\n\n    dbg(c.p + \"saved cache file: \" + g.CACHEFILE + c.w)\n"
  },
  {
    "path": "mps_youtube/commands/__init__.py",
    "content": "import collections\nimport re\n\nfrom .. import g\nfrom ..main import completer\n\nCommand = collections.namedtuple('Command', 'regex category usage function')\n\n# input types\nWORD = r'[^\\W\\d][-\\w\\s]{,100}'\nRS = r'(?:(?:repeat|shuffle|-[avfw])\\s*)'\nPL = r'\\S*?((?:RD|PL|LL|UU|FL|OL)[-_0-9a-zA-Z]+)\\s*'\n\n## @command decorator\n##\n## The @command decorator takes a single regex followed by one or more\n## strings that corresponds to command names that will be added to\n## the tab completion.\n##\n## If your command has short-forms, only register the longer\n## forms.\n## If you use several functions and regexes for the same command but different\n## arguments, append the completion string on EACH function, not only\n## the first time you register it.\ndef command(regex, *commands):\n    \"\"\" Decorator to register an mps-youtube command. \"\"\"\n    for command in commands:\n        completer.add_cmd(command)\n    def decorator(function):\n        cmd = Command(re.compile(regex), None, None, function)\n        g.commands.append(cmd)\n        return function\n    return decorator\n\n\n# Placed at bottom to deal with cyclic imports\nfrom . import download, search, album_search, spotify_playlist, misc, config, local_playlist\nfrom . import play, songlist, generate_playlist, lastfm\n"
  },
  {
    "path": "mps_youtube/commands/album_search.py",
    "content": "import re\nimport time\nimport difflib\nfrom urllib.request import build_opener\nfrom urllib.error import HTTPError, URLError\nfrom urllib.parse import urlencode\nfrom xml.etree import ElementTree as ET\n\n\nfrom .. import c, g, screen, __version__, __url__, config, util, pafy\nfrom .. import content as content_py\nfrom . import command\nfrom .songlist import paginatesongs\nfrom .search import get_tracks_from_json\n\n\ndef show_message(message, col=c.r, update=False):\n    \"\"\" Show message using col, update screen if required. \"\"\"\n    g.content = content_py.generate_songlist_display()\n    g.message = col + message + c.w\n\n    if update:\n        screen.update()\n\n\ndef _do_query(url, query, err='query failed', report=False):\n    \"\"\" Perform http request using yewtube user agent header.\n\n    if report is True, return whether response is from memo\n\n    \"\"\"\n    # create url opener\n    ua = \"mps-youtube/%s ( %s )\" % (__version__, __url__)\n    mpsyt_opener = build_opener()\n    mpsyt_opener.addheaders = [('User-agent', ua)]\n\n    # convert query to sorted list of tuples (needed for consistent url_memo)\n    query = [(k, query[k]) for k in sorted(query.keys())]\n    url = \"%s?%s\" % (url, urlencode(query))\n\n    try:\n        wdata = mpsyt_opener.open(url).read().decode()\n\n    except (URLError, HTTPError) as e:\n        g.message = \"%s: %s (%s)\" % (err, e, url)\n        g.content = content_py.logo(c.r)\n        return None if not report else (None, False)\n\n    return wdata if not report else (wdata, False)\n\n\ndef _best_song_match(songs, title, duration, titleweight, durationweight):\n    \"\"\" Select best matching song based on title, length.\n\n    Score from 0 to 1 where 1 is best. titleweight and durationweight\n    parameters added to enable function usage when duration can't be guessed\n\n    \"\"\"\n    # pylint: disable=R0914\n    seqmatch = difflib.SequenceMatcher\n\n    def variance(a, b):\n        \"\"\" Return difference ratio. \"\"\"\n        return float(abs(a - b)) / max(a, b)\n\n    candidates = []\n\n    ignore = \"music video lyrics new lyrics video audio\".split()\n    extra = \"official original vevo\".split()\n\n    for song in songs:\n        dur, tit = int(song.length), song.title\n        util.dbg(\"Title: %s, Duration: %s\", tit, dur)\n\n        for word in extra:\n            if word in tit.lower() and word not in title.lower():\n                pattern = re.compile(word, re.I)\n                tit = pattern.sub(\"\", tit)\n\n        for word in ignore:\n            if word in tit.lower() and word not in title.lower():\n                pattern = re.compile(word, re.I)\n                tit = pattern.sub(\"\", tit)\n\n        replacechars = re.compile(r\"[\\]\\[\\)\\(\\-]\")\n        tit = replacechars.sub(\" \", tit)\n        multiple_spaces = re.compile(r\"(\\s)(\\s*)\")\n        tit = multiple_spaces.sub(r\"\\1\", tit)\n\n        title_score = seqmatch(None, title.lower(), tit.lower()).ratio()\n        duration_score = 1 - variance(duration, dur)\n        util.dbg(\"Title score: %s, Duration score: %s\", title_score,\n                 duration_score)\n\n        # apply weightings\n        score = duration_score * durationweight + title_score * titleweight\n        candidates.append((score, song))\n\n    best_score, best_song = max(candidates, key=lambda x: x[0])\n    percent_score = int(100 * best_score)\n    return best_song, percent_score\n\n\ndef _match_tracks(artist, title, mb_tracks):\n    \"\"\" Match list of tracks in mb_tracks by performing multiple searches. \"\"\"\n    # pylint: disable=R0914\n    util.dbg(\"artists is %s\", artist)\n    util.dbg(\"title is %s\", title)\n    title_artist_str = c.g + title + c.w, c.g + artist + c.w\n    util.xprint(\"\\nSearching for %s by %s\\n\\n\" % title_artist_str)\n\n    def dtime(x):\n        \"\"\" Format time to M:S. \"\"\"\n        return time.strftime('%M:%S', time.gmtime(int(x)))\n\n    # do matching\n    for track in mb_tracks:\n        ttitle = track['title']\n        length = track['length']\n        util.xprint(\"Search :  %s%s - %s%s - %s\" % (c.y, artist, ttitle, c.w,\n                                                    dtime(length)))\n        q = \"%s %s\" % (artist, ttitle)\n        w = q = ttitle if artist == \"Various Artists\" else q\n        query = w#generate_search_qs(w, 0)\n        util.dbg(query)\n\n        # perform fetch\n        wdata = pafy.search_videos(q, int(config.PAGES.get))  # pafy.call_gdata('search', query)\n        results = get_tracks_from_json(wdata)\n\n        if not results:\n            util.xprint(c.r + \"Nothing matched :(\\n\" + c.w)\n            continue\n\n        s, score = _best_song_match(\n            results, artist + \" \" + ttitle, length, .5, .5)\n        cc = c.g if score > 85 else c.y\n        cc = c.r if score < 75 else cc\n        util.xprint(\"Matched:  %s%s%s - %s \\n[%sMatch confidence: \"\n                    \"%s%s]\\n\" % (c.y, s.title, c.w, util.fmt_time(s.length),\n                                 cc, score, c.w))\n        yield s\n\n\ndef _get_mb_tracks(albumid):\n    \"\"\" Get track listing from MusicBraiz by album id. \"\"\"\n    ns = {'mb': 'http://musicbrainz.org/ns/mmd-2.0#'}\n    url = \"http://musicbrainz.org/ws/2/release/\" + albumid\n    query = {\"inc\": \"recordings\"}\n    wdata = _do_query(url, query, err='album search error')\n\n    if not wdata:\n        return None\n\n    root = ET.fromstring(wdata)\n    tlist = root.find(\"./mb:release/mb:medium-list/mb:medium/mb:track-list\",\n                      namespaces=ns)\n    mb_songs = tlist.findall(\"mb:track\", namespaces=ns)\n    tracks = []\n    path = \"./mb:recording/mb:\"\n\n    for track in mb_songs:\n\n        try:\n            title, length, rawlength = \"unknown\", 0, 0\n            title = track.find(path + \"title\", namespaces=ns).text\n            rawlength = track.find(path + \"length\", namespaces=ns).text\n            length = int(round(float(rawlength) / 1000))\n\n        except (ValueError, AttributeError):\n            util.xprint(\"not found\")\n\n        tracks.append(dict(title=title, length=length, rawlength=rawlength))\n\n    return tracks\n\n\ndef _get_mb_album(albumname, **kwa):\n    \"\"\" Return artist, album title and track count from MusicBrainz. \"\"\"\n    url = \"http://musicbrainz.org/ws/2/release/\"\n    qargs = dict(\n        release='\"%s\"' % albumname,\n        primarytype=kwa.get(\"primarytype\", \"album\"),\n        status=kwa.get(\"status\", \"official\"))\n    qargs.update({k: '\"%s\"' % v for k, v in kwa.items()})\n    qargs = [\"%s:%s\" % item for item in qargs.items()]\n    qargs = {\"query\": \" AND \".join(qargs)}\n    g.message = \"Album search for '%s%s%s'\" % (c.y, albumname, c.w)\n    wdata = _do_query(url, qargs)\n\n    if not wdata:\n        return None\n\n    ns = {'mb': 'http://musicbrainz.org/ns/mmd-2.0#'}\n    root = ET.fromstring(wdata)\n    rlist = root.find(\"mb:release-list\", namespaces=ns)\n\n    if int(rlist.get('count')) == 0:\n        return None\n\n    album = rlist.find(\"mb:release\", namespaces=ns)\n    artist = album.find(\"./mb:artist-credit/mb:name-credit/mb:artist\",\n                        namespaces=ns).find(\"mb:name\", namespaces=ns).text\n    title = album.find(\"mb:title\", namespaces=ns).text\n    aid = album.get('id')\n    return dict(artist=artist, title=title, aid=aid)\n\n\n@command(r'album\\s*(.{0,500})', 'album')\ndef search_album(term):\n    \"\"\"Search for albums. \"\"\"\n    # pylint: disable=R0914,R0912\n    if not term:\n        show_message(\"Enter album name:\", c.g, update=True)\n        term = input(\"> \")\n\n        if not term or len(term) < 2:\n            g.message = c.r + \"Not enough input!\" + c.w\n            g.content = content_py.generate_songlist_display()\n            return\n\n    album = _get_mb_album(term)\n\n    if not album:\n        show_message(\"Album '%s' not found!\" % term)\n        return\n\n    prompt = \"Artist? [%s] > \" % album['artist']\n    util.xprint(prompt, end=\"\")\n    artistentry = input().strip()\n\n    if artistentry:\n\n        if artistentry == \"q\":\n            show_message(\"Album search abandoned!\")\n            return\n\n        album = _get_mb_album(term, artist=artistentry)\n\n        if not album:\n            show_message(\"Album '%s' by '%s' not found!\" % (term, artistentry))\n            return\n\n    title, artist = album['title'], album['artist']\n    mb_tracks = _get_mb_tracks(album['aid'])\n\n    if not mb_tracks:\n        show_message(\"Album '%s' by '%s' has 0 tracks!\" % (title, artist))\n        return\n\n    msg = \"%s%s%s by %s%s%s\\n\\n\" % (c.g, title, c.w, c.g, artist, c.w)\n    msg += \"Enter to begin matching or [q] to abort\"\n    g.message = msg\n    g.content = \"Tracks:\\n\"\n    for n, track in enumerate(mb_tracks, 1):\n        g.content += \"%02s  %s\" % (n, track['title'])\n        g.content += \"\\n\"\n\n    screen.update()\n    entry = input(\"Continue? [Enter] > \")\n\n    if entry == \"\":\n        pass\n\n    else:\n        show_message(\"Album search abandoned!\")\n        return\n\n    songs = []\n    screen.clear()\n    itt = _match_tracks(artist, title, mb_tracks)\n\n    stash = config.SEARCH_MUSIC.get, config.ORDER.get\n    config.SEARCH_MUSIC.value = True\n    config.ORDER.value = \"relevance\"\n\n    try:\n        songs.extend(itt)\n\n    except KeyboardInterrupt:\n        util.xprint(\"%sHalted!%s\" % (c.r, c.w))\n\n    finally:\n        config.SEARCH_MUSIC.value, config.ORDER.value = stash\n\n    if songs:\n        util.xprint(\"\\n%s / %s songs matched\" % (len(songs), len(mb_tracks)))\n        input(\"Press Enter to continue\")\n        if g.lastfm_network:\n            g.artist = artist\n            g.album = title\n            g.scrobble = True\n            # Fill up queue with all the track names\n            g.scrobble_queue = [t['title'] for t in mb_tracks]\n\n    msg = \"Contents of album %s%s - %s%s %s(%d/%d)%s:\" % (\n        c.y, artist, title, c.w, c.b, len(songs), len(mb_tracks), c.w)\n    failmsg = \"Found no album tracks for %s%s%s\" % (c.y, title, c.w)\n\n    paginatesongs(songs, msg=msg, failmsg=failmsg)\n"
  },
  {
    "path": "mps_youtube/commands/config.py",
    "content": "from .. import g, c, config, util\nfrom . import command\n\n\n@command(r'set|showconfig', 'set', 'showconfig')\ndef showconfig():\n    \"\"\" Dump config data. \"\"\"\n    width = util.getxy().width\n    longest_key = 17\n    longest_val = 0\n    has_temps = False\n\n    for setting in config:\n        val = config[setting]\n        longest_val = max(longest_val, len(str(val.display)))\n        has_temps = has_temps or val.temp_value is not None\n\n    width -= 27\n    s = \"  %s%-{0}s%s : %-{1}s\".format(longest_key, longest_val+1)\n\n    if has_temps:\n        width -= longest_val + 5\n        out = \"  %s%-{}s   %-{}s %s%s%s\\n\".format(longest_key, longest_val) % (\n            c.ul, \"Key\", \"Value\", \"Temporary\", \" \" * width, c.w)\n    else:\n        out = \"  %s%-{}s   %s%s%s\\n\".format(longest_key) % (c.ul, \"Key\", \"Value\", \" \" * width, c.w)\n\n    for setting in config:\n        val = config[setting]\n\n        # don't show player specific settings if unknown player\n        if not util.is_known_player(config.PLAYER.get) and \\\n                val.require_known_player:\n            continue\n\n        # don't show max_results if auto determined\n        if g.detectable_size and setting == \"MAX_RESULTS\":\n            continue\n\n        if g.detectable_size and setting == \"CONSOLE_WIDTH\":\n            continue\n\n        out += s % (c.g, setting.lower(), c.w, val.display)\n\n        if has_temps:\n            out += \"%s%s\" % (c.w, val.display_temp)\n\n        out += \"\\n\"\n\n    g.content = out\n    g.message = \"Enter %sset <key> <value>%s to change\\n\" % (c.g, c.w)\n    g.message += \"Enter %sset all default%s to reset all\" % (c.g, c.w)\n\n\n@command(r'set\\s+-t\\s*([-\\w]+)\\s*(.*)')\ndef setconfigtemp(key, val):\n    setconfig(key, val, is_temp=True)\n\n\n@command(r'set\\s+([-\\w]+)\\s*(.*)')\ndef setconfig(key, val, is_temp=False):\n    \"\"\" Set configuration variable. \"\"\"\n    key = key.replace(\"-\", \"_\")\n    if key.upper() == \"ALL\" and val.upper() == \"DEFAULT\":\n\n        for ci in config:\n            config[ci].value = config[ci].default\n\n        config.save()\n        message = \"Default configuration reinstated\"\n\n    elif not key.upper() in config:\n        message = \"Unknown config item: %s%s%s\" % (c.r, key, c.w)\n\n    elif val.upper() == \"DEFAULT\":\n        att = config[key.upper()]\n        att.value = att.default\n        att.temp_value = None\n        message = \"%s%s%s set to %s%s%s (default)\"\n        dispval = att.display or \"None\"\n        message = message % (c.y, key, c.w, c.y, dispval, c.w)\n        config.save()\n\n    else:\n        # config.save() will be called by config.set() method\n        message = config[key.upper()].set(val, is_temp=is_temp)\n\n    showconfig()\n    g.message = message\n\n\n@command(r'encoders?', 'encoder')\ndef show_encs():\n    \"\"\" Display available encoding presets. \"\"\"\n    out = \"%sEncoding profiles:%s\\n\\n\" % (c.ul, c.w)\n\n    for x, e in enumerate(g.encoders):\n        sel = \" (%sselected%s)\" % (c.y, c.w) if config.ENCODER.get == x else \"\"\n        out += \"%2d. %s%s\\n\" % (x, e['name'], sel)\n\n    g.content = out\n    message = \"Enter %sset encoder <num>%s to select an encoder\"\n    g.message = message % (c.g, c.w)\n"
  },
  {
    "path": "mps_youtube/commands/download.py",
    "content": "import os\nimport re\nimport sys\nimport time\nimport shlex\nimport random\nimport subprocess\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\n\nfrom .. import g, c, screen, streams, content, config, util, pafy\nfrom . import command, PL\nfrom .search import yt_url, user_pls\nfrom .songlist import dump, plist\n\n\n@command(r'(dv|da|d|dl|download)\\s*(\\d{1,4})', 'da', 'dv', 'd', 'dl', 'download')\ndef download(dltype, num):\n    \"\"\" Download a track or playlist by menu item number. \"\"\"\n    # This function needs refactoring!\n    # pylint: disable=R0912\n    # pylint: disable=R0914\n    if g.browse_mode == \"ytpl\" and dltype in (\"da\", \"dv\"):\n        plid = g.ytpls[int(num) - 1][\"link\"]\n        down_plist(dltype, plid)\n        return\n\n    elif g.browse_mode == \"ytpl\":\n        g.message = \"Use da or dv to specify audio / video playlist download\"\n        g.message = c.y + g.message + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    elif g.browse_mode != \"normal\":\n        g.message = \"Download must refer to a specific video item\"\n        g.message = c.y + g.message + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    screen.writestatus(\"Fetching video info...\")\n    song = (g.model[int(num) - 1])\n\n    # best = dltype.startswith(\"dv\") or dltype.startswith(\"da\")\n    #\n    # if not best:\n    #\n    #     try:\n    #         # user prompt for download stream\n    #         url, ext, url_au, ext_au = prompt_dl(song)\n    #\n    #     except KeyboardInterrupt:\n    #         g.message = c.r + \"Download aborted!\" + c.w\n    #         g.content = content.generate_songlist_display()\n    #         return\n    #\n    #     if not url or ext_au == \"abort\":\n    #         # abort on invalid stream selection\n    #         g.content = content.generate_songlist_display()\n    #         g.message = \"%sNo download selected / invalid input%s\" % (c.y, c.w)\n    #         return\n    #\n    #     else:\n    #         # download user selected stream(s)\n    #         filename = _make_fname(song, ext)\n    #         args = (song, filename, url)\n    #\n    #         if url_au and ext_au:\n    #             # downloading video and audio stream for muxing\n    #             audio = False\n    #             filename_au = _make_fname(song, ext_au)\n    #             args_au = (song, filename_au, url_au)\n    #\n    #         else:\n    #             audio = ext in (\"m4a\", \"ogg\")\n    #\n    #         kwargs = dict(audio=audio)\n    #\n    # elif best:\n    #     # set updownload without prompt\n    #     url_au = None\n    #     av = \"audio\" if dltype.startswith(\"da\") else \"video\"\n    #     audio = av == \"audio\"\n    #     filename = _make_fname(song, None, av=av)\n    #     args = (song, filename)\n    #     kwargs = dict(url=None, audio=audio)\n\n    try:\n        # perform download(s)\n        # dl_filenames = [args[1]]\n        # f = _download(*args, **kwargs)\n        success = pafy.download_video(song.ytid, config.DDIR.get, True if dltype.startswith(\"da\") else False)\n        if success:\n            g.message = \"Saved \\'\" + song.title + \"\\' to \" + c.g + config.DDIR.get + c.w\n\n        # if url_au:\n        #     dl_filenames += [args_au[1]]\n        #     _download(*args_au, allow_transcode=False, **kwargs)\n\n    except KeyboardInterrupt:\n        g.message = c.r + \"Download halted!\" + c.w\n\n        # try:\n        #     for downloaded in dl_filenames:\n        #         os.remove(downloaded)\n        #\n        # except IOError:\n        #     pass\n\n    # if url_au:\n    #     # multiplex\n    #     name, ext = os.path.splitext(args[1])\n    #     tmpvideoname = name + '.' +str(random.randint(10000, 99999)) + ext\n    #     os.rename(args[1], tmpvideoname)\n    #     mux_cmd = [g.muxapp, \"-i\", tmpvideoname, \"-i\", args_au[1], \"-c\",\n    #                \"copy\", name + \".mp4\"]\n    #\n    #     try:\n    #         subprocess.call(mux_cmd)\n    #         g.message = \"Saved to :\" + c.g + mux_cmd[7] + c.w\n    #         os.remove(tmpvideoname)\n    #         os.remove(args_au[1])\n    #\n    #     except KeyboardInterrupt:\n    #         g.message = \"Audio/Video multiplex aborted!\"\n\n    g.content = content.generate_songlist_display()\n\n\n@command(r'(da|dv)\\s+((?:\\d+\\s\\d+|-\\d+|\\d+-|\\d+,)(?:[\\d\\s,-]*))', 'da', 'dv')\ndef down_many(dltype, choice, subdir=None):\n    \"\"\" Download multiple items. \"\"\"\n    choice = util.parse_multi(choice)\n    choice = list(set(choice))\n    downsongs = [g.model[int(x) - 1] for x in choice]\n    temp = g.model[::]\n    g.model.songs = downsongs[::]\n    count = len(downsongs)\n    av = \"audio\" if dltype.startswith(\"da\") else \"video\"\n    msg = \"\"\n\n    def handle_error(message):\n        \"\"\" Handle error in download. \"\"\"\n        g.message = message\n        g.content = disp\n        screen.update()\n        time.sleep(2)\n        g.model.songs.pop(0)\n\n    try:\n        for song in downsongs:\n            g.result_count = len(g.model)\n            disp = content.generate_songlist_display()\n            title = \"Download Queue (%s):%s\\n\\n\" % (av, c.w)\n            disp = re.sub(r\"(Num\\s*?Title.*?\\n)\", title, disp)\n            g.content = disp\n            screen.update()\n\n            try:\n                filename = _make_fname(song, None, av=av, subdir=subdir)\n\n            except IOError as e:\n                handle_error(\"Error for %s: %s\" % (song.title, str(e)))\n                count -= 1\n                continue\n\n            except KeyError:\n                handle_error(\"No audio track for %s\" % song.title)\n                count -= 1\n                continue\n\n            try:\n                _download(song, filename, url=None, audio=av == \"audio\")\n\n            except HTTPError:\n                handle_error(\"HTTP Error for %s\" % song.title)\n                count -= 1\n                continue\n\n            g.model.songs.pop(0)\n            msg = \"Downloaded %s items\" % count\n            g.message = \"Saved to \" + c.g + song.title + c.w\n\n    except KeyboardInterrupt:\n        msg = \"Downloads interrupted!\"\n\n    finally:\n        g.model.songs = temp[::]\n        g.message = msg\n        g.result_count = len(g.model)\n        g.content = content.generate_songlist_display()\n\n\n@command(r'(da|dv)pl\\s+%s' % PL, 'dapl', 'dvpl')\ndef down_plist(dltype, parturl):\n    \"\"\" Download YouTube playlist. \"\"\"\n\n    plist(parturl)\n    dump(False)\n    title = g.pafy_pls[parturl][0].title\n    # Remove double quotes for convenience\n    subdir = util.sanitize_filename(title.replace('\"', ''))\n    down_many(dltype, \"1-\", subdir=subdir)\n    msg = g.message\n    plist(parturl)\n    g.message = msg\n\n\n@command(r'(da|dv)upl\\s+(.*)', 'daupl', 'dvupl')\ndef down_user_pls(dltype, user):\n    \"\"\" Download all user playlists. \"\"\"\n    user_pls(user)\n    for i in g.ytpls:\n        down_plist(dltype, i.get('link'))\n\n    return\n\n\ndef _make_fname(song, ext=None, av=None, subdir=None):\n    \"\"\"\" Create download directory, generate filename. \"\"\"\n    # pylint: disable=E1103\n    # Instance of 'bool' has no 'extension' member (some types not inferable)\n    ddir = os.path.join(config.DDIR.get, subdir) if subdir else config.DDIR.get\n    if not os.path.exists(ddir):\n        os.makedirs(ddir)\n\n    if not ext:\n        stream = streams.select(streams.get(song),\n                audio=av == \"audio\", m4a_ok=True)\n        ext = stream['ext']\n\n    # filename = song.title[:59] + \".\" + ext\n    filename = song.title + \".\" + ext\n    # Remove double quotes for convenience\n    filename = filename.replace('\"', '')\n    filename = os.path.join(ddir, util.sanitize_filename(filename))\n    return filename\n\n\ndef extract_metadata(name):\n    \"\"\" Try to determine metadata from video title. \"\"\"\n    seps = name.count(\" - \")\n    artist = title = None\n\n    if seps == 1:\n\n        pos = name.find(\" - \")\n        artist = name[:pos].strip()\n        title = name[pos + 3:].strip()\n\n    else:\n        title = name.strip()\n\n    return dict(artist=artist, title=title)\n\n\ndef remux_audio(filename, title):\n    \"\"\" Remux audio file. Insert limited metadata tags. \"\"\"\n    util.dbg(\"starting remux\")\n    temp_file = filename + \".\" + str(random.randint(10000, 99999))\n    os.rename(filename, temp_file)\n    meta = extract_metadata(title)\n    metadata = [\"title=%s\" % meta[\"title\"]]\n\n    if meta[\"artist\"]:\n        metadata = [\"title=%s\" % meta[\"title\"], \"-metadata\",\n                    \"artist=%s\" % meta[\"artist\"]]\n\n    cmd = [g.muxapp, \"-y\", \"-i\", temp_file, \"-acodec\", \"copy\", \"-metadata\"]\n    cmd += metadata + [\"-vn\", filename]\n    util.dbg(cmd)\n\n    try:\n        with open(os.devnull, \"w\") as devnull:\n            subprocess.call(cmd, stdout=devnull, stderr=subprocess.STDOUT)\n\n    except OSError:\n        util.dbg(\"Failed to remux audio using %s\", g.muxapp)\n        os.rename(temp_file, filename)\n\n    else:\n        os.unlink(temp_file)\n        util.dbg(\"remuxed audio file using %s\" % g.muxapp)\n\n\ndef transcode(filename, enc_data):\n    \"\"\" Re encode a download. \"\"\"\n    base = os.path.splitext(filename)[0]\n    exe = g.muxapp if g.transcoder_path == \"auto\" else g.transcoder_path\n\n    # ensure valid executable\n    if not exe or not os.path.exists(exe) or not os.access(exe, os.X_OK):\n        util.xprint(\"Encoding failed. Couldn't find a valid encoder :(\\n\")\n        time.sleep(2)\n        return filename\n\n    command = shlex.split(enc_data['command'])\n    newcom, outfn = command[::], \"\"\n\n    for n, d in enumerate(command):\n\n        if d == \"ENCODER_PATH\":\n            newcom[n] = exe\n\n        elif d == \"IN\":\n            newcom[n] = filename\n\n        elif d == \"OUT\":\n            newcom[n] = outfn = base\n\n        elif d == \"OUT.EXT\":\n            newcom[n] = outfn = base + \".\" + enc_data['ext']\n\n    returncode = subprocess.call(newcom)\n\n    if returncode == 0 and g.delete_orig:\n        os.unlink(filename)\n\n    return outfn\n\n\ndef external_download(song, filename, url):\n    \"\"\" Perform download using external application. \"\"\"\n    cmd = config.DOWNLOAD_COMMAND.get\n    ddir, basename = config.DDIR.get, os.path.basename(filename)\n    cmd_list = shlex.split(cmd)\n\n    def list_string_sub(orig, repl, lst):\n        \"\"\" Replace substrings for items in a list. \"\"\"\n        return [x if orig not in x else x.replace(orig, repl) for x in lst]\n\n    cmd_list = list_string_sub(\"%F\", filename, cmd_list)\n    cmd_list = list_string_sub(\"%d\", ddir, cmd_list)\n    cmd_list = list_string_sub(\"%f\", basename, cmd_list)\n    cmd_list = list_string_sub(\"%u\", url, cmd_list)\n    cmd_list = list_string_sub(\"%i\", song.ytid, cmd_list)\n    util.dbg(\"Downloading using: %s\", \" \".join(cmd_list))\n    subprocess.call(cmd_list)\n\n\ndef _download(song, filename, url=None, audio=False, allow_transcode=True):\n    \"\"\" Download file, show status.\n\n    Return filename or None in case of user specified download command.\n\n    \"\"\"\n    # pylint: disable=R0914\n    # too many local variables\n    # Instance of 'bool' has no 'url' member (some types not inferable)\n\n    if not url:\n        stream = streams.select(streams.get(song), audio=audio, m4a_ok=True)\n        url = stream['url']\n\n    # if an external download command is set, use it\n    if config.DOWNLOAD_COMMAND.get:\n        title = c.y + os.path.splitext(os.path.basename(filename))[0] + c.w\n        util.xprint(\"Downloading %s using custom command\" % title)\n        external_download(song, filename, url)\n        return None\n\n    if not config.OVERWRITE.get:\n        if os.path.exists(filename):\n            util.xprint(\"File exists. Skipping %s%s%s ..\\n\" %\n                    (c.r, filename, c.w))\n            time.sleep(0.2)\n            return filename\n\n    util.xprint(\"Downloading to %s%s%s ..\" % (c.r, filename, c.w))\n    status_string = ('  {0}{1:,}{2} Bytes [{0}{3:.2%}{2}] received. Rate: '\n                     '[{0}{4:4.0f} kbps{2}].  ETA: [{0}{5:.0f} secs{2}]')\n\n    resp = urlopen(url)\n    total = int(resp.info()['Content-Length'].strip())\n    chunksize, bytesdone, t0 = 16384, 0, time.time()\n    outfh = open(filename, 'wb')\n\n    while True:\n        chunk = resp.read(chunksize)\n        outfh.write(chunk)\n        elapsed = time.time() - t0\n        bytesdone += len(chunk)\n        rate = 0\n        if elapsed != 0:\n            rate = (bytesdone / 1024) / elapsed\n        if rate:\n            eta = (total - bytesdone) / (rate * 1024)\n        else:\n            eta = 0\n        stats = (c.y, bytesdone, c.w, bytesdone * 1.0 / total, rate, eta)\n\n        if not chunk:\n            outfh.close()\n            break\n\n        status = status_string.format(*stats)\n        sys.stdout.write(\"\\r\" + status + ' ' * 4 + \"\\r\")\n        sys.stdout.flush()\n\n    active_encoder = g.encoders[config.ENCODER.get]\n    ext = filename.split(\".\")[-1]\n    valid_ext = ext in active_encoder['valid'].split(\",\")\n\n    if audio and g.muxapp:\n        remux_audio(filename, song.title)\n\n    if config.ENCODER.get != 0 and valid_ext and allow_transcode:\n        filename = transcode(filename, active_encoder)\n\n    return filename\n\n\ndef menu_prompt(model, prompt=\" > \", rows=None, header=None, theading=None,\n                footer=None, force=0):\n    \"\"\" Generate a list of choice, returns item from model. \"\"\"\n    content = \"\"\n\n    for x in header, theading, rows, footer:\n        if isinstance(x, list):\n\n            for line in x:\n                content += line + \"\\n\"\n\n        elif isinstance(x, str):\n            content += x + \"\\n\"\n\n    g.content = content\n    screen.update()\n\n    choice = input(prompt)\n\n    if choice in model:\n        return model[choice]\n\n    elif force:\n        return menu_prompt(model, prompt, rows, header, theading, footer,\n                           force)\n\n    elif not choice.strip():\n        return False, False\n\n    else:  # unrecognised input\n        return False, \"abort\"\n\n\ndef prompt_dl(song):\n    \"\"\" Prompt user do choose a stream to dl.  Return (url, extension). \"\"\"\n    # pylint: disable=R0914\n    dl_data, p = get_dl_data(song)\n    dl_text = gen_dl_text(dl_data, song, p)\n\n    model = [x['url'] for x in dl_data]\n    ed = enumerate(dl_data)\n    model = {str(n + 1): (x['url'], x['ext']) for n, x in ed}\n    url, ext = menu_prompt(model, \"Download number: \", *dl_text)\n    url2 = ext2 = None\n    mediatype = [i for i in dl_data if i['url'] == url][0]['mediatype']\n\n    if mediatype == \"video\" and g.muxapp and not config.DOWNLOAD_COMMAND.get:\n        # offer mux if not using external downloader\n        dl_data, p = get_dl_data(song, mediatype=\"audio\")\n        dl_text = gen_dl_text(dl_data, song, p)\n        au_choices = \"1\" if len(dl_data) == 1 else \"1-%s\" % len(dl_data)\n        footer = [util.F('-audio') % ext, util.F('select mux') % au_choices]\n        dl_text = tuple(dl_text[0:3]) + (footer,)\n        aext = (\"ogg\", \"m4a\")\n        model = [x['url'] for x in dl_data if x['ext'] in aext]\n        ed = enumerate(dl_data)\n        model = {str(n + 1): (x['url'], x['ext']) for n, x in ed}\n        prompt = \"Audio stream: \"\n        url2, ext2 = menu_prompt(model, prompt, *dl_text)\n\n    return url, ext, url2, ext2\n\n\ndef gen_dl_text(ddata, song, p):\n    \"\"\" Generate text for dl screen. \"\"\"\n    hdr = []\n    hdr.append(\"  %s%s%s\" % (c.r, song.title, c.w))\n    author = p.author\n    hdr.append(c.r + \"  Uploaded by \" + author + c.w)\n    hdr.append(\"  [\" + util.fmt_time(song.length) + \"]\")\n    hdr.append(\"\")\n\n    heading = tuple(\"Item Format Quality Media Size Notes\".split())\n    fmt = \"  {0}%-6s %-8s %-13s %-7s   %-5s   %-16s{1}\"\n    heading = [fmt.format(c.w, c.w) % heading]\n    heading.append(\"\")\n\n    content = []\n\n    for n, d in enumerate(ddata):\n        row = (n + 1, d['ext'], d['quality'], d['mediatype'], d['size'],\n               d['notes'])\n        fmt = \"  {0}%-6s %-8s %-13s %-7s %5s Mb   %-16s{1}\"\n        row = fmt.format(c.g, c.w) % row\n        content.append(row)\n\n    content.append(\"\")\n\n    footer = \"Select [%s1-%s%s] to download or [%sEnter%s] to return\"\n    footer = [footer % (c.y, len(content) - 1, c.w, c.y, c.w)]\n    return(content, hdr, heading, footer)\n\n\ndef get_dl_data(song, mediatype=\"any\"):\n    \"\"\" Get filesize and metadata for all streams, return dict. \"\"\"\n    def mbsize(x):\n        \"\"\" Return size in MB. \"\"\"\n        return str(int(x / (1024 ** 2)))\n\n    p = util.get_pafy(song)\n    dldata = []\n    text = \" [Fetching stream info] >\"\n    streamlist = [x for x in p.allstreams]\n\n    if mediatype == \"audio\":\n        streamlist = [x for x in p.audiostreams]\n\n    l = len(streamlist)\n    for n, stream in enumerate(streamlist):\n        sys.stdout.write(text + \"-\" * n + \">\" + \" \" * (l - n - 1) + \"<\\r\")\n        sys.stdout.flush()\n\n        try:\n            size = mbsize(stream.get_filesize())\n\n        except TypeError:\n            util.dbg(c.r + \"---Error getting stream size\" + c.w)\n            size = 0\n\n        item = {'mediatype': stream.mediatype,\n                'size': size,\n                'ext': stream.extension,\n                'quality': stream.quality,\n                'notes': stream.notes,\n                'url': stream.url}\n\n        dldata.append(item)\n\n    screen.writestatus(\"\")\n    return dldata, p\n\n\n@command(r'dlurl\\s(.*[-_a-zA-Z0-9]{11}.*)', 'dlurl')\ndef dl_url(url):\n    \"\"\" Open and prompt for download of youtube video url. \"\"\"\n    g.browse_mode = \"normal\"\n    yt_url(url)\n\n    if len(g.model) == 1:\n        download(\"download\", \"1\")\n\n    if g.command_line:\n        sys.exit()\n\n\n@command(r'daurl\\s(.*[-_a-zA-Z0-9]{11}.*)', 'daurl')\ndef da_url(url):\n    \"\"\" Open and prompt for download of youtube best audio from url. \"\"\"\n    g.browse_mode = \"normal\"\n    yt_url(url)\n\n    if len(g.model) == 1:\n        download(\"da\", \"1\")\n\n    if g.command_line:\n        sys.exit()\n"
  },
  {
    "path": "mps_youtube/commands/generate_playlist.py",
    "content": "\"\"\"\n    Playlist Generation\n\"\"\"\nfrom os import path\nfrom random import choice\nimport string\n\nfrom .. import content, g, playlists, screen, util, listview\nfrom ..playlist import Playlist\nfrom . import command, search, album_search\n\n\n@command(r'mkp\\s*(.{1,100})', 'mkp')\ndef generate_playlist(sourcefile):\n    \"\"\"Generate a playlist from video titles in sourcefile\"\"\"\n\n    # Hooks into this, check if the argument --description is present\n    if \"--description\" in sourcefile or \"-d\" in sourcefile:\n        description_generator(sourcefile)\n        return\n\n    expanded_sourcefile = path.expanduser(sourcefile)\n    if not check_sourcefile(expanded_sourcefile):\n        g.message = util.F('mkp empty') % expanded_sourcefile\n    else:\n        queries = read_sourcefile(expanded_sourcefile)\n        g.message = util.F('mkp parsed') % (len(queries), sourcefile)\n        if queries:\n            create_playlist(queries)\n            g.message = util.F('pl help')\n            g.content = content.playlists_display()\n\n\ndef read_sourcefile(filename):\n    \"\"\"Read each line as a query from filename\"\"\"\n    with open(filename) as srcfl:\n        queries = list()\n        for item in srcfl.readlines():\n            clean_item = str(item).strip()\n            if not clean_item:\n                continue\n            queries.append(clean_item)\n        return queries\n\n\ndef check_sourcefile(filename):\n    \"\"\"Check if filename exists and has a non-zero size\"\"\"\n    return path.isfile(filename) and path.getsize(filename) > 0\n\n\ndef create_playlist(queries, title=''):\n    \"\"\"Add a new playlist\n\n    Create playlist with a random name, get the first\n    match for each title in queries and append it to the playlist\n    \"\"\"\n    plname = title.replace(\" \", \"-\") or random_plname()\n    if not g.userpl.get(plname):\n        g.userpl[plname] = Playlist(plname)\n    for query in queries:\n        g.message = util.F('mkp finding') % query\n        screen.update()\n        qresult = find_best_match(query)\n        if qresult:\n            g.userpl[plname].songs.append(qresult)\n    if g.userpl[plname]:\n        playlists.save()\n\n\ndef find_best_match(query):\n    \"\"\"Find the best(first)\"\"\"\n    # This assumes that the first match is the best one\n    qs = search.generate_search_qs(query)\n    wdata = pafy.call_gdata('search', qs)\n    results = search.get_tracks_from_json(wdata)\n    if results:\n        res, score = album_search._best_song_match(\n            results, query, 0.1, 1.0, 0.0)\n        return res\n\n\ndef random_plname():\n    \"\"\"Generates a random alphanumeric string of 6 characters\"\"\"\n    n_chars = 6\n    return ''.join(choice(string.ascii_lowercase + string.digits)\n                   for _ in range(n_chars))\n\n\ndef description_generator(text):\n    \"\"\" Fetches a videos description and parses it for\n        <artist> - <track> combinations\n    \"\"\"\n    if not isinstance(g.model, Playlist):\n        g.message = util.F(\"mkp desc unknown\")\n        return\n\n    # Use only the first result, for now\n    num = text.replace(\"--description\", \"\")\n    num = num.replace(\"-d\", \"\")\n    num = util.number_string_to_list(num)[0]\n\n    query = {}\n    query['id'] = g.model[num].ytid\n    query['part'] = 'snippet'\n    query['maxResults'] = '1'\n    data = pafy.call_gdata('videos', query)['items'][0]['snippet']\n    title = \"mkp %s\" % data['title']\n    data = util.fetch_songs(data['description'], data['title'])\n\n    columns = [\n        {\"name\": \"idx\", \"size\": 3, \"heading\": \"Num\"},\n        {\"name\": \"artist\", \"size\": 30, \"heading\": \"Artist\"},\n        {\"name\": \"title\", \"size\": \"remaining\", \"heading\": \"Title\"},\n    ]\n\n    def run_m(idx):\n        \"\"\" Create playlist based on the\n            results selected\n        \"\"\"\n        create_playlist(idx, title)\n\n    if data:\n        data = [listview.ListSongtitle(x) for x in data]\n        g.content = listview.ListView(columns, data, run_m)\n        g.message = util.F(\"mkp desc which data\")\n    else:\n        g.message = util.F(\"mkp no valid\")\n\n    return\n"
  },
  {
    "path": "mps_youtube/commands/lastfm.py",
    "content": "import time\nimport datetime\n\ntry:\n    import pylast\n    has_pylast = True\nexcept ImportError:\n    has_pylast = False\n\nfrom .. import g, util, config\nfrom . import command\n\n@command(r'lastfm_connect', 'lastfm_connect')\ndef init_network(verbose=True):\n    \"\"\" Initialize the global pylast network variable \"\"\"\n    if not has_pylast :\n        if verbose:\n            pylast_url = 'https://github.com/pylast/pylast'\n            g.message = '\"pylast\" module not found\\n see %s' % (pylast_url)\n        return\n\n    # TODO: Add option to read lastfm config from file or env variable\n    key = config.LASTFM_API_KEY.get\n    secret = config.LASTFM_API_SECRET.get\n    password = config.LASTFM_PASSWORD.get # already hashed\n    username = config.LASTFM_USERNAME.get\n\n    if not (key and secret and password and username):\n        if verbose:\n            util.xprint(\"Not all Last.fm credentials were set.\")\n        return\n\n    try:\n        g.lastfm_network = pylast.LastFMNetwork(api_key=key, api_secret=secret,\n                                                username=username,\n                                                password_hash=password)\n        if verbose:\n            g.message = \"Last.fm authentication successful!\"\n    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError) as e:\n        if verbose:\n            g.message = \"Last.fm connection error: %s\" % (str(e))\n\ndef scrobble_track(artist, album, track):\n    \"\"\" Scrobble a track to the user's Last.fm account \"\"\"\n    if not g.lastfm_network:\n        return\n    unix_timestamp = int(time.mktime(datetime.datetime.now().timetuple()))\n    try:\n        g.lastfm_network.scrobble(artist=artist, title=track, album=album,\n                                  timestamp=unix_timestamp)\n    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError):\n        return\n\ndef set_now_playing(artist, track):\n    \"\"\" Set the current track as \"now playing\" on the user's Last.fm account \"\"\"\n    if not g.lastfm_network:\n        return\n    try:\n        g.lastfm_network.update_now_playing(artist=artist, title=track)\n    except (pylast.WSError, pylast.MalformedResponseError, pylast.NetworkError):\n        return\n"
  },
  {
    "path": "mps_youtube/commands/local_playlist.py",
    "content": "import re\n\nfrom .. import g, c, playlists, content, util\nfrom ..playlist import Playlist, Video\nfrom . import command, WORD\nfrom .songlist import paginatesongs, songlist_rm_add\nfrom ..util import parse_video_length\n\n\n@command(r'rmp\\s*(\\d+|%s)' % WORD, 'rmp')\ndef playlist_remove(name):\n    \"\"\" Delete a saved playlist by name - or purge working playlist if *all.\"\"\"\n    if name.isdigit() or g.userpl.get(name):\n\n        if name.isdigit():\n            name = int(name) - 1\n            name = sorted(g.userpl)[name]\n\n        playlists.delete(name)\n        g.message = \"Deleted playlist %s%s%s\" % (c.y, name, c.w)\n        g.content = content.playlists_display()\n        #playlists.save()\n\n    else:\n        g.message = util.F('pl not found advise ls') % name\n        g.content = content.playlists_display()\n\n\n@command(r'add\\s*(-?\\d[-,\\d\\s]{1,250})(%s)' % WORD, 'add')\ndef playlist_add(nums, playlist):\n    \"\"\" Add selected song nums to saved playlist. \"\"\"\n    nums = util.parse_multi(nums)\n    # Replacing spaces with hyphens before checking if playlist already exist.\n    # See https://github.com/mps-youtube/mps-youtube/issues/1046.\n    playlist = playlist.replace(\" \", \"-\")\n\n    if not g.userpl.get(playlist):\n        g.userpl[playlist] = Playlist(playlist)\n\n    for songnum in nums:\n        g.userpl[playlist].songs.append(g.model[songnum - 1])\n        dur = g.userpl[playlist].duration\n        f = (len(nums), playlist, len(g.userpl[playlist]), dur)\n        g.message = util.F('added to saved pl') % f\n\n    if nums:\n        playlists.save()\n\n    g.content = content.generate_songlist_display()\n\n\n@command(r'mv\\s*(\\d{1,3})\\s*(%s)' % WORD, 'mv')\ndef playlist_rename_idx(_id, name):\n    \"\"\" Rename a playlist by ID. \"\"\"\n    _id = int(_id) - 1\n    playlist_rename(sorted(g.userpl)[_id] + \" \" + name)\n\n\n@command(r'mv\\s*(%s\\s+%s)' % (WORD, WORD), 'mv')\ndef playlist_rename(playlists_):\n    \"\"\" Rename a playlist using mv command. \"\"\"\n    # Deal with old playlist names that permitted spaces\n    a, b = \"\", playlists_.split(\" \")\n    while a not in g.userpl:\n        a = (a + \" \" + (b.pop(0))).strip()\n        if not b and a not in g.userpl:\n            g.message = util.F('no pl match for rename')\n            g.content = g.content or content.playlists_display()\n            return\n\n    b = \"-\".join(b)\n    g.userpl[b] = Playlist(b)\n    g.userpl[b].songs = list(g.userpl[a].songs)\n    playlist_remove(a)\n    g.message = util.F('pl renamed') % (a, b)\n    playlists.save()\n\n\n@command(r'(rm|add)\\s(?:\\*|all)', 'rm', 'add')\ndef add_rm_all(action):\n    \"\"\" Add all displayed songs to current playlist.\n\n    remove all displayed songs from view.\n\n    \"\"\"\n    if action == \"rm\":\n        g.model.songs.clear()\n        msg = c.b + \"Cleared all songs\" + c.w\n        g.content = content.generate_songlist_display(zeromsg=msg)\n\n    elif action == \"add\":\n        size = len(g.model)\n        songlist_rm_add(\"add\", \"-\" + str(size))\n\n\n@command(r'save', 'save')\ndef save_last():\n    \"\"\" Save command with no playlist name. \"\"\"\n    if g.last_opened:\n        open_save_view(\"save\", g.last_opened)\n\n    else:\n        saveas = \"\"\n\n        # save using artist name in postion 1\n        if g.model:\n            if g.selected_pafy_pls_id: # if a playlist was selected\n                saveas = g.pafy_pls[g.selected_pafy_pls_id][0].info['info']['title']\n            else: # user didn't selected a playlist\n                saveas = g.model[0].title[:18].strip()\n            saveas = re.sub(r\"[^-\\w]\", \"-\", saveas, flags=re.UNICODE)\n\n        # loop to find next available name\n        post = 0\n\n        while g.userpl.get(saveas):\n            post += 1\n            saveas = g.model[0].title[:18].strip() + \"-\" + str(post)\n\n        # Playlists are not allowed to start with a digit\n        # TODO: Possibly change this, but ban purely numerical names\n        saveas = saveas.lstrip(\"0123456789\")\n\n        open_save_view(\"save\", saveas)\n\n\n@command(r'(open|save|view)\\s*(%s)' % WORD, 'open', 'save', 'view')\ndef open_save_view(action, name):\n    \"\"\" Open, save or view a playlist by name.  Get closest name match. \"\"\"\n    name = name.replace(\" \", \"-\")\n    if action == \"open\" or action == \"view\":\n        saved = g.userpl.get(name)\n\n        if not saved:\n            name = util.get_near_name(name, g.userpl)\n            saved = g.userpl.get(name)\n\n        elif action == \"open\":\n            g.active.songs = list(saved.songs)\n            g.last_opened = name\n            msg = util.F(\"pl loaded\") % name\n            paginatesongs(g.active, msg=msg)\n\n        elif action == \"view\":\n            g.last_opened = \"\"\n            msg = util.F(\"pl viewed\") % name\n            paginatesongs(list(saved.songs), msg=msg)\n\n        elif not saved and action in \"view open\".split():\n            g.message = util.F(\"pl not found\") % name\n            g.content = content.playlists_display()\n\n    elif action == \"save\":\n        if not g.model:\n            g.message = \"Nothing to save. \" + util.F('advise search')\n            g.content = content.generate_songlist_display()\n\n        else:\n            if g.selected_pafy_pls_id: # if a playlist was selected by user:\n                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])\n            else: # user created custom playlist and never opened it and now wants to save it\n                g.userpl[name] = Playlist(name, list(g.model.songs))\n            g.message = util.F('pl saved') % name\n            playlists.save()\n            g.content = content.generate_songlist_display()\n\n\n@command(r'(open|view)\\s*(\\d{1,4})', 'open', 'view')\ndef open_view_bynum(action, num):\n    \"\"\" Open or view a saved playlist by number. \"\"\"\n    srt = sorted(g.userpl)\n    name = srt[int(num) - 1]\n    open_save_view(action, name)\n\n\n@command(r'ls', 'ls')\ndef ls():\n    \"\"\" List user saved playlists. \"\"\"\n    if not g.userpl:\n        g.message = util.F('no playlists')\n        g.content = g.content or \\\n                content.generate_songlist_display(zeromsg=g.message)\n\n    else:\n        g.content = content.playlists_display()\n        g.message = util.F('pl help')\n\n\n@command(r'vp', 'vp')\ndef vp():\n    \"\"\" View current working playlist. \"\"\"\n\n    msg = util.F('current pl')\n    txt = util.F('advise add') if g.model else util.F('advise search')\n    failmsg = util.F('pl empty') + \" \" + txt\n\n    paginatesongs(g.active, msg=msg, failmsg=failmsg)\n"
  },
  {
    "path": "mps_youtube/commands/misc.py",
    "content": "import re\nfrom datetime import datetime, timedelta\nimport socket\nimport traceback\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError, URLError\nfrom .. import player\n\ntry:\n    # pylint: disable=F0401\n    import pyperclip\n    has_pyperclip = True\n\nexcept ImportError:\n    has_pyperclip = False\n\ntry:\n    import readline\n    has_readline = True\nexcept ImportError:\n    has_readline = False\n\nfrom .. import g, c, __version__, content, screen, cache, pafy\nfrom .. import streams, history, config, util\nfrom ..helptext import get_help\nfrom ..content import generate_songlist_display, logo, qrcode_display\nfrom . import command\nfrom .songlist import paginatesongs\n\n\n@command(r'clearcache')\ndef clearcache():\n    \"\"\" Clear cached items - for debugging use. \"\"\"\n    g.pafs = {}\n    g.streams = {}\n    util.dbg(\"%scache cleared%s\", c.p, c.w)\n    g.message = \"cache cleared\"\n\n\n@command(r'(?:help|h)(?:\\s+([-_a-zA-Z]+))?', 'help')\ndef show_help(choice):\n    \"\"\" Print help message. \"\"\"\n\n    g.content = get_help(choice)\n\n\n@command(r'(?:q|quit|exit)', 'quit', 'exit')\ndef quits(showlogo=True):\n    \"\"\" Exit the program. \"\"\"\n    if has_readline and config.INPUT_HISTORY.get:\n        readline.write_history_file(g.READLINE_FILE)\n        util.dbg(\"Saved history file\")\n\n    cache.save()\n\n    screen.clear()\n    msg = logo(c.r, version=__version__) if showlogo else \"\"\n    msg += util.F(\"exitmsg\", 2)\n\n    if config.CHECKUPDATE.get and showlogo:\n\n        try:\n            url = \"https://raw.githubusercontent.com/iamtalhaasghar/yewtube/master/setup.py\"\n            v = urlopen(url, timeout=1).read().decode()\n            v = re.search(r'__version__\\s*=\\s*\"\\s*([\\d\\.]+)\\s*\"\\s*', v, re.MULTILINE)\n\n            if v:\n                v = v.group(1)\n\n                if v > __version__:\n                    msg += \"\\n\\nA newer version is available (%s). Use `help new` command to check what's changed.\\n\" % v\n\n        except (URLError, HTTPError, socket.timeout):\n            util.dbg(\"check update timed out\")\n\n    screen.msgexit(msg)\n\ndef _format_comment(n, qnt, author_name, published_date, content, reply=False):\n    # poster = snippet.get('authorDisplayName')\n    # shortdate = util.yt_datetime(snippet.get('publishedAt', ''))[1]\n    # text = snippet.get('textDisplay', '')\n    cid = (\"%s%s/%s %s\" % ('└── ' if reply else '', n, qnt, c.c(\"g\", author_name)))\n    return (\"%-39s %s\\n\" % (cid, published_date)) + \\\n            c.c(\"y\", content.strip()) + '\\n\\n'\n\ndef _fetch_commentreplies(parentid):\n    # return pafy.call_gdata('comments', {\n    #     'parentId': parentid,\n    #     'part': 'snippet',\n    #     'textFormat': 'plainText',\n    #     'maxResults': 50}).get('items', [])\n    return None\ndef fetch_comments(item):\n    \"\"\" Fetch comments for item using gdata. \"\"\"\n    # pylint: disable=R0912\n    # pylint: disable=R0914\n    ytid, title = item.ytid, item.title\n    util.dbg(\"Fetching comments for %s\", c.c(\"y\", ytid))\n    screen.writestatus(\"Fetching comments for %s\" % c.c(\"y\", title[:55]))\n    # qs = {'textFormat': 'plainText',\n    #       'videoId': ytid,\n    #       'maxResults': 50,\n    #       'part': 'snippet'}\n\n    # jsdata = None\n    try:\n        all_comments = pafy.get_comments(ytid)\n    except Exception:\n        raise\n    # coms = [x.get('snippet', {}) for x in jsdata.get('items', [])]\n\n    # skip blanks\n    # coms = [x for x in coms\n    #         if len(x.get('topLevelComment', {}).get('snippet', {}).get('textDisplay', '').strip())]\n\n    if not len(all_comments):\n        g.message = \"No comments for %s\" % item.title[:50]\n        g.content = generate_songlist_display()\n        return\n\n    commentstext = ''\n\n    for n, com in enumerate(all_comments, 1):\n        # snippet = com.get('topLevelComment', {}).get('snippet', {})\n        commentstext += _format_comment(n, len(all_comments), com['author']['name'], com['published'], com['content'])\n        # todo fetch comment replies\n        # if com.get('replyCount') > 0:\n        #     replies = _fetch_commentreplies(com.get('topLevelComment').get('id'))\n        #     for n, com in enumerate(reversed(replies), 1):\n        #         commentstext += _format_comment(com.get('snippet', {}),\n        #                                         n, len(replies), True)\n\n    g.current_page = 0\n    g.content = content.StringContent(commentstext)\n\n\n@command(r'c\\s?(\\d{1,4})', 'c')\ndef comments(number):\n    \"\"\" Receive use request to view comments. \"\"\"\n    if g.browse_mode == \"normal\":\n        item = g.model[int(number) - 1]\n        fetch_comments(item)\n\n    else:\n        g.content = generate_songlist_display()\n        g.message = \"Comments only available for video items\"\n\n\n@command(r'x\\s*(\\d+)', 'x')\ndef clipcopy_video(num):\n    \"\"\" Copy video/playlist url to clipboard. \"\"\"\n    if g.browse_mode == \"ytpl\":\n\n        p = g.ytpls[int(num) - 1]\n        link = \"https://youtube.com/playlist?list=%s\" % p['link']\n\n    elif g.browse_mode == \"normal\":\n        item = (g.model[int(num) - 1])\n        link = \"https://youtube.com/watch?v=%s\" % item.ytid\n\n    else:\n        g.message = \"clipboard copy not valid in this mode\"\n        g.content = generate_songlist_display()\n        return\n\n    if has_pyperclip:\n\n        try:\n            pyperclip.copy(link)\n            g.message = c.y + link + c.w + \" copied\"\n            g.content = generate_songlist_display()\n\n        except Exception as e:\n            g.content = generate_songlist_display()\n            g.message = link + \"\\nError - couldn't copy to clipboard.\\n\" + \\\n                    ''.join(traceback.format_exception_only(type(e), e))\n\n    else:\n        g.message = \"pyperclip module must be installed for clipboard support\\n\"\n        g.message += \"see https://pypi.python.org/pypi/pyperclip/\"\n        g.content = generate_songlist_display()\n\n\n@command(r'X\\s*(\\d+)', 'X')\ndef clipcopy_stream(num):\n    \"\"\" Copy content stream url to clipboard. \"\"\"\n    if g.browse_mode == \"normal\":\n\n        item = (g.model[int(num) - 1])\n        details = player.stream_details(item)[1]\n        stream = details['url']\n\n    else:\n        g.message = \"clipboard copy not valid in this mode\"\n        g.content = generate_songlist_display()\n        return\n\n    if has_pyperclip:\n\n        try:\n            pyperclip.copy(stream)\n            g.message = c.y + stream + c.w + \" copied\"\n            g.content = generate_songlist_display()\n\n        except Exception as e:\n            g.content = generate_songlist_display()\n            g.message = stream + \"\\nError - couldn't copy to clipboard.\\n\" + \\\n                    ''.join(traceback.format_exception_only(type(e), e))\n\n    else:\n        g.message = \"pyperclip module must be installed for clipboard support\\n\"\n        g.message += \"see https://pypi.python.org/pypi/pyperclip/\"\n        g.content = generate_songlist_display()\n\n\n@command(r'i\\s*(\\d{1,4})', 'i')\ndef video_info(num):\n    \"\"\" Get video information. \"\"\"\n    if g.browse_mode == \"ytpl\":\n        p = g.ytpls[int(num) - 1]\n\n        # fetch the playlist item as it has more metadata\n        if p['link'] in g.pafy_pls:\n            ytpl = g.pafy_pls[p['link']][0]\n        else:\n            g.content = logo(col=c.g)\n            g.message = \"Fetching playlist info..\"\n            screen.update()\n            util.dbg(\"%sFetching playlist using pafy%s\", c.y, c.w)\n            ytpl = pafy.get_playlist2(p['link'])\n            g.pafy_pls[p['link']] = (ytpl, util.IterSlicer(ytpl))\n\n        ytpl_desc = ytpl.description\n        g.content = generate_songlist_display()\n        created = util.yt_datetime_local(p['created'])\n        updated = util.yt_datetime_local(p['updated'])\n        out = c.ul + \"Playlist Info\" + c.w + \"\\n\\n\"\n        out += p['title']\n        out += \"\\n\" + ytpl_desc\n        out += (\"\\n\\nAuthor     : \" + p['author'])\n        out += \"\\nSize       : \" + str(p['size']) + \" videos\"\n        out += \"\\nCreated    : \" + created[1] + \" \" + created[2]\n        out += \"\\nUpdated    : \" + updated[1] + \" \" + updated[2]\n        out += \"\\nID         : \" + str(p['link'])\n        out += (\"\\n\\n%s[%sPress enter to go back%s]%s\" % (c.y, c.w, c.y, c.w))\n        g.content = out\n\n    elif g.browse_mode == \"normal\":\n        g.content = logo(c.b)\n        screen.update()\n        screen.writestatus(\"Fetching video metadata..\")\n        item = (g.model[int(num) - 1])\n        streams.get(item)\n        p = pafy.get_video_info(item.ytid)\n        #pub = datetime.strptime(str(p.published), \"%Y-%m-%d %H:%M:%SZ\")\n        #pub = util.utc2local(pub)\n        screen.writestatus(\"Fetched\")\n        out = c.ul + \"Video Info\" + c.w + \"\\n\\n\"\n        out += p['title'] or \"\"\n        out += \"\\n\\nDescription:\\n\\n\" + str(p.get('description', \"\")) + \"\\n\"\n        out += \"\\nKeywords: \" + str(p['keywords']) + \"\\n\"\n        out += \"\\nIs Live Now    : \" + str(p['isLiveNow'])\n        out += \"\\nDuration       : \" + str(timedelta(seconds=int(p['duration']['secondsText'])))\n        out += \"\\nView count     : \" + \"{:,}\".format(int(p['viewCount']['text']))\n        out += \"\\nAuthor         : \" + str(p['channel']['name'] + ' ~ ' + p['channel']['link'])\n        out += \"\\nPublished Date : \" + str(p['publishDate'])\n        out += \"\\nUploaded Date  : \" + str(p['uploadDate'])\n        out += \"\\nRating         : \" + str(p['averageRating'])\n        out += \"\\nLikes          : \" + \"{:,}\".format(p.get('likes', 0))\n        out += \"\\nDislikes       : \" + \"{:,}\".format(p.get('dislikes', 0))\n        out += \"\\nCategory       : \" + str(p['category'])\n        out += \"\\nFamily Safe    : \" + str(p['isFamilySafe'])\n        out += \"\\nLink           : \" + str(p['link'])\n        if config.SHOW_QRCODE.get:\n            out += \"\\n\" + qrcode_display(\n                \"https://youtube.com/watch?v=%s\" % p.videoid)\n\n        out += \"\\n\\n%s[%sPress enter to go back%s]%s\" % (c.y, c.w, c.y, c.w)\n        g.content = out\n\n\n@command(r's\\s*(\\d{1,4})', 's')\ndef stream_info(num):\n    \"\"\" Get stream information. \"\"\"\n    if g.browse_mode == \"normal\":\n        g.content = logo(c.b)\n        screen.update()\n        screen.writestatus(\"Fetching stream metadata..\")\n        item = (g.model[int(num) - 1])\n        streams.get(item)\n        p = util.get_pafy(item)\n        setattr(p, 'ytid', p.videoid)\n        details = player.stream_details(p)[1]\n        screen.writestatus(\"Fetched\")\n        out = \"\\n\\n\" + c.ul + \"Stream Info\" + c.w + \"\\n\"\n        out += \"\\nExtension   : \" + details['ext']\n        out += \"\\nSize        : \" + str(details['size'])\n        out += \"\\nQuality     : \" + details['quality']\n        out += \"\\nRaw bitrate : \" + str(details['rawbitrate'])\n        out += \"\\nMedia type  : \" + details['mtype']\n        out += \"\\nLink        : \" + details['url']\n        out += \"\\n\\n%s[%sPress enter to go back%s]%s\" % (c.y, c.w, c.y, c.w)\n        g.content = out\n\n\n@command(r'history', 'history')\ndef view_history(duplicates=True):\n    \"\"\" Display the user's play history \"\"\"\n    history = g.userhist.get('history')\n    #g.last_opened = \"\"\n    try:\n        hist_list = list(reversed(history.songs))\n        message = \"Viewing play history\"\n        if not duplicates:\n            # List unique elements and preserve order.\n            seen = set()\n            seen_add = seen.add  # it makes calls to add() faster\n            hist_list = [x for x in hist_list if not (x.ytid in seen or seen_add(x.ytid))]\n            message = \"Viewing recent played songs\"\n        paginatesongs(hist_list)\n        g.message = message\n\n    except AttributeError:\n        g.content = logo(c.r)\n        g.message = \"History empty\"\n\n\n    if not config.HISTORY.get:\n        g.message += \"\\t{1}History recording is currently off{0}\".format(c.w,c.y)\n\n\n\n@command(r'history recent', 'history recent')\ndef recent_history():\n    \"\"\" Display the recent user's played songs \"\"\"\n    view_history(duplicates=False)\n\n\n@command(r'history clear', 'history clear')\ndef clear_history():\n    \"\"\" Clears the user's play history \"\"\"\n    g.userhist['history'].songs = []\n    history.save()\n    g.message = \"History cleared\"\n    g.content = logo()\n"
  },
  {
    "path": "mps_youtube/commands/play.py",
    "content": "import random\nimport sys\nimport typing as T\nimport webbrowser\nfrom urllib.error import HTTPError, URLError\n\nfrom .. import c, config, content, g, streams, util\nfrom . import RS, WORD, command\nfrom .search import related, yt_url\nfrom .songlist import plist\n\n@command(r'play all', 'play all')\ndef play_loaded():\n    g.model.songs = content.get_last_query()\n    if g.model.songs:\n        play_all(\"\", \"\", \"\")\n\n@command(r'play\\s+(%s|\\d+)' % WORD, 'play')\ndef play_pl(name):\n    \"\"\" Play a playlist by name. \"\"\"\n    if name.isdigit():\n        name = int(name)\n        name = sorted(g.userpl)[name - 1]\n\n    saved = g.userpl.get(name)\n\n    if not saved:\n        name = util.get_near_name(name, g.userpl)\n        saved = g.userpl.get(name)\n\n    if saved:\n        g.model.songs = list(saved.songs)\n        play_all(\"\", \"\", \"\")\n\n    else:\n        g.message = util.F(\"pl not found\") % name\n        g.content = content.playlists_display()\n\n\n@command(r'(%s{0,3})([-,\\d\\s\\[\\]]{1,250})\\s*(%s{0,3})$' %\n         (RS, RS))\ndef play(pre, choice, post=\"\"):\n    \"\"\" Play choice.  Use repeat/random if appears in pre/post. \"\"\"\n    # pylint: disable=R0914\n    # too many local variables\n\n    # Im just highjacking this if g.content is a\n    # content.Content class\n    if isinstance(g.content, content.Content):\n        play_call = getattr(g.content, \"_play\", None)\n        if callable(play_call):\n            play_call(pre, choice, post)\n        return\n\n    if g.browse_mode == \"ytpl\":\n\n        if choice.isdigit():\n            g.selected_pafy_pls_id = g.ytpls[int(choice)-1]['link']\n            return plist(g.selected_pafy_pls_id)\n        else:\n            g.message = \"Invalid playlist selection: %s\" % c.y + choice + c.w\n            g.content = content.generate_songlist_display()\n            return\n\n    if not g.model:\n        g.message = c.r + \"There are no tracks to select\" + c.w\n        g.content = g.content or content.generate_songlist_display()\n\n    else:\n        shuffle = \"shuffle\" in pre + post\n        repeat = \"repeat\" in pre + post\n        novid = \"-a\" in pre + post\n        fs = \"-f\" in pre + post\n        nofs = \"-w\" in pre + post\n        forcevid = \"-v\" in pre + post\n\n        if ((novid and fs) or (novid and nofs) or (nofs and fs)\n           or (novid and forcevid)):\n            raise IOError(\"Conflicting override options specified\")\n\n        override = False\n        override = \"audio\" if novid else override\n        override = \"fullscreen\" if fs else override\n        override = \"window\" if nofs else override\n\n        if (not fs) and (not nofs):\n            override = \"forcevid\" if forcevid else override\n\n        selection = util.parse_multi(choice)\n        songlist = [g.model[x - 1] for x in selection]\n\n        # cache next result of displayed items\n        # when selecting a single item\n        if len(songlist) == 1:\n            chosen = selection[0] - 1\n\n            if len(g.model) > chosen + 1:\n                streams.preload(g.model[chosen + 1], override=override)\n\n        if g.scrobble:\n            old_queue = g.scrobble_queue\n            g.scrobble_queue = [g.scrobble_queue[x - 1] for x in selection]\n\n        try:\n            if not config.PLAYER.get or not util.has_exefile(config.PLAYER.get):\n                g.message = \"Player not configured! Enter %sset player <player_app> \"\\\n                            \"%s to set a player\" % (c.g, c.w)\n                return\n            g.PLAYER_OBJ.play(songlist, shuffle, repeat, override)\n        except KeyboardInterrupt:\n            return\n        finally:\n            g.content = content.generate_songlist_display()\n\n        if g.scrobble:\n            g.scrobble_queue = old_queue\n\n        if config.AUTOPLAY.get:\n            related(selection.pop())\n            play(pre, str(random.randint(1, 15)), post=\"\")\n\n\n@command(r'(%s{0,3})(?:\\*|all)\\s*(%s{0,3})' %\n        (RS, RS))\ndef play_all(pre, choice, post=\"\"):\n    \"\"\" Play all tracks in model (last displayed). shuffle/repeat if req'd.\"\"\"\n    options = pre + choice + post\n    play(options, \"1-\" + str(len(g.model)))\n\n\n@command(r'playurl\\s(.*[-_a-zA-Z0-9]{11}[^\\s]*)(\\s-(?:f|a|w))?', 'playurl')\ndef play_url(url: str, override: T.Any):\n    \"\"\"Open and play a youtube video url.\n\n    Args:\n        url: url to be played\n        override: override\n\n    Raises:\n        SystemExit: If run from command line\n    \"\"\"\n    # @fixme check override type hint\n    override = override if override else \"_\"\n    g.browse_mode = \"normal\"\n    yt_url(url, print_title=True)\n\n    if len(g.model) == 1:\n        play(override, \"1\", \"_\")\n\n    if g.command_line:\n        sys.exit()\n\n\n@command(r'browserplay\\s(\\d{1,50})', 'browserplay')\ndef browser_play(number):\n    \"\"\"Open a previously searched result in the browser.\"\"\"\n    if (len(g.model) == 0):\n        g.message = c.r + \"No previous search.\" + c.w\n        g.content = content.logo(c.r)\n        return\n\n    try:\n        index = int(number) - 1\n\n        if (0 <= index < len(g.model)):\n            base_url = \"https://www.youtube.com/watch?v=\"\n            video = g.model[index]\n            url = base_url + video.ytid\n            webbrowser.open(url)\n            g.content = g.content or content.generate_songlist_display()\n\n        else:\n            g.message = c.r + \"Out of range.\" + c.w\n            g.content = g.content or content.generate_songlist_display()\n            return\n\n    except (HTTPError, URLError, Exception) as e:\n        g.message = c.r + str(e) + c.w\n        g.content = g.content or content.generate_songlist_display()\n        return\n"
  },
  {
    "path": "mps_youtube/commands/search.py",
    "content": "import base64\nimport json\nimport logging\nimport math\nimport re\nimport typing as T\nfrom argparse import ArgumentParser\nfrom datetime import datetime, timedelta\nfrom urllib import parse\n\nfrom .. import pafy\n\nparser = ArgumentParser()\nparser.add_argument('-d', '--duration', choices=('any', 'short', 'medium', 'long'))\nparser.add_argument('-a', '--after')\nparser.add_argument('-l', '--live', nargs=\"?\", const=True)\nparser.add_argument('-c', '--category', nargs=1)\nparser.add_argument('search', nargs='+')\n\n\nfrom .. import c, config, content, contentquery, g, listview, screen, util\nfrom ..playlist import Playlist, Video\nfrom . import command\nfrom .songlist import paginatesongs, plist\n\nISO8601_TIMEDUR_EX = re.compile(r'PT((\\d{1,3})H)?((\\d{1,3})M)?((\\d{1,2})S)?')\n\nDAYS = dict(day = 1,\n            week = 7,\n            month = 30,\n            year = 365)\n\n\ndef _display_search_results(progtext, wdata, msg=None, failmsg=None):\n    \"\"\" Perform memoized url fetch, display progtext. \"\"\"\n\n    loadmsg = \"Searching for '%s%s%s'\" % (c.y, progtext, c.w)\n\n    def iter_songs():\n        wdata2 = wdata\n        while True:\n            for song in get_tracks_from_json(wdata2):\n                yield song\n\n            if type(wdata2) is list or not wdata2.get('nextPageToken'):\n                break\n            query = None#wdata2['nextPageToken']\n            wdata2 = None#pafy.call_gdata('search', qs)\n\n    # The youtube search api returns a maximum of 500 results\n    length = len(wdata)\n    slicer = util.IterSlicer(iter_songs(), length)\n\n    paginatesongs(slicer, length=length, msg=msg, failmsg=failmsg,\n            loadmsg=loadmsg)\n\n\ndef token(page):\n    \"\"\" Returns a page token for a given start index. \"\"\"\n    index = (page or 0) * util.getxy().max_results\n    k = index//128 - 1\n    index -= 128 * k\n    f = [8, index]\n    if k > 0 or index > 127:\n        f.append(k+1)\n    f += [16, 0]\n    b64 = base64.b64encode(bytes(f)).decode('utf8')\n    return b64.strip('=')\n\n\n# def generate_search_qs(term, match='term', videoDuration='any', after=None, category=None, is_live=False):\n#     \"\"\" Return query string. \"\"\"\n#\n#     aliases = dict(views='viewCount')\n#     qs = {\n#         'q': term,\n#         'maxResults': 50,\n#         'safeSearch': \"none\",\n#         'order': aliases.get(config.ORDER.get, config.ORDER.get),\n#         'part': 'id,snippet',\n#         'type': 'video',\n#         'videoDuration': videoDuration\n#         #,'key': config.API_KEY.get\n#     }\n#\n#     if after:\n#         after = after.lower()\n#         qs['publishedAfter'] = '%sZ' % (datetime.utcnow() - timedelta(days=DAYS[after])).isoformat() \\\n#                                 if after in DAYS.keys() else '%s%s' % (after, 'T00:00:00Z' * (len(after) == 10))\n#\n#     if match == 'related':\n#         qs['relatedToVideoId'] = term\n#         del qs['q']\n#\n#     if config.SEARCH_MUSIC.get:\n#         qs['videoCategoryId'] = 10\n#\n#     if category:\n#         qs['videoCategoryId'] = category\n#\n#     if is_live:\n#         qs['eventType'] = \"live\"\n#\n#     return qs\n\n\ndef userdata_cached(userterm):\n    \"\"\" Check if user name search term found in cache \"\"\"\n    userterm = ''.join([t.strip().lower() for t in userterm.split(' ')])\n    return g.username_query_cache.get(userterm)\n\n\ndef cache_userdata(userterm, username, channel_id):\n    \"\"\" Cache user name and channel id tuple \"\"\"\n    userterm = ''.join([t.strip().lower() for t in userterm.split(' ')])\n    g.username_query_cache[userterm] = (username, channel_id)\n    util.dbg('Cache data for username search query \"{}\": {} ({})'.format(\n        userterm, username, channel_id))\n\n    while len(g.username_query_cache) > 300:\n        g.username_query_cache.popitem(last=False)\n    return (username, channel_id)\n\n\ndef channelfromname(user):\n    \"\"\" Query channel id from username. \"\"\"\n\n    cached = userdata_cached(user)\n    if cached:\n        return cached\n\n    try:\n        channel_id, channel_name = pafy.channel_id_from_name(user)\n        return cache_userdata(user, channel_name, channel_id)\n\n    except Exception as e:\n        import traceback\n        traceback.print_exception(type(e), e, e.__traceback__)\n        g.message = \"Could not retrieve information for user {}\\n{}\".format(\n            c.y + user + c.w, e)\n        util.dbg('Error during channel request for user {}:\\n{}'.format(\n            user, e))\n\n    # at this point, we know the channel id associated to a user name\n    return None\n\n\n@command(r'channels\\s+(.+)')\ndef channelsearch(q_user):\n\n    # qs = {'part': 'id,snippet',\n    #       'q': q_user,\n    #       'maxResults': 50,\n    #       'type': 'channel',\n    #       'order': \"relevance\"\n    #       }\n\n    QueryObj = contentquery.ContentQuery(listview.ListUser, 'search', q_user)\n    columns = [\n        {\"name\": \"idx\", \"size\": 3, \"heading\": \"Num\"},\n        {\"name\": \"name\", \"size\": 30, \"heading\": \"Username\"},\n        {\"name\": \"description\", \"size\": \"remaining\", \"heading\": \"Description\"},\n        ]\n\n    def run_m(user_id):\n        \"\"\" Search ! \"\"\"\n        usersearch_id(*(user_id[0]))\n    del g.content\n\n    g.content = listview.ListView(columns, QueryObj, run_m)\n    g.message = \"Results for channel search: '%s'\" % q_user\n\n\n@command(r'user\\s+(.+)', 'user')\ndef usersearch(q_user, identify='forUsername'):\n    \"\"\" Fetch uploads by a YouTube user. \"\"\"\n\n    user, _, term = (x.strip() for x in q_user.partition(\"/\"))\n    if identify == 'forUsername':\n        ret = channelfromname(user)\n        if not ret:  # Error\n            return\n        user, channel_id = ret\n\n    else:\n        channel_id = user\n\n    # at this point, we know the channel id associated to a user name\n    usersearch_id(user, channel_id, term)\n\n\ndef usersearch_id(user, channel_id, term):\n    \"\"\" Performs a search within a user's (i.e. a channel's) uploads\n    for an optional search term with the user (i.e. the channel)\n    identified by its ID \"\"\"\n\n    #query = generate_search_qs(term)\n    aliases = dict(views='viewCount')  # The value of the config item is 'views' not 'viewCount'\n    if config.USER_ORDER.get:\n        pass\n        #query['order'] = aliases.get(config.USER_ORDER.get,\n        #        config.USER_ORDER.get)\n    #query['channelId'] = channel_id\n\n    termuser = tuple([c.y + x + c.w for x in (term, user)])\n    if term:\n        msg = \"Results for {1}{3}{0} (by {2}{4}{0})\"\n        progtext = \"%s by %s\" % termuser\n        failmsg = \"No matching results for %s (by %s)\" % termuser\n    else:\n        msg = \"Video uploads by {2}{4}{0}\"\n        progtext = termuser[1]\n        if config.SEARCH_MUSIC:\n            failmsg = \"\"\"User %s not found or has no videos in the Music category.\nUse 'set search_music False' to show results not in the Music category.\"\"\" % termuser[1]\n        else:\n            failmsg = \"User %s not found or has no videos.\"  % termuser[1]\n    msg = str(msg).format(c.w, c.y, c.y, term, user)\n    results = pafy.all_videos_from_channel(channel_id)\n    _display_search_results(progtext, results, msg, failmsg)\n\n\ndef related_search(vitem):\n    \"\"\" Fetch videos related to vitem\n    vitem = {'description': str, 'length': int, 'title': str, 'ytid': str}\n    \"\"\"\n\n    t = vitem.title\n    ttitle = t[:48].strip() + \"..\" if len(t) > 49 else t\n\n    msg = \"Videos related to %s%s%s\" % (c.y, ttitle, c.w)\n    failmsg = \"Related to %s%s%s not found\" % (c.y, vitem.ytid, c.w)\n\n    # todo: implement realted search in pafy\n    #_search(ttitle, vitem.title, msg, failmsg)\n\n\n# Livestream category search\n@command(r'live\\s+(.+)', 'live')\ndef livestream_category_search(term):\n    sel_category = g.categories.get(term, None)\n\n    if not sel_category:\n        g.message = (\"That is not a valid category. Valid categories are: \")\n        g.message += (\", \".join(g.categories.keys()))\n        return\n\n    query = {\n        \"part\": \"id,snippet\",\n        \"eventType\": \"live\",\n        \"maxResults\": 50,\n        \"type\": \"video\",\n        \"videoCategoryId\": sel_category\n    }\n\n    query_obj = contentquery.ContentQuery(listview.ListLiveStream, 'search', query)\n    columns = [\n              {\"name\": \"idx\", \"size\": 3, \"heading\": \"Num\"},\n              {\"name\": \"title\", \"size\": 40, \"heading\": \"Title\"},\n              {\"name\": \"description\", \"size\": \"remaining\", \"heading\": \"Description\"},\n              ]\n\n    def start_stream(returned):\n        songs = Playlist(\"Search Results\", [Video(*x) for x in returned])\n        if not config.PLAYER.get or not util.has_exefile(config.PLAYER.get):\n            g.message = \"Player not configured! Enter %sset player <player_app> \"\\\n                        \"%s to set a player\" % (c.g, c.w)\n            return\n        g.PLAYER_OBJ.play(songs, False, False, False)\n\n    g.content = listview.ListView(columns, query_obj, start_stream)\n    g.message = \"Livestreams in category: '%s'\" % term\n\n\n# Note: [^./] is to prevent overlap with playlist search command\n@command(r'(?:search|\\.|/)\\s*([^./].{1,500})', 'search')\ndef search(term):\n    \"\"\" Perform search. \"\"\"\n    try:  # TODO make use of unknowns\n        args, unknown = parser.parse_known_args(term.split())\n        video_duration = args.duration if args.duration else 'any'\n        if args.category:\n            if not args.category[0].isdigit():\n                args.category = g.categories.get(args.category[0])\n            else:\n                args.category = \"\".join(args.category)\n        after = args.after\n        term = ' '.join(args.search)\n    except SystemExit:  # <------ argsparse calls exit()\n        g.message = c.b + \"Bad syntax. Enter h for help\" + c.w\n        return\n\n    if not term or len(term) < 2:\n        g.message = c.r + \"Not enough input\" + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    logging.info(\"search for %s\", term)\n    #query = generate_search_qs(term, videoDuration=video_duration, after=after, category=args.category, is_live=args.live)\n\n    msg = \"Search results for %s%s%s\" % (c.y, term, c.w)\n    failmsg = \"Found nothing for %s%s%s\" % (c.y, term, c.w)\n    wdata = pafy.search_videos(term, int(config.PAGES.get))\n    _display_search_results(term, wdata, msg, failmsg)\n\n\n@command(r'u(?:ser)?pl\\s(.*)', 'userpl', 'upl')\ndef user_pls(user):\n    \"\"\" Retrieve user playlists. \"\"\"\n    return pl_search(user, is_user=True)\n\n\n@command(r'(?:\\.\\.|\\/\\/|pls(?:earch)?\\s)\\s*(.*)', 'plsearch')\ndef pl_search(term, page=0, splash=True, is_user=False):\n    \"\"\" Search for YouTube playlists.\n\n    term can be query str or dict indicating user playlist search.\n\n    \"\"\"\n    if not term or len(term) < 2:\n        g.message = c.r + \"Not enough input\" + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    if splash:\n        g.content = content.logo(c.g)\n        prog = \"user: \" + term if is_user else term\n        g.message = \"Searching playlists for %s\" % c.y + prog + c.w\n        screen.update()\n\n    logging.info(\"playlist search for %s\", prog)\n    if is_user:\n        ret = channelfromname(term)\n        if not ret:\n            return\n        user, channel_id = ret\n        pldata = pafy.all_playlists_from_channel(channel_id)\n    else:\n        pldata = pafy.playlist_search(term)\n\n    playlists = get_pl_from_json(pldata)[:util.getxy().max_results]\n\n    if playlists:\n        g.last_search_query = (pl_search, {\"term\": term, \"is_user\": is_user})\n        g.browse_mode = \"ytpl\"\n        g.current_page = page\n        g.result_count = len(pldata)\n        g.ytpls = playlists\n        g.message = \"Playlist results for %s\" % c.y + prog + c.w\n        g.content = content.generate_playlist_display()\n\n    else:\n        g.message = \"No playlists found for: %s\" % c.y + prog + c.w\n        g.current_page = 0\n        g.content = content.generate_songlist_display(zeromsg=g.message)\n\n\ndef get_pl_from_json(pldata):\n    \"\"\" Process json playlist data. \"\"\"\n\n    try:\n        items = pldata\n\n    except KeyError:\n        items = []\n\n    results = []\n\n    for item in items:\n        results.append(dict(\n            link=item[\"id\"],\n            size=item[\"videoCount\"],\n            title=item[\"title\"],\n            author= item['channel'][\"name\"] if 'channel' in item.keys()  else None,\n            created=item.get(\"publishedAt\"),\n            updated=item.get('publishedAt'), #XXX Not available in API?\n            description=item.get(\"description\")))\n\n    return results\n\n\ndef get_track_id_from_json(item):\n    \"\"\" Try to extract video Id from various response types \"\"\"\n    fields = ['contentDetails/videoId',\n              'snippet/resourceId/videoId',\n              'id/videoId',\n              'id']\n    for field in fields:\n        node = item\n        for p in field.split('/'):\n            if node and isinstance(node, dict):\n                node = node.get(p)\n        if node:\n            return node\n    return ''\n\n\ndef get_tracks_from_json(jsons):\n    \"\"\" Get search results from API response \"\"\"\n\n    if len(jsons) == 0:\n        util.dbg(\"got unexpected data or no search results\")\n        return ()\n\n    # populate list of video objects\n    songs = []\n    for item in jsons:\n        try:\n            ytid = get_track_id_from_json(item)\n            duration = util.parse_video_length(item.get('duration'))\n            #stats = item.get('statistics', {})\n            #snippet = item.get('snippet', {})\n            title = item.get('title', '').strip()\n            # instantiate video representation in local model\n            cursong = Video(ytid=ytid, title=title, length=duration)\n            dislike_data = {'likes': 0, 'dislikes':0, 'rating':0}#pafy.return_dislikes(ytid)\n            likes = int(dislike_data['likes'])\n            dislikes = int(dislike_data['dislikes'])\n            # this is a very poor attempt to calculate a rating value\n            rating = int(dislike_data['rating'])#5.*likes/(likes+dislikes) if (likes+dislikes) > 0 else 0\n            category = '?'#snippet.get('categoryId')\n            publishedlocaldatetime = item.get('publishedTime','?')#util.yt_datetime_local(snippet.get('publishedAt', ''))\n\n            # cache video information in custom global variable store\n            g.meta[ytid] = dict(\n                # tries to get localized title first, fallback to normal title\n                title=title,\n                length=str(util.fmt_time(cursong.length)),\n                rating=rating,#str('{}'.format(rating))[:4].ljust(4, \"0\"),\n                uploader=item['channel']['id'],\n                uploaderName=item['channel']['name'],\n                category=category,\n                aspect=\"custom\", #XXX\n                uploaded=publishedlocaldatetime,#publishedlocaldatetime[1] if publishedlocaldatetime is not None else None,\n                uploadedTime=publishedlocaldatetime,#,publishedlocaldatetime[2] if publishedlocaldatetime is not None else None,\n                likes=str(num_repr(likes)),\n                dislikes=str(num_repr(dislikes)),\n                commentCount='?',#str(num_repr(int(stats.get('commentCount', 0)))),\n                viewCount= item['viewCount']['text'] if 'viewCount' in item.keys() else '?')#str(num_repr(int(stats.get('viewCount', 0)))))\n            songs.append(cursong)\n\n        except Exception as e:\n            import traceback\n            traceback.print_exception(type(e), e, e.__traceback__)\n            input('Press any key to continue...')\n            util.dbg(json.dumps(item, indent=2))\n            util.dbg('Error during metadata extraction/instantiation of ' +\n                'search result {}\\n{}'.format(ytid, e))\n\n\n\n    # return video objects\n    return songs\n\n\ndef num_repr(num):\n    \"\"\" Return up to four digit string representation of a number, eg 2.6m. \"\"\"\n    if num <= 9999:\n        return str(num)\n\n    def digit_count(x):\n        \"\"\" Return number of digits. \"\"\"\n        return int(math.floor(math.log10(x)) + 1)\n\n    digits = digit_count(num)\n    sig = 3 if digits % 3 == 0 else 2\n    rounded = int(round(num, int(sig - digits)))\n    digits = digit_count(rounded)\n    suffix = \"_kmBTqXYX\"[(digits - 1) // 3]\n    front = 3 if digits % 3 == 0 else digits % 3\n\n    if not front == 1:\n        return str(rounded)[0:front] + suffix\n\n    return str(rounded)[0] + \".\" + str(rounded)[1] + suffix\n\n\n@command(r'u\\s?([\\d]{1,4})', 'u')\ndef user_more(num):\n    \"\"\" Show more videos from user of vid num. \"\"\"\n    if g.browse_mode != \"normal\":\n        g.message = \"User uploads must refer to a specific video item\"\n        g.message = c.y + g.message + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    g.current_page = 0\n    item = g.model[int(num) - 1]\n\n    #TODO: Cleaner way of doing this?\n    if item.ytid in g.meta:\n        channel_id = g.meta.get(item.ytid, {}).get('uploader')\n        user = g.meta.get(item.ytid, {}).get('uploaderName')\n    else:\n        paf = util.get_pafy(item)\n        user, channel_id = channelfromname(paf.author)\n\n    usersearch_id(user, channel_id, '')\n\n\n@command(r'r\\s?(\\d{1,4})', 'r')\ndef related(num):\n    \"\"\" Show videos related to to vid num. \"\"\"\n    if g.browse_mode != \"normal\":\n        g.message = \"Related items must refer to a specific video item\"\n        g.message = c.y + g.message + c.w\n        g.content = content.generate_songlist_display()\n        return\n\n    g.current_page = 0\n    item = g.model[int(num) - 1]\n    related_search(item)\n\n\n@command(r'mix\\s*(\\d{1,4})', 'mix')\ndef mix(num):\n    \"\"\" Retrieves the YouTube mix for the selected video. \"\"\"\n    g.content = g.content or content.generate_songlist_display()\n    if g.browse_mode != \"normal\":\n        g.message = util.F('mix only videos')\n    else:\n        item = (g.model[int(num) - 1])\n        if item is None:\n            g.message = util.F('invalid item')\n            return\n        item = util.get_pafy(item)\n        # Mix playlists are made up of 'RD' + video_id\n        try:\n            plist(\"RD\" + item.videoid)\n        except OSError:\n            g.message = util.F('no mix')\n\n\n@command(r\"url\\s(.*[-_a-zA-Z0-9]{11}.*)\", \"url\")\ndef yt_url(url: str, print_title: bool = False):\n    \"\"\"\n    Acess videos by urls.\n\n    If `print_title` is true only last title from unique parsed id will be printed.\n\n    If for example `vid1` and `vid2` have title `title1` and `title2`, respectively,\n    `yt_url('vid1 vid2 vid1', True)`\n    will print `title2` from `vid2` instead `title1` from last entry `vid1`.\n\n    Args:\n        url: youtube url\n        print_title: print title or not\n    \"\"\"\n    url_list = url.split()\n\n    g.model.songs = []\n\n    v_ids = set()\n    v_title = None\n    for url in url_list:\n        try:\n            v_id = pafy.extract_video_id(url)\n            if v_id in v_ids:\n                continue\n            p = pafy.get_video_info(v_id)\n        except (IOError, ValueError) as e:\n            g.message = c.r + str(e) + c.w\n            g.content = g.content or content.generate_songlist_display(\n                    zeromsg=g.message)\n            return\n\n        g.browse_mode = \"normal\"\n        v = Video(p['id'], p['title'], int(p['duration']['secondsText']))\n        if p and isinstance(p, dict):\n            v_title = p.get(\"title\")\n        g.model.songs.append(v)\n        v_ids.add(v_id)\n\n    if not g.command_line:\n        g.content = content.generate_songlist_display()\n\n    if print_title and v_title:\n        util.xprint(v_title)\n\n\n@command(r'url_file\\s(\\S+)', 'url_file')\ndef yt_url_file(file_name):\n    \"\"\" Access a list of urls in a text file \"\"\"\n\n    #Open and read the file\n    try:\n        with open(file_name, \"r\") as fo:\n            output = ' '.join([line.strip() for line in fo if line.strip()])\n\n    except (IOError):\n        g.message = c.r + 'Error while opening the file, check the validity of the path' + c.w\n        g.content = g.content or content.generate_songlist_display(\n                zeromsg=g.message)\n        return\n\n    #Finally pass the input to yt_url\n    yt_url(output)\n"
  },
  {
    "path": "mps_youtube/commands/songlist.py",
    "content": "import math\nimport random\n\n\nfrom .. import g, c, screen, streams, content, util, pafy\nfrom ..playlist import Video\nfrom . import command, PL\n\n\ndef paginatesongs(func, page=0, splash=True, dumps=False,\n        length=None, msg=None, failmsg=None, loadmsg=None):\n    \"\"\"\n    A utility function for handling lists of songs, so that\n    the pagination and the dump command will work properly.\n\n    :param func: Either a function taking a start and end index,\n        or a slicable object. Either way, it should produce an iterable\n        of :class:`mps_youtube.playlist.Video` objects.\n    :param page: The page number to display\n    :param splash: Whether or not to display a splash screen while\n        loading.\n    :param dumps: Used by :func:`dump` command to load all songs, instead\n        of only those that fit on a page\n    :param length: The total number of songs. It it is not provided,\n        ``len(func)`` will be used instead.\n    :param msg: Message to display after loading successfully\n    :param failmsg: Message to display on failure (if no songs are\n        returned by func\n    :param loadmsg: Message to display while loading\n    :type page: int\n    :type splash: bool\n    :type dumps: bool\n    :type length: int\n    :type msg: str\n    :type failmsg: str\n    :type loadmsg: str\n    \"\"\"\n    if splash:\n        g.message = loadmsg or ''\n        g.content = content.logo(col=c.b)\n        screen.update()\n\n    max_results = util.getxy().max_results\n\n    if dumps:\n        s = 0\n        e = None\n    else:\n        s = page * max_results\n        e = (page + 1) * max_results\n\n    if callable(func):\n        songs = func(s, e)\n    else:\n        songs = func[s:e]\n\n    if length is None:\n        length = len(func)\n\n    args = {'func':func, 'length':length, 'msg':msg,\n            'failmsg':failmsg, 'loadmsg': loadmsg}\n    g.last_search_query = (paginatesongs, args)\n    g.browse_mode = \"normal\"\n    g.current_page = page\n    g.result_count = length\n    g.model.songs = songs\n    g.content = content.generate_songlist_display()\n    g.last_opened = \"\"\n    g.message = msg or ''\n    if not songs:\n        g.message = failmsg or g.message\n\n    if songs:\n        # preload first result url\n        streams.preload(songs[0], delay=0)\n\n\n@command(r'pl\\s+%s' % PL, 'pl')\ndef plist(parturl):\n    \"\"\" Retrieve YouTube playlist. \"\"\"\n\n    if parturl in g.pafy_pls:\n        ytpl, plitems = g.pafy_pls[parturl]\n    else:\n        util.dbg(\"%sFetching playlist using pafy%s\", c.y, c.w)\n        ytpl = pafy.get_playlist(parturl)\n        plitems = util.IterSlicer(ytpl.videos)\n        g.pafy_pls[parturl] = (ytpl, plitems)\n\n    def pl_seg(s, e):\n        return [Video(i['id'], i['title'], util.parse_video_length(i['duration'])) for i in plitems[s:e]]\n\n    msg = \"Showing YouTube playlist %s\" % (c.y + ytpl.info['info']['title'] + c.w)\n    loadmsg = \"Retrieving YouTube playlist\"\n    paginatesongs(pl_seg, length=len(ytpl.videos), msg=msg, loadmsg=loadmsg)\n\n\n@command(r'(rm|add)\\s*(-?\\d[-,\\d\\s]{,250})', 'rm', 'add')\ndef songlist_rm_add(action, songrange):\n    \"\"\" Remove or add tracks. works directly on user input. \"\"\"\n    selection = util.parse_multi(songrange)\n\n    if action == \"add\":\n        duplicate_songs = []\n        for songnum in selection:\n            if g.model[songnum - 1] in g.active:\n                duplicate_songs.append(str(songnum))\n            g.active.songs.append(g.model[songnum - 1])\n\n        d = g.active.duration\n        g.message = util.F('added to pl') % (len(selection), len(g.active), d)\n        if duplicate_songs:\n            duplicate_songs = ', '.join(sorted(duplicate_songs))\n            g.message += '\\n'\n            g.message += util.F('duplicate tracks') % duplicate_songs\n\n    elif action == \"rm\":\n        selection = sorted(set(selection), reverse=True)\n        removed = str(tuple(reversed(selection))).replace(\",\", \"\")\n\n        for x in selection:\n            g.model.songs.pop(x - 1)\n            try:\n                g.active.songs.pop(g.current_page * util.getxy().max_results + x - 1)\n            except IndexError:\n                pass\n\n        g.message = util.F('songs rm') % (len(selection), removed)\n\n    g.content = content.generate_songlist_display()\n\n\n@command(r'(mv|sw)\\s*(\\d{1,4})\\s*[\\s,]\\s*(\\d{1,4})', 'mv', 'sw')\ndef songlist_mv_sw(action, a, b):\n    \"\"\" Move a song or swap two songs. \"\"\"\n    i, j = int(a) - 1, int(b) - 1\n\n    if action == \"mv\":\n        g.model.songs.insert(j, g.model.songs.pop(i))\n        g.message = util.F('song move') % (g.model[j].title, b)\n\n    elif action == \"sw\":\n        g.model[i], g.model[j] = g.model[j], g.model[i]\n        g.message = util.F('song sw') % (min(a, b), max(a, b))\n\n    g.content = content.generate_songlist_display()\n\n\n@command(r'(n|p)\\s*(\\d{1,2})?')\ndef nextprev(np, page=None):\n    \"\"\" Get next / previous search results. \"\"\"\n    if isinstance(g.content, content.PaginatedContent):\n        page_count = g.content.numPages()\n        function = g.content.getPage\n        args = {}\n    else:\n        page_count = math.ceil(g.result_count/util.getxy().max_results)\n        function, args = g.last_search_query\n\n    good = False\n\n    if function:\n        if np == \"n\":\n            if g.current_page + 1 < page_count:\n                g.current_page += 1\n                good = True\n\n        elif np == \"p\":\n            if page and int(page) in range(1,20):\n                g.current_page = int(page)-1\n                good = True\n\n            elif g.current_page > 0:\n                g.current_page -= 1\n                good = True\n\n    if good:\n        function(page=g.current_page, **args)\n\n    else:\n        norp = \"next\" if np == \"n\" else \"previous\"\n        g.message = \"No %s items to display\" % norp\n\n    if not isinstance(g.content, content.PaginatedContent):\n        g.content = content.generate_songlist_display()\n    return good\n\n\n@command(r'(un)?dump', 'dump', 'undump')\ndef dump(un):\n    \"\"\" Show entire playlist. \"\"\"\n    func, args = g.last_search_query\n\n    if func is paginatesongs:\n        paginatesongs(dumps=(not un), **args)\n\n    else:\n        un = \"\" if not un else un\n        g.message = \"%s%sdump%s may only be used on an open YouTube playlist\"\n        g.message = g.message % (c.y, un, c.w)\n        g.content = content.generate_songlist_display()\n\n\n@command(r'shuffle', 'shuffle')\ndef shuffle_fn():\n    \"\"\" Shuffle displayed items. \"\"\"\n    random.shuffle(g.model.songs)\n    g.message = c.y + \"Items shuffled\" + c.w\n    g.content = content.generate_songlist_display()\n\n@command(r'shuffle all', 'shuffle all')\ndef shuffle_playlist():\n    \"\"\" Shuffle entire loaded playlist. \"\"\"\n    songs = content.get_last_query()\n\n    if songs: \n        random.shuffle(songs)\n        paginatesongs(list(songs))\n        g.message = c.y + \"Shuffled entire playlist\" + c.w\n        g.content = content.generate_songlist_display()\n\n@command(r'reverse', 'reverse')\ndef reverse_songs():\n    \"\"\" Reverse order of displayed items. \"\"\"\n    g.model.songs = g.model.songs[::-1]\n    g.message = c.y + \"Reversed displayed songs\" + c.w\n    g.content = content.generate_songlist_display()\n\n\n@command(r'reverse\\s*(\\d{1,4})\\s*-\\s*(\\d{1,4})\\s*', 'reverse')\ndef reverse_songs_range(lower, upper):\n    \"\"\" Reverse the songs within a specified range. \"\"\"\n    lower, upper = int(lower), int(upper)\n    if lower > upper: lower, upper = upper, lower\n    \n    g.model.songs[lower-1:upper] = reversed(g.model.songs[lower-1:upper])\n    g.message = c.y + \"Reversed range: \" + str(lower) + \"-\" + str(upper) + c.w\n    g.content = content.generate_songlist_display()\n    \n\n@command(r'reverse all', 'reverse all')\ndef reverse_playlist():\n    \"\"\" Reverse order of entire loaded playlist. \"\"\"\n    songs = content.get_last_query()\n\n    if songs:   \n        paginatesongs(list(reversed(songs)))\n        g.message = c.y + \"Reversed entire playlist\" + c.w\n        g.content = content.generate_songlist_display()\n"
  },
  {
    "path": "mps_youtube/commands/spotify_playlist.py",
    "content": "import re\nimport time\nimport difflib\n\ntry:\n    # pylint: disable=F0401\n    import spotipy\n    import spotipy.oauth2 as oauth2\n    has_spotipy = True\n\nexcept ImportError:\n    has_spotipy = False\n\n\nfrom .. import c, g, screen, __version__, __url__, content, config, util\nfrom . import command\nfrom .songlist import paginatesongs\nfrom .search import get_tracks_from_json\n\n\ndef generate_credentials():\n    \"\"\"Generate the token. Please respect these credentials :)\"\"\"\n    credentials = oauth2.SpotifyClientCredentials(\n        client_id='6451e12933bb49ed8543d41e3296a88d',\n        client_secret='40ef54678fe441bd9acd66f5d5c34e69')\n    return credentials\n\n\ndef grab_playlist(spotify, playlist):\n    if '/' in playlist:\n        if playlist.endswith('/'):\n            playlist = playlist[:-1]\n        splits = playlist.split('/')\n    else:\n        splits = playlist.split(':')\n\n    username = splits[-3]\n    playlist_id = splits[-1]\n    results = spotify.user_playlist(username, playlist_id,\n                                    fields='tracks,next,name,owner')\n\n    all_tracks = []\n    tracks = results['tracks']\n    while True:\n        for item in tracks['items']:\n            track = item['track']\n            try:\n                all_tracks.append(track)\n            except KeyError:\n                pass\n        # 1 page = 50 results\n        # check if there are more pages\n        if tracks['next']:\n            tracks = spotify.next(tracks)\n        else:\n            break\n\n    return (results, all_tracks)\n\n\ndef show_message(message, col=c.r, update=False):\n    \"\"\" Show message using col, update screen if required. \"\"\"\n    g.content = content.generate_songlist_display()\n    g.message = col + message + c.w\n\n    if update:\n        screen.update()\n\n\ndef _best_song_match(songs, title, duration, titleweight, durationweight):\n    \"\"\" Select best matching song based on title, length.\n\n    Score from 0 to 1 where 1 is best. titleweight and durationweight\n    parameters added to enable function usage when duration can't be guessed\n\n    \"\"\"\n    # pylint: disable=R0914\n    seqmatch = difflib.SequenceMatcher\n\n    def variance(a, b):\n        \"\"\" Return difference ratio. \"\"\"\n        return float(abs(a - b)) / max(a, b)\n\n    candidates = []\n\n    ignore = \"music video lyrics new lyrics video audio\".split()\n    extra = \"official original vevo\".split()\n\n    for song in songs:\n        dur, tit = int(song.length), song.title\n        util.dbg(\"Title: %s, Duration: %s\", tit, dur)\n\n        for word in extra:\n            if word in tit.lower() and word not in title.lower():\n                pattern = re.compile(word, re.I)\n                tit = pattern.sub(\"\", tit)\n\n        for word in ignore:\n            if word in tit.lower() and word not in title.lower():\n                pattern = re.compile(word, re.I)\n                tit = pattern.sub(\"\", tit)\n\n        replacechars = re.compile(r\"[\\]\\[\\)\\(\\-]\")\n        tit = replacechars.sub(\" \", tit)\n        multiple_spaces = re.compile(r\"(\\s)(\\s*)\")\n        tit = multiple_spaces.sub(r\"\\1\", tit)\n\n        title_score = seqmatch(None, title.lower(), tit.lower()).ratio()\n        duration_score = 1 - variance(duration, dur)\n        util.dbg(\"Title score: %s, Duration score: %s\", title_score,\n                 duration_score)\n\n        # apply weightings\n        score = duration_score * durationweight + title_score * titleweight\n        candidates.append((score, song))\n\n    best_score, best_song = max(candidates, key=lambda x: x[0])\n    percent_score = int(100 * best_score)\n    return best_song, percent_score\n\n\ndef _match_tracks(tracks):\n    \"\"\" Match list of tracks by performing multiple searches. \"\"\"\n    # pylint: disable=R0914\n\n    def dtime(x):\n        \"\"\" Format time to M:S. \"\"\"\n        return time.strftime('%M:%S', time.gmtime(int(x)))\n\n    # do matching\n    for track in tracks:\n        ttitle = track['name']\n        artist = track['artists'][0]['name']\n        length = track['duration_ms']/1000\n        util.xprint(\"Search :  %s%s - %s%s - %s\" % (c.y, artist, ttitle, c.w,\n                                                    dtime(length)))\n        q = \"%s %s\" % (artist, ttitle)\n        w = q = ttitle if artist == \"Various Artists\" else q\n        query = w#generate_search_qs(w, 0)\n        util.dbg(query)\n\n        # perform fetch\n        wdata = None#pafy.call_gdata('search', query)\n        results = get_tracks_from_json(wdata)\n\n        if not results:\n            util.xprint(c.r + \"Nothing matched :(\\n\" + c.w)\n            continue\n\n        s, score = _best_song_match(\n            results, artist + \" \" + ttitle, length, .5, .5)\n        cc = c.g if score > 85 else c.y\n        cc = c.r if score < 75 else cc\n        util.xprint(\"Matched:  %s%s%s - %s \\n[%sMatch confidence: \"\n                    \"%s%s]\\n\" % (c.y, s.title, c.w, util.fmt_time(s.length),\n                                 cc, score, c.w))\n        yield s\n\n\n@command(r'suser\\s*(.*[-_a-zA-Z0-9].*)?', 'suser')\ndef search_user(term):\n    \"\"\"Search for Spotify user playlists. \"\"\"\n    # pylint: disable=R0914,R0912\n    if has_spotipy:\n\n        if not term:\n            show_message(\"Enter username:\", c.g, update=True)\n            term = input(\"> \")\n\n            if not term or len(term) < 2:\n                g.message = c.r + \"Not enough input!\" + c.w\n                g.content = None#content.generate_songlist_display()\n                return\n\n        credentials = generate_credentials()\n        token = credentials.get_access_token()\n        spotify = spotipy.Spotify(auth=token)\n\n        playlists = spotify.user_playlists(term)\n        links = []\n        check = 1\n\n        g.content = \"Playlists:\\n\"\n\n        while True:\n            for playlist in playlists['items']:\n                if playlist['name'] is not None:\n                    g.content += (u'{0:>2}. {1:<30}  ({2} tracks)'.format(\n                        check, playlist['name'],\n                        playlist['tracks']['total']))\n                    g.content += \"\\n\"\n                    links.append(playlist)\n                    check += 1\n            if playlists['next']:\n                playlists = spotify.next(playlists)\n            else:\n                break\n\n        g.message = c.g + \"Choose your playlist:\" + c.w\n        screen.update()\n\n        choice = int(input(\"> \"))\n        playlist = links[choice-1]\n\n        search_playlist(playlist['external_urls']['spotify'], spotify=spotify)\n\n    else:\n        g.message = \"spotipy module must be installed for Spotify support\\n\"\n        g.message += \"see https://pypi.python.org/pypi/spotipy/\"\n\n\n\n@command(r'splaylist\\s*(.*[-_a-zA-Z0-9].*)?', 'splaylist')\ndef search_playlist(term, spotify=None):\n    \"\"\"Search for Spotify playlist. \"\"\"\n    # pylint: disable=R0914,R0912\n    if has_spotipy:\n\n        if not term:\n            show_message(\"Enter playlist url:\", c.g, update=True)\n            term = input(\"> \")\n\n            if not term or len(term) < 2:\n                g.message = c.r + \"Not enough input!\" + c.w\n                g.content = None#content.generate_songlist_display()\n                return\n\n        if not spotify:\n            credentials = generate_credentials()\n            token = credentials.get_access_token()\n            spotify = spotipy.Spotify(auth=token)\n\n        try:\n            playlist, tracks = grab_playlist(spotify, term)\n        except TypeError:\n            tracks = None\n\n        if not tracks:\n            show_message(\"Playlist '%s' not found!\" % term)\n            return\n\n        if not playlist['tracks']['total']:\n            show_message(\"Playlist '%s' by '%s' has 0 tracks!\" % (playlist['name'], playlist['owner']['id']))\n            return\n\n        msg = \"%s%s%s by %s%s%s\\n\\n\" % (c.g, playlist['name'], c.w, c.g, playlist['owner']['id'], c.w)\n        msg += \"Enter to begin matching or [q] to abort\"\n        g.message = msg\n        g.content = \"Tracks:\\n\"\n        for n, track in enumerate(tracks, 1):\n            trackname = '{0:<20} - {1}'.format(track['artists'][0]['name'], track['name'])\n            g.content += \"%03s  %s\" % (n, trackname)\n            g.content += \"\\n\"\n\n        screen.update()\n        entry = input(\"Continue? [Enter] > \")\n\n        if entry == \"\":\n            pass\n\n        else:\n            show_message(\"Playlist search abandoned!\")\n            return\n\n        songs = []\n        screen.clear()\n        itt = _match_tracks(tracks)\n\n        stash = config.SEARCH_MUSIC.get, config.ORDER.get\n        config.SEARCH_MUSIC.value = True\n        config.ORDER.value = \"relevance\"\n\n        try:\n            songs.extend(itt)\n\n        except KeyboardInterrupt:\n            util.xprint(\"%sHalted!%s\" % (c.r, c.w))\n\n        finally:\n            config.SEARCH_MUSIC.value, config.ORDER.value = stash\n\n        if songs:\n            util.xprint(\"\\n%s / %s songs matched\" % (len(songs), len(tracks)))\n            input(\"Press Enter to continue\")\n\n        msg = \"Contents of playlist %s%s - %s%s %s(%d/%d)%s:\" % (\n            c.y, playlist['owner']['id'], playlist['name'], c.w, c.b, len(songs), len(tracks), c.w)\n        failmsg = \"Found no playlist tracks for %s%s%s\" % (c.y, playlist['name'], c.w)\n\n        paginatesongs(songs, msg=msg, failmsg=failmsg)\n\n    else:\n        g.message = \"spotipy module must be installed for Spotify support\\n\"\n        g.message += \"see https://pypi.python.org/pypi/spotipy/\"\n"
  },
  {
    "path": "mps_youtube/config.py",
    "content": "import os\nimport re\nimport sys\nimport copy\nimport pickle\nimport json\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom urllib.parse import urlencode\n\ntry:\n    import pylast\n    has_pylast = True\nexcept ImportError:\n    has_pylast = False\n\nfrom . import g, c, paths, util\n\n\nmswin = os.name == \"nt\"\n\nclass ConfigItem:\n\n    \"\"\" A configuration item. \"\"\"\n\n    def __init__(self, name, value, minval=None, maxval=None, check_fn=None,\n            require_known_player=False, allowed_values=None):\n        \"\"\" If specified, the check_fn should return a dict.\n\n        {valid: bool, message: success/fail mesage, value: value to set}\n\n        \"\"\"\n        self.default = self.value = value\n        self.temp_value = None\n        self.name = name\n        self.type = type(value)\n        self.maxval, self.minval = maxval, minval\n        self.check_fn = check_fn\n        self.require_known_player = require_known_player\n        self.allowed_values = []\n        if allowed_values:\n            self.allowed_values = allowed_values\n\n    @property\n    def get(self):\n        \"\"\" Return value. \"\"\"\n        if self.temp_value is None:\n            return self.value\n        else:\n            return self.temp_value\n\n    @property\n    def display(self):\n        \"\"\" Return value in a format suitable for display. \"\"\"\n        return self.display_helper(self.value)\n\n    @property\n    def display_temp(self):\n        if self.temp_value is None: return \"\"\n        return self.display_helper(self.temp_value)\n\n    def display_helper(self, retval):\n        if self.name == \"max_res\":\n            retval = str(retval) + \"p\"\n\n        if self.name == \"encoder\":\n            retval = str(retval) + \" [%s]\" % (str(g.encoders[retval]['name']))\n\n        return retval\n\n    def set(self, value, is_temp=False):\n        \"\"\" Set value with checks. \"\"\"\n        # note: fail_msg should contain %s %s for self.name, value\n        #       success_msg should not\n        # pylint: disable=R0912\n        # too many branches\n\n        success_msg = fail_msg = \"\"\n        value = value.strip()\n        value_orig = value\n\n        # handle known player not set\n\n        if self.allowed_values and value not in self.allowed_values:\n            fail_msg = \"%s must be one of * - not %s\"\n            allowed_values = copy.copy(self.allowed_values)\n            if '' in allowed_values:\n                allowed_values[allowed_values.index('')] = \"<nothing>\"\n            fail_msg = fail_msg.replace(\"*\", \", \".join(allowed_values))\n\n        if self.require_known_player and \\\n                not util.is_known_player(Config.PLAYER.get):\n            fail_msg = \"%s requires mpv or mplayer, can't set to %s\"\n\n        # handle true / false values\n\n        elif self.type == bool:\n\n            if value.upper() in \"0 OFF NO DISABLED FALSE\".split():\n                value = False\n                success_msg = \"%s set to False\" % c.c(\"g\", self.name)\n\n            elif value.upper() in \"1 ON YES ENABLED TRUE\".split():\n                value = True\n                success_msg = \"%s set to True\" % c.c(\"g\", self.name)\n\n            else:\n                fail_msg = \"%s requires True/False, got %s\"\n\n        # handle int values\n\n        elif self.type == int:\n\n            if not value.isdigit():\n                fail_msg = \"%s requires a number, got %s\"\n\n            else:\n                value = int(value)\n\n                if self.maxval and self.minval:\n\n                    if not self.minval <= value <= self.maxval:\n                        m = \" must be between %s and %s, got \"\n                        m = m % (self.minval, self.maxval)\n                        fail_msg = \"%s\" + m + \"%s\"\n\n                if not fail_msg:\n                    dispval = value or \"None\"\n                    success_msg = \"%s set to %s\" % (c.c(\"g\", self.name),\n                                                    dispval)\n\n        # handle space separated list\n\n        elif self.type == list:\n            success_msg = \"%s set to %s\" % (c.c(\"g\", self.name), value)\n            value = value.split()\n\n        # handle string values\n\n        elif self.type == str:\n            dispval = value or \"None\"\n            success_msg = \"%s set to %s\" % (c.c(\"g\", self.name),\n                                            c.c(\"g\", dispval))\n\n        # handle failure\n\n        if fail_msg:\n            failed_val = value_orig.strip() or \"<nothing>\"\n            colvals = c.y + self.name + c.w, c.y + failed_val + c.w\n            return fail_msg % colvals\n\n        elif self.check_fn:\n            checked = self.check_fn(value)\n            value = checked.get(\"value\") or value\n\n            if checked['valid']:\n                value = checked.get(\"value\", value)\n                set_save(self, value, is_temp)\n                return checked.get(\"message\", success_msg)\n\n            else:\n                return checked.get('message', fail_msg)\n\n        elif success_msg:\n            set_save(self, value, is_temp)\n            return success_msg\n\ndef set_save(self, value, is_temp):\n    if not is_temp:\n        self.temp_value = None\n        self.value = value\n        Config.save()\n    else:\n        self.temp_value = value\n\ndef check_console_width(val):\n    \"\"\" Show ruler to check console width. \"\"\"\n    valid = True\n    message = \"-\" * val + \"\\n\"\n    message += \"console_width set to %s, try a lower value if above line ove\"\\\n        \"rlaps\" % val\n    return dict(valid=valid, message=message)\n\n\n# def check_api_key(key):\n#     \"\"\" Validate an API key by calling an API endpoint with no quota cost \"\"\"\n#     url = \"https://www.googleapis.com/youtube/v3/i18nLanguages\"\n#     query = {\"part\": \"snippet\", \"fields\": \"items/id\", \"key\": key}\n#     try:\n#         urlopen(url + \"?\" + urlencode(query)).read()\n#         message = \"The key, '\" + key + \"' will now be used for API requests.\"\n#\n#         # Make pafy use the same api key\n#         pafy.set_api_key(Config.API_KEY.get)\n#\n#         return dict(valid=True, message=message)\n#     except HTTPError:\n#         message = \"Invalid key or quota exceeded, '\" + key + \"'\"\n#         return dict(valid=False, message=message)\n\n\ndef check_ddir(d):\n    \"\"\" Check whether dir is a valid directory. \"\"\"\n    expanded = os.path.expanduser(d)\n    if os.path.isdir(expanded):\n        message = \"Downloads will be saved to \" + c.y + d + c.w\n        return dict(valid=True, message=message, value=expanded)\n\n    else:\n        message = \"Not a valid directory: \" + c.r + d + c.w\n        return dict(valid=False, message=message)\n\n\ndef check_win_pos(pos):\n    \"\"\" Check window position input. \"\"\"\n    if not pos.strip():\n        return dict(valid=True, message=\"Window position not set (default)\")\n\n    pos = pos.lower()\n    reg = r\"(TOP|BOTTOM).?(LEFT|RIGHT)\"\n\n    if not re.match(reg, pos, re.I):\n        msg = \"Try something like top-left or bottom-right (or default)\"\n        return dict(valid=False, message=msg)\n\n    else:\n        p = re.match(reg, pos, re.I).groups()\n        p = \"%s-%s\" % p\n        msg = \"Window position set to %s\" % p\n        return dict(valid=True, message=msg, value=p)\n\n\ndef check_win_size(size):\n    \"\"\" Check window size input. \"\"\"\n    if not size.strip():\n        return dict(valid=True, message=\"Window size not set (default)\")\n\n    size = size.lower()\n    reg = r\"\\d{1,4}x\\d{1,4}\"\n\n    if not re.match(reg, size, re.I):\n        msg = \"Try something like 720x480\"\n        return dict(valid=False, message=msg)\n\n    else:\n        return dict(valid=True, value=size)\n\n\ndef check_encoder(option):\n    \"\"\" Check encoder value is acceptable. \"\"\"\n    encs = g.encoders\n\n    if option >= len(encs):\n        message = \"%s%s%s is too high, type %sencoders%s to see valid values\"\n        message = message % (c.y, option, c.w, c.g, c.w)\n        return dict(valid=False, message=message)\n\n    else:\n        message = \"Encoder set to %s%s%s\"\n        message = message % (c.y, encs[option]['name'], c.w)\n        return dict(valid=True, message=message)\n\n\ndef check_player(player):\n    \"\"\" Check player exefile exists and get mpv version. \"\"\"\n    if util.has_exefile(player):\n        print(player)\n        util.assign_player(player)\n        if \"mpv\" in player:\n            version = \"%s.%s.%s\" % g.mpv_version\n            fmt = c.g, c.w, c.g, c.w, version\n            msg = \"%splayer%s set to %smpv%s (version %s)\" % fmt\n            return dict(valid=True, message=msg, value=player)\n\n        else:\n            msg = \"%splayer%s set to %s%s%s\" % (c.g, c.w, c.g, player, c.w)\n            return dict(valid=True, message=msg, value=player)\n\n    else:\n        if mswin and not (player.endswith(\".exe\") or player.endswith(\".com\")):\n            # Using mpv.exe has issues; use mpv.com\n            if \"mpv\" in player:\n                retval = check_player(player + \".com\")\n                if retval[\"valid\"]:\n                    return retval\n            return check_player(player + \".exe\")\n\n        else:\n            msg = \"Player application %s%s%s not found\" % (c.r, player, c.w)\n            return dict(valid=False, message=msg)\n\n\ndef check_lastfm_password(password):\n    if not has_pylast:\n        msg = \"pylast not installed\"\n        return dict(valid=False, message=msg)\n    password_hash = pylast.md5(password)\n    return dict(valid=True, value=password_hash)\n\n\nclass _Config:\n\n    \"\"\" Holds various configuration values. \"\"\"\n\n    _configitems = [\n            ConfigItem(\"order\", \"relevance\",\n                allowed_values=\"relevance date views rating title\".split()),\n            ConfigItem(\"user_order\", \"\", allowed_values =\n                [\"\"] + \"relevance date views rating\".split()),\n            ConfigItem(\"max_results\", 19, maxval=50, minval=1),\n            ConfigItem(\"console_width\", 80, minval=70,\n                maxval=880, check_fn=check_console_width),\n            ConfigItem(\"max_res\", 2160, minval=360, maxval=2160),\n            ConfigItem(\"player\", \"vlc\" + \".exe\" * mswin,\n                check_fn=check_player),\n            ConfigItem(\"playerargs\", \"\"),\n            ConfigItem(\"encoder\", 0, minval=0, check_fn=check_encoder),\n            ConfigItem(\"notifier\", \"\"),\n            ConfigItem(\"checkupdate\", True),\n            ConfigItem(\"show_player_keys\", True, require_known_player=True),\n            ConfigItem(\"fullscreen\", False, require_known_player=True),\n            ConfigItem(\"show_status\", True),\n            ConfigItem(\"always_repeat\", False),\n            ConfigItem(\"columns\", \"date user\"),\n            ConfigItem(\"ddir\", paths.get_default_ddir(), check_fn=check_ddir),\n            ConfigItem(\"overwrite\", True),\n            ConfigItem(\"show_video\", True),\n            ConfigItem(\"search_music\", False),\n            ConfigItem(\"window_pos\", \"\", check_fn=check_win_pos,\n                require_known_player=True),\n            ConfigItem(\"window_size\", \"\",\n                check_fn=check_win_size, require_known_player=True),\n            ConfigItem(\"download_command\", ''),\n            ConfigItem(\"lookup_metadata\", True),\n            ConfigItem(\"lastfm_username\", ''),\n            ConfigItem(\"lastfm_password\", '', check_fn=check_lastfm_password),\n            ConfigItem(\"lastfm_api_key\", ''),\n            ConfigItem(\"lastfm_api_secret\", ''),\n            ConfigItem(\"audio_format\", \"auto\",\n                allowed_values=\"auto webm m4a\".split()),\n            ConfigItem(\"video_format\", \"auto\",\n                allowed_values=\"auto webm mp4 3gp\".split()),\n            ConfigItem(\"pages\", 3, minval=1, maxval=100),\n            ConfigItem(\"autoplay\", False),\n            ConfigItem(\"set_title\", True),\n            ConfigItem(\"mpris\", not mswin),\n            ConfigItem(\"show_qrcode\", False),\n            ConfigItem(\"history\", True), \n            ConfigItem(\"input_history\", True),\n            ConfigItem(\"vlc_dummy_interface\", False)\n            ]\n\n    def __getitem__(self, key):\n        # TODO: Possibly more efficient algorithm, w/ caching\n        for i in self._configitems:\n            if i.name.upper() == key:\n                return i\n        raise KeyError\n\n    def __getattr__(self, name):\n        try:\n            # todo: remove this later\n            if name != 'API_KEY':\n                return self[name]\n        except KeyError:\n            raise AttributeError\n\n    def __iter__(self):\n        return (i.name.upper() for i in self._configitems)\n\n    def save(self):\n        \"\"\" Save current config to file. \"\"\"\n        config = {setting: self[setting].value for setting in self}\n\n        with open(g.CFFILE, \"w\") as cf:\n            json.dump(config, cf, indent=2)\n\n        util.dbg(c.p + \"Saved config: \" + g.CFFILE + c.w)\n\n    def convert_old_cf_to_json(self):\n        \"\"\"\n        check if old-style config exists,\n        convert old-style pickled binary config to json and save to disk,\n        delete old-style config\n        \"\"\"\n        if os.path.exists(g.OLD_CFFILE):\n            with open(g.OLD_CFFILE, \"rb\") as cf:\n                with open(g.CFFILE, \"w\") as cfj:\n                    json.dump(pickle.load(cf), cfj, indent=2)\n            os.remove(g.OLD_CFFILE)\n\n    def load(self):\n        \"\"\" Override config if config file exists. \"\"\"\n        if os.path.exists(g.CFFILE):\n            with open(g.CFFILE, \"r\") as cf:\n                saved_config = json.load(cf)\n\n            for k, v in saved_config.items():\n\n                try:\n                    self[k].value = v\n\n                except KeyError:  # Ignore unrecognised data in config\n                    util.dbg(\"Unrecognised config item: %s\", k)\n\n            # Update config files from versions <= 0.01.41\n            if isinstance(self.PLAYERARGS.get, list):\n                self.WINDOW_POS.value = \"top-right\"\n                redundant = (\"-really-quiet --really-quiet -prefer-ipv4 -nolirc \"\n                             \"-fs --fs\".split())\n\n                for r in redundant:\n                    util.dbg(\"removing redundant arg %s\", r)\n                    util.list_update(r, self.PLAYERARGS.value, remove=True)\n\n                self.PLAYERARGS.value = \" \".join(self.PLAYERARGS.get)\n                self.save()\n\nConfig = _Config()\ndel _Config # _Config is a singleton and should not have more instances\n# Prevent module from being deleted\n# http://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name\nref = sys.modules[__name__]\n# Any module trying to import config will get the Config object instead\nsys.modules[__name__] = Config\n"
  },
  {
    "path": "mps_youtube/content.py",
    "content": "import math\nimport copy\nimport random\n\n\nfrom . import g, c, config\nfrom .util import getxy, fmt_time, uea_pad, yt_datetime, F\n\ntry:\n    import qrcode\n    import io\n    HAS_QRCODE = True\nexcept ImportError:\n    HAS_QRCODE = False\n\n\n# In the future, this could support more advanced features\nclass Content:\n    pass\n\n\nclass PaginatedContent(Content):\n    def getPage(self, page):\n        raise NotImplementedError\n\n    def numPages(self):\n        raise NotImplementedError\n\n\nclass LineContent(PaginatedContent):\n    def getPage(self, page):\n        max_results = getxy().max_results\n        s = page * max_results\n        e = (page + 1) * max_results\n        return self.get_text(s, e)\n\n    def numPages(self):\n        return math.ceil(self.get_count()/getxy().max_results)\n\n    def get_text(self, s, e):\n        raise NotImplementedError\n\n    def get_count(self):\n        raise NotImplementedError\n\n\nclass StringContent(LineContent):\n    def __init__(self, string):\n        self._lines = string.splitlines()\n\n    def get_text(self, s, e):\n        return '\\n'.join(self._lines[s:e])\n\n    def get_count(self):\n        width = getxy().width\n        count = sum(len(i) // width + 1 for i in self._lines)\n        return count\n\n\ndef page_msg(page=0):\n    \"\"\" Format information about currently displayed page to a string. \"\"\"\n    if isinstance(g.content, PaginatedContent):\n        page_count = g.content.numPages()\n    else:\n        page_count = math.ceil(g.result_count/getxy().max_results)\n\n    if page_count > 1:\n        pagemsg = \"{}{}/{}{}\"\n        #start_index = max_results * g.current_page\n        return pagemsg.format('<' if page > 0 else '[',\n                              \"%s%s%s\" % (c.y, page+1, c.w),\n                              page_count,\n                              '>' if page + 1 < page_count else ']')\n    return None\n\n\ndef generate_songlist_display(song=False, zeromsg=None):\n    \"\"\" Generate list of choices from a song list.\"\"\"\n    # pylint: disable=R0914\n    if g.browse_mode == \"ytpl\":\n        return generate_playlist_display()\n\n    max_results = getxy().max_results\n\n    if not g.model:\n        g.message = zeromsg or \"Enter /search-term to search or [h]elp\"\n        return logo(c.g) + \"\\n\\n\"\n    g.rprompt = page_msg(g.current_page)\n\n    have_meta = all(x.ytid in g.meta for x in g.model)\n\n    user_columns = _get_user_columns() if have_meta else []\n    maxlength = max(x.length for x in g.model)\n    lengthsize = 8 if maxlength > 35999 else 7\n    lengthsize = 6 if maxlength < 6000 else lengthsize\n    reserved = 9 + lengthsize + len(user_columns)\n    cw = getxy().width\n    cw -= 1\n    title_size = cw - sum(1 + x['size'] for x in user_columns) - reserved\n    before = [{\"name\": \"idx\", \"size\": 3, \"heading\": \"Num\"},\n              {\"name\": \"title\", \"size\": title_size, \"heading\": \"Title\"}]\n    after = [{\"name\": \"length\", \"size\": lengthsize, \"heading\": \"Length\"}]\n    columns = before + user_columns + after\n\n    for n, column in enumerate(columns):\n        column['idx'] = n\n        column['sign'] = \"-\" if not column['name'] == \"length\" else \"\"\n\n    fmt = [\"%{}{}s  \".format(x['sign'], x['size']) for x in columns]\n    fmtrow = fmt[0:1] + [\"%s  \"] + fmt[2:]\n    fmt, fmtrow = \"\".join(fmt).strip(), \"\".join(fmtrow).strip()\n    titles = tuple([x['heading'][:x['size']] for x in columns])\n    hrow = c.ul + fmt % titles + c.w\n    out = \"\\n\" + hrow + \"\\n\"\n\n    for n, x in enumerate(g.model[:max_results]):\n        col = (c.r if n % 2 == 0 else c.p) if not song else c.b\n        details = {'title': x.title, \"length\": fmt_time(x.length)}\n        details = copy.copy(g.meta[x.ytid]) if have_meta else details\n        otitle = details['title']\n        details['idx'] = \"%2d\" % (n + 1)\n        details['title'] = uea_pad(columns[1]['size'], otitle)\n        #cat = details.get('category') or '-'\n        #details['category'] = 'pafy.get_categoryname(cat)'\n        details['ytid'] = x.ytid\n        line = ''\n\n        for z in columns:\n            fieldsize, field, direction = z['size'], z['name'], \"<\" if z['sign'] == \"-\" else \">\"\n            line += uea_pad(fieldsize, details[field], direction)\n            if not columns[-1] == z:\n                line += \"  \"\n\n        col = col if not song or song != g.model[n] else c.p\n        line = col + line + c.w\n        out += line + \"\\n\"\n\n    return out + \"\\n\" * (5 - len(g.model)) if not song else out\n\n\ndef generate_playlist_display():\n    \"\"\" Generate list of playlists. \"\"\"\n\n    if not g.ytpls:\n        g.message = c.r + \"No playlists found!\"\n        return logo(c.g) + \"\\n\\n\"\n    g.rprompt = page_msg(g.current_page)\n\n    cw = getxy().width\n    fmtrow = \"%s%-5s %s %-12s %-8s  %-2s%s\\n\"\n    fmthd = \"%s%-5s %-{}s %-12s %-9s %-5s%s\\n\".format(cw - 36)\n    head = (c.ul, \"Item\", \"Playlist\", \"Author\", \"Updated\", \"Count\", c.w)\n    out = \"\\n\" + fmthd % head\n\n    for n, x in enumerate(g.ytpls):\n        col = (c.g if n % 2 == 0 else c.w)\n        length = x.get('size') or \"?\"\n        length = \"%4s\" % length\n        title = x.get('title') or \"unknown\"\n        author = x.get('author') or \"unknown\"\n        updated = yt_datetime(x.get('updated'))[1]\n        title = uea_pad(cw - 36, title)\n        out += (fmtrow % (col, str(n + 1), title, author[:12], updated, str(length), c.w))\n\n    return out + \"\\n\" * (5 - len(g.ytpls))\n\n\ndef _get_user_columns():\n    \"\"\" Get columns from user config, return dict. \"\"\"\n    total_size = 0\n    user_columns = config.COLUMNS.get\n    user_columns = user_columns.replace(\",\", \" \").split()\n\n    defaults = {\"views\": dict(name=\"viewCount\", size=4, heading=\"View\"),\n                \"rating\": dict(name=\"rating\", size=4, heading=\"Rtng\"),\n                \"comments\": dict(name=\"commentCount\", size=4, heading=\"Comm\"),\n                \"date\": dict(name=\"uploaded\", size=8, heading=\"Date\"),\n                \"time\": dict(name=\"uploadedTime\", size=11, heading=\"Time\"),\n                \"user\": dict(name=\"uploaderName\", size=10, heading=\"User\"),\n                \"likes\": dict(name=\"likes\", size=4, heading=\"Like\"),\n                \"dislikes\": dict(name=\"dislikes\", size=4, heading=\"Dslk\"),\n                \"category\": dict(name=\"category\", size=8, heading=\"Category\"),\n                \"ytid\": dict(name=\"ytid\", size=12, heading=\"Video ID\")}\n\n    ret = []\n    for column in user_columns:\n        namesize = column.split(\":\")\n        name = namesize[0]\n\n        if name in defaults:\n            z = defaults[name]\n            nm, sz, hd = z['name'], z['size'], z['heading']\n\n            if len(namesize) == 2 and namesize[1].isdigit():\n                sz = int(namesize[1])\n\n            total_size += sz\n            cw = getxy().width\n            if total_size < cw - 18:\n                ret.append(dict(name=nm, size=sz, heading=hd))\n\n    return ret\n\n\ndef logo(col=None, version=\"\"):\n    \"\"\" Return text logo. \"\"\"\n    col = col if col else random.choice((c.g, c.r, c.y, c.b, c.p, c.w))\n    logo_txt = r\"\"\"                      _         _          \n                     | |       | |         \n  _   _  _____      _| |_ _   _| |__   ___ \n | | | |/ _ \\ \\ /\\ / / __| | | | '_ \\ / _ \\\n | |_| |  __/\\ V  V /| |_| |_| | |_) |  __/\n  \\__, |\\___| \\_/\\_/  \\__|\\__,_|_.__/ \\___|\n   __/ |                                   \n  |___/                                    \n    \"\"\"\n\n    version = \" v\" + version if version else \"\"\n    logo_txt = col + logo_txt + c.w + version\n    lines = logo_txt.split(\"\\n\")\n    length = max(len(x) for x in lines)\n    x, y, _ = getxy()\n    indent = (x - length - 1) // 2\n    newlines = (y - 12) // 2\n    indent, newlines = (0 if x < 0 else x for x in (indent, newlines))\n    lines = [\" \" * indent + l for l in lines]\n    logo_txt = \"\\n\".join(lines) + \"\\n\" * newlines\n    return \"\" if g.debug_mode or g.no_textart else logo_txt\n\n\ndef playlists_display():\n    \"\"\" Produce a list of all playlists. \"\"\"\n    if not g.userpl:\n        g.message = F(\"no playlists\")\n        return generate_songlist_display() if g.model else (logo(c.y) + \"\\n\\n\")\n\n    maxname = max(len(a) for a in g.userpl)\n    out = \"      {0}Local Playlists{1}\\n\".format(c.ul, c.w)\n    start = \"      \"\n    fmt = \"%s%s%-3s %-\" + str(maxname + 3) + \"s%s %s%-7s%s %-5s%s\"\n    head = (start, c.b, \"ID\", \"Name\", c.b, c.b, \"Count\", c.b, \"Duration\", c.w)\n    out += \"\\n\" + fmt % head + \"\\n\\n\"\n\n    for v, z in enumerate(sorted(g.userpl)):\n        n, p = z, g.userpl[z]\n        l = fmt % (start, c.g, v + 1, n, c.w, c.y, str(len(p)), c.y,\n                   p.duration, c.w) + \"\\n\"\n        out += l\n\n    return out\n\n\ndef qrcode_display(url):\n    if not HAS_QRCODE:\n        return \"(Install 'qrcode' to generate them)\"\n    qr = qrcode.QRCode()\n    buf = io.StringIO()\n    buf.isatty = lambda: True\n    qr.add_data(url)\n    qr.print_ascii(out=buf)\n    return buf.getvalue()\n\ndef get_last_query():\n    # Prevent crash if no last query\n    if g.last_search_query == (None, None) or \\\n            'func' not in g.last_search_query[1]:\n        g.content = logo()\n        g.message = \"No playlist loaded\"\n        return\n\n    songs_list_or_func = g.last_search_query[1]['func']\n    if callable(songs_list_or_func):\n        songs = songs_list_or_func(0,None)\n    else:\n        songs = songs_list_or_func\n\n    return songs"
  },
  {
    "path": "mps_youtube/contentquery.py",
    "content": "\"\"\"\n    ContentQuery is an abstraction layer between the the pafy.call_gdata\n    and the listViews.\n\n    It lets you treat A query as a list of all the results, even though\n    data is only queried when requested.\n\"\"\"\n\nfrom . import util, pafy\n\n\nclass ContentQuery:\n    \"\"\" A wrapper for pafy.call_gdata. I lets you treat a search as a list,\n        but the results will only be fetched when needed.\n    \"\"\"\n    maxresults = 0\n    pdata = []\n    nextpagetoken = None\n\n    datatype = None\n    query = None\n    api = None\n\n    def __init__(self, datatype, api, query):\n        # Perform initial API call, setBoundaries\n        # call parseData\n\n        self.datatype = datatype\n        self.query = query\n        self.api = api\n\n        self.pdata = []\n\n        self._perform_api_call()\n\n    def __getitem__(self, iid):\n        # Check if we already got the item or slice needed\n        # Call and parse nextPage as long as you dont have the data\n        # needed.\n        last_id = iid.stop if iid.__class__ == slice else iid\n        last_datapoint = min(last_id, self.maxresults)\n        while len(self.pdata) < last_datapoint:\n            self._perform_api_call()\n        return self.pdata[iid]\n\n    def count(self):\n        \"\"\" Returns how many items are in the list \"\"\"\n        return self.maxresults\n\n    def __len__(self):\n        return abs(self.count())\n\n    def _perform_api_call(self):\n        # Include nextPageToken if it is set\n        # qry = dict(\n        #     pageToken=self.nextpagetoken,\n        #     **(self.query)\n        #     ) if self.nextpagetoken else self.query\n\n        # Run query\n        util.dbg(\"CQ.query\", self.query)\n        data = pafy.channel_search(self.query)#pafy.call_gdata(self.api, qry)\n        \n        self.maxresults = len(data)#int(data.get(\"pageInfo\").get(\"totalResults\"))\n        self.nextpagetoken = None#data.get(\"nextPageToken\")\n\n        for obj in data:\n            self.pdata.append(self.datatype(obj))\n"
  },
  {
    "path": "mps_youtube/description_parser.py",
    "content": "\"\"\"\n    Module for trying to parse and retrieve song data from descriptions\n\"\"\"\nimport re\nimport random\n\n\ndef calculate_certainty(line):\n    \"\"\" Determine if a line contains a  \"\"\"\n    certainty_indexes = [\n        {'regex': r\"(?:\\(?(?:\\d{0,4}:)?\\d{0,2}:\\d{0,2}\\)?(?: - )?){1,2}\",\n         'weight': 1},\n        {'regex': r\"(([\\w&()\\[\\]'\\.\\/ ]+)([ ]?[-]+[ ]?)([\\w&()\\[\\]'\\.\\/ ]+))+\",\n         'weight': 0.75},\n        {'regex': r\"^([\\d]+[. ]+)\",\n         'weight': 1}\n    ]\n\n    certainty = 0.0\n    for method in certainty_indexes:\n        if re.match(method['regex'], line):\n            certainty += method['weight']\n\n    return certainty / len(certainty_indexes)\n\n\ndef has_artist(text):\n    \"\"\" Determine if the strìng has artist or not \"\"\"\n    regex = r\"(?:([\\w&()\\[\\]'\\.\\/ ]+)(?:[ ]?[-]+[ ]?)([\\w&()\\[\\]'\\.\\/ ]+))+\"\n    return not re.match(regex, text)\n\n\ndef strip_string(text, single=False):\n    \"\"\" Strip an artist-combo string \"\"\"\n    # Removes timestamps\n    ts_reg = r\"(?:\\(?(?:\\d{0,4}:)?\\d{1,2}:\\d{1,2}\\)?(?: - )?){1,2}\"\n    text = re.sub(ts_reg, \"\", text)\n\n    # Removes Tracknumbers.\n    text = re.sub(r\"^([\\d]+[. ]+)\", \"\", text)\n\n    # Removes starting with non words\n    text = re.sub(r\"^[^\\w&()\\[\\]'\\.\\/]\", \"\", text, flags=re.MULTILINE)\n\n    artist, track = None, None\n    if not single:\n        rgex = r\"(?:([\\w&()\\[\\]'\\.\\/ ]+)(?:[ ]?[-]+[ ]?)([\\w&()\\[\\]'\\.\\/ ]+))+\"\n        artist, track = (re.findall(rgex, text)[0])\n    else:\n        track = text\n\n    return artist, track\n\n\ndef long_substr(data):\n    \"\"\" https://stackoverflow.com/a/2894073 \"\"\"\n    substr = ''\n    if len(data) > 1 and len(data[0]) > 0:\n        for i in range(len(data[0])):\n            for j in range(len(data[0])-i+1):\n                if j > len(substr) and is_substr(data[0][i:i+j], data):\n                    substr = data[0][i:i+j]\n    return substr\n\n\ndef is_substr(find, data):\n    \"\"\" Check if is substring \"\"\"\n    if len(data) < 1 and len(find) < 1:\n        return False\n    for i, _ in enumerate(data):\n        if find not in data[i]:\n            return False\n    return True\n\n\ndef artist_from_title(title):\n    \"\"\" Try to determine an artist by doing a search on the video\n        and try to find the most common element by n number of times looking\n        for the most common substring in a subset of the results from youtube\n    \"\"\"\n    query = {}\n    query['q'] = title\n    query['type'] = 'video'\n    query['fields'] = \"items(snippet(title))\"\n    query['maxResults'] = 50\n    query['part'] = \"snippet\"\n\n    results = None#pafy.call_gdata('search', query)['items']\n    titles = [x['snippet']['title'].upper() for x in results]\n\n    alts = {}\n    for _ in range(100):\n        random.shuffle(titles)\n        subset = titles[:10]\n        string = long_substr(subset).strip()\n        if len(string) > 3:\n            alts[string] = alts.get(string, 0) + 1\n\n    best_string = None\n    if len(alts) == 1:\n        best_string = list(alts.keys())[0].capitalize()\n    else:\n        best_guess = 99999\n        best_string = None\n\n        for key in list(alts.keys()):\n            current_guess = title.upper().find(key)\n            if current_guess < best_guess:\n                best_guess = current_guess\n                best_string = key.capitalize()\n\n    best_string = re.sub(r\"([^\\w]+)$\", \"\", best_string)\n    best_string = re.sub(r\"^([^\\w]+)\", \"\", best_string)\n    return best_string\n\n\ndef parse(text, title=\"Unknown\"):\n    \"\"\" Main function\"\"\"\n\n    # Determine a certainty index for each line\n    lines = []\n    for line in text.split('\\n'):\n        lines.append((calculate_certainty(line), line))\n\n    # Get average from all strings\n    certainty_average = sum([x[0] for x in lines]) / len(lines)\n\n    # Single out lines with above average certainty index\n    lines = filter(lambda a: a is not None,\n                   [x if x[0] > certainty_average else None for x in lines])\n\n    # Determine if they are artist combo strings or only title\n    cmbs = []\n    for line in lines:\n        is_ac = has_artist(line[1])\n        cmbs.append(strip_string(line[1], is_ac))\n\n    # No or very few tracklists will ommit aritsts or add artist information\n    # on only a few select number of tracks, therefore we count entries with\n    # and without artist, and remove the anomalities IF the number of\n    # anomalities are small enough\n\n    counters = {'has': 0, 'not': 0}\n    for combo in cmbs:\n        counters['has' if combo[0] else 'not'] += 1\n\n    dominant = 'has' if counters['has'] > counters['not'] else 'not'\n\n    diff = abs(counters['has'] - counters['not'])\n    if diff > sum([counters['has'], counters['not']]):\n        print(\"Too many anomalities detected\")\n        return []\n\n    if dominant == 'has':\n        cmbs = filter(lambda a: a is not None,\n                      [x if x[0] is not None else None for x in cmbs])\n    else:\n        arti = artist_from_title(title)\n        cmbs = filter(lambda a: a is not None,\n                      [(arti, x[1]) if x[0] is None else None for x in cmbs])\n    return list(cmbs)\n"
  },
  {
    "path": "mps_youtube/g.py",
    "content": "\"\"\" Module for holding globals that are needed throught mps-youtube. \"\"\"\n\nimport collections\nimport os\nimport sys\n\nfrom . import c, paths\nfrom .playlist import Playlist\n\nvolume = None\ntranscoder_path = \"auto\"\ndelete_orig = True\nencoders = []\nmuxapp = False\nmeta = {}\nartist = \"\" # Mostly used for scrobbling purposes\nalbum = \"\" # Mostly used for scrobbling purposes\nscrobble = False\nscrobble_queue = []\nlastfm_network = None\ndetectable_size = True\ncommand_line = False\ndebug_mode = False\npreload_disabled = False\nytpls = []\nmpv_version = 0, 0, 0\nmpv_options = None\nmpv_usesock = False\nmplayer_version = 0\nmprisctl = None\nbrowse_mode = \"normal\"\npreloading = []\n# expiry = 5 * 60 * 60  # 5 hours\nno_clear_screen = False\nno_textart = False\nmax_retries = 3\nmax_cached_streams = 1500\nusername_query_cache = collections.OrderedDict()\nmodel = Playlist(name=\"model\")\nlast_search_query = (None, None)\ncurrent_page = 0\nresult_count = 0\nrprompt = None\nactive = Playlist(name=\"active\")\nuserpl = {}\nuserhist = {}\npafs = collections.OrderedDict()\nstreams = collections.OrderedDict()\npafy_pls = {}  #\nselected_pafy_pls_id = ''\nlast_opened = message = content = \"\"\nsuffix = \"3\" # Python 3\nOLD_CFFILE = os.path.join(paths.get_config_dir(), \"config\")\nCFFILE = os.path.join(paths.get_config_dir(), \"config.json\")\nTCFILE = os.path.join(paths.get_config_dir(), \"transcode\")\nOLD_PLFILE = os.path.join(paths.get_config_dir(), \"playlist\" + suffix)\nPLFILE = os.path.join(paths.get_config_dir(), \"playlist_v2\")\nPLFOLDER = os.path.join(paths.get_config_dir(), \"playlists\")\nOLDHISTFILE = os.path.join(paths.get_config_dir(), \"play_history\")\nHISTFILE = os.path.join(paths.get_config_dir(), \"play_history.m3u\")\nCACHEFILE = os.path.join(paths.get_config_dir(), \"cache_py_\" + sys.version[0:5])\nREADLINE_FILE = None\nPLAYER_OBJ = None\ncategories = {\n        \"film\":      1,\n        \"autos\":     2,\n        \"music\":    10,\n        \"sports\":   17,\n        \"travel\":   19,\n        \"gaming\":   20,\n        \"blogging\": 21,\n        \"news\":     25\n}\nplayerargs_defaults = {\n    \"mpv\": {\n        \"msglevel\": {\n            \"<0.4\": \"--msglevel=all=no:statusline=status\",\n            \">=0.4\": \"--msg-level=all=no,statusline=status\",\n        },\n        \"title\": \"--force-media-title\",\n        \"fs\": \"--fs\",\n        \"novid\": \"--no-video\",\n        \"ignidx\": \"--demuxer-lavf-o=fflags=+ignidx\",\n        \"geo\": \"--geometry\"},\n    \"mplayer\": {\n        \"title\": \"-title\",\n        \"fs\": \"-fs\",\n        \"novid\": \"-novideo\",\n        # \"ignidx\": \"-lavfdopts o=fflags=+ignidx\".split()\n        \"ignidx\": \"\",\n        \"geo\": \"-geometry\"},\n    \"vlc\": {\n        \"title\": \"--meta-title\"}\n    }\nargument_commands = []\ncommands = []\n\ntext = {\n    \"exitmsg\": (\"*yewtube - https://github.com/iamtalhaasghar/yewtube is a fork of\\nmps-youtube - *https://github.com/mps-youtube/mps-youtube*\"\n                \"\\nReleased under the GPLv3 license\\n\"\n                \"(c) 2021 iamtalhaasghar\\n(c) 2014, 2015 np1 and contributors*\\n\"\"\"),\n    \"exitmsg_\": (c.r, c.b, c.r, c.w),\n\n    # Error / Warning messages\n\n    'no playlists': \"*No saved playlists found!*\",\n    'no playlists_': (c.r, c.w),\n    'pl bad name': '*&&* is not valid a valid name. Ensure it starts with'\n                   ' a letter or _',\n    'pl bad name_': (c.r, c.w),\n    'pl not found': 'Playlist *&&* unknown. Saved playlists are shown '\n                    'above',\n    'pl not found_': (c.r, c.w),\n    'pl not found advise ls': 'Playlist \"*&&*\" not found. Use *ls* to '\n                              'list',\n    'pl not found advise ls_': (c.y, c.w, c.g, c.w),\n    'pl empty': 'Playlist is empty!',\n    'advise add': 'Use *add N* to add a track',\n    'advise add_': (c.g, c.w),\n    'advise search': 'Search for items and then use *add* to add them',\n    'advise search_': (c.g, c.w),\n    'no data': 'Error fetching data. Possible network issue.'\n               '\\n*&&*',\n    'no data_': (c.r, c.w),\n    'use dot': 'Start your query with a *.* to perform a search',\n    'use dot_': (c.g, c.w),\n    'cant get track': 'Problem playing last item: *&&*',\n    'cant get track_': (c.r, c.w),\n    'track unresolved': 'Sorry, this track is not available',\n    'no player': '*&&* was not found on this system',\n    'no player_': (c.y, c.w),\n    'no pl match for rename': '*Couldn\\'t find matching playlist to '\n                              'rename*',\n    'no pl match for rename_': (c.r, c.w),\n    'invalid range': \"*Invalid item / range entered!*\",\n    'invalid range_': (c.r, c.w),\n    '-audio': \"*Warning* - the filetype you selected (&&) has no audio!\",\n    '-audio_': (c.y, c.w),\n    'no mix': 'No mix is available for the selected video',\n    'mix only videos': 'Mixes are only available for videos',\n    'invalid item': '*Invalid item entered!*',\n    'duplicate tracks': '*Warning* - duplicate track(s) && added to '\n                        'playlist!',\n    'duplicate tracks_': (c.y, c.w),\n\n    # Info messages..\n\n    'select mux': (\"Select [*&&*] to mux audio or [*Enter*] to download \"\n                   \"without audio\\nThis feature is experimental!\"),\n    'select mux_': (c.y, c.w, c.y, c.w),\n    'pl renamed': 'Playlist *&&* renamed to *&&*',\n    'pl renamed_': (c.y, c.w, c.y, c.w),\n    'pl saved': 'Playlist saved as *&&*.  Use *ls* to list playlists',\n    'pl saved_': (c.y, c.w, c.g, c.w),\n    'pl loaded': 'Loaded playlist *&&* as current playlist',\n    'pl loaded_': (c.y, c.w),\n    'pl viewed': 'Showing playlist *&&*',\n    'pl viewed_': (c.y, c.w),\n    'pl help': 'Enter *open <name or ID>* to load a playlist',\n    'pl help_': (c.g, c.w),\n    'added to pl': '*&&* tracks added (*&&* total [*&&*]). Use *vp* to '\n                   'view',\n    'added to pl_': (c.y, c.w, c.y, c.w, c.y, c.w, c.g, c.w),\n    'added to saved pl': '*&&* tracks added to *&&* (*&&* total [*&&*])',\n    'added to saved pl_': (c.y, c.w, c.y, c.w, c.y, c.w, c.y, c.w),\n    'song move': 'Moved *&&* to position *&&*',\n    'song move_': (c.y, c.w, c.y, c.w),\n    'song sw': (\"Switched item *&&* with *&&*\"),\n    'song sw_': (c.y, c.w, c.y, c.w),\n    'current pl': \"This is the current playlist. Use *save <name>* to save\"\n                  \" it\",\n    'current pl_': (c.g, c.w),\n    'help topic': (\"  Enter *help <topic>* for specific help:\"),\n    'help topic_': (c.y, c.w),\n    'songs rm': '*&&* tracks removed &&',\n    'songs rm_': (c.y, c.w),\n    'mkp empty': \"*&&* is either empty or doesn't exist\",\n    'mkp empty_': (c.b, c.r),\n    'mkp parsed': \"*&&* entries found in *&&*\",\n    'mkp parsed_': (c.g, c.w, c.b, c.w),\n    'mkp finding': \"Finding the best match for *&&* ...\",\n    'mkp finding_': (c.y, c.w),\n    'mkp desc unknown': \"Unknown tabletype, *do a new search*\",\n    'mkp desc unknown_': (c.y, c.w),\n    'mkp desc which data': \"Which *tracks* to include?\",\n    'mkp desc which data_': (c.y, c.w),\n    'mkp no valid': \"*No valid tracks found in that description*\",\n    'mkp no valid_': (c.y, c.w)}\n"
  },
  {
    "path": "mps_youtube/helptext.py",
    "content": "\"\"\"\n    Holds all help text\n\"\"\"\nimport pathlib\nimport re\nimport socket\nfrom urllib.error import HTTPError, URLError\nfrom urllib.request import urlopen\n\nfrom . import c, g\nfrom .util import F, get_near_name\n\n\ndef helptext():\n    \"\"\" Return a list of help categories, with their contents. \"\"\"\n\n    return [\n        (\"basic\", \"Basics\", \"\"\"\n\n    {0}Basic Usage{1}\n\n    Use {2}/{1} or {2}.{1} to prefix your search query.  e.g., {2}/pink floyd{1}\n\n    Then, when results are shown:\n\n        {2}<number(s)>{1} - play specified items, separated by commas.\n                      e.g., {2}1-3,5{1} plays items 1, 2, 3 and 5.\n\n        {2}i <number>{1} - view information on video <number>\n        {2}c <number>{1} - view comments for video <number>\n        {2}d <number>{1} - download video <number>\n        {2}r <number>{1} - show videos related to video <number>\n        {2}u <number>{1} - show videos uploaded by uploader of video <number>\n        {2}x <number>{1} - copy item <number> url to clipboard. (See the note below)\n        Note: This feature requires `pyperclip` which is installed automatically when you install yewtube but\n        Linux users further need to install `xsel` or `xclip` manually using apt, dnf, pacman, zypper or whatever package manager you use.\n        Visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error for more info.\n\n        {2}q{1}, {2}quit{1} - exit yewtube\n    \"\"\".format(c.ul, c.w, c.y)),\n        (\"search\", \"Searching and Retrieving\", \"\"\"\n    {0}Searching and Retrieving{1}\n\n    {2}set search_music false{1} - search all YouTube categories.\n    {2}set search_music true{1}  - search only YouTube music category.\n\n    {2}/<query>{1} or {2}.<query>{1} to search for videos. e.g., {2}/daft punk{1}\n    Search Arguments:\n    {2}-d, --duration{1}    Can be any/short/medium/long\n    {2}-a, --after{1}       Date in {2}YYYY-MM-DD{1} or {2}YYYY-MM-DD{1}T{2}HH:MM{1} format\n    {2}-l, --live{1}        Limit search to livestreams\n    {2}-c, --category{1}    Search within a category, (number or string)\n                      Available categories:\n                      {2}{3}{1}\n\n    {2}//<query>{1} or {2}..<query>{1} - search for YouTube playlists. e.g., \\\n    {2}//80's music{1}\n    {2}n{1} and {2}p{1} - continue search to next/previous pages.\n    {2}p <number>{1} - switch to page <number>.\n\n    {2}album <album title>{1} - Search for matching tracks using album title\n    {2}channels <Channel name>{1} - Search for channels by channelname\n    {2}live <category>{1} - Search for livestreams from a range of categories.\n    Categories: {2}{3}{1}\n\n    {2}mkp <fullfilepath>{1} - Creates a playlist automatically with video titles from fullfilepath\n    <fullfilepath>: Full path of text file with one title per line\n\n    {2}mkp -d <search result number>{1} - Create a playlist based on tracks\n    listed in that videos description. (Alternatively one can use {2}--description{1})\n\n    {2}user <username>{1} - list YouTube uploads by <username>.\n    {2}user <username>/<query>{1} - as above, but matches <query>.\n    {2}userpl <username>{1} - list YouTube playlists created by <username>.\n    {2}pl <url or id>{1} - Open YouTube playlist by url or id.\n    {2}url <url or id>{1} - Retrieve specific YouTube video by url or id.\n    {2}url <url> <url> ... <url>{1} - Retrieve specific YouTube videos by url or id.\n    {2}url_file <file_absolute_path>{1} - Retrieve YouTube videos by url or id from a .txt file.\n    File format : .txt, with one url or id by line.\n\n    {2}r <number>{1} - show videos related to video <number>.\n    {2}u <number>{1} - show videos uploaded by uploader of video <number>.\n    {2}c <number>{1} - view comments for video <number>\n    \"\"\".format(c.ul, c.w, c.y, \", \".join(g.categories.keys()))),\n\n        (\"edit\", \"Editing / Manipulating Results\", \"\"\"\n    {0}Editing and Manipulating Results{1}\n\n    {2}rm <number(s)>{1} - remove items from displayed results.\n    {2}sw <number>,<number>{1} - swap two items.\n    {2}mv <number>,<number>{1} - move item <number> to position <number>.\n    {2}save <name>{1} - save displayed items as a local playlist.\n    {2}mix <number>{1} - show YouTube mix playlist from item in results.\n\n    {2}shuffle{1} - Shuffle the displayed results.\n    {2}shuffle all{1} - Shuffle entire loaded playlist.\n    {2}reverse{1} or {2}reverse <number>-<number>{1} - Reverse the displayed items or item range.\n    {2}reverse all{1} - Reverse order of entire loaded playlist.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"download\", \"Downloading and Playback\", \"\"\"\n    {0}Downloading and Playback{1}\n\n    {2}set show_video true{1} - play video instead of audio.\n\n    {2}<number(s)>{1} - play specified items, separated by commas.\n                  e.g., {2}1-3,5{1} plays items 1, 2, 3 and 5\n\n    {2}d <number>{1} - view downloads available for an item.\n    {2}da <number(s)>{1} - download best available audio file(s).\n    {2}dv <number(s)>{1} - download best available video file(s).\n    {2}dapl <url or id>{1} - download YouTube playlist (audio) by url or id.\n    {2}dvpl <url or id>{1} - download YouTube playlist (video) by url or id.\n    {2}daupl <username>{1} - download user's YouTube playlists (audio).\n    {2}dvupl <username>{1} - download user's YouTube playlists (video).\n    {2}dlurl <url or id>{1} - download a YouTube video by url or video id.\n    {2}daurl <url or id>{1} - download best available audio of YouTube video by url or video id.\n    {2}playurl <url or id>{1} - play a YouTube video by url or id.\n    {2}browserplay <number>{1} - open a specified previous search in browser.\n\n    {2}all{1} or {2}*{1} - play all displayed items.\n    {2}repeat <number(s)>{1} - play and repeat the specified items.\n    {2}shuffle <number(s)>{1} - play specified items in random order.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"dl-command\", \"Downloading Using External Application\", \"\"\"\n    {0}Download Using A Custom Application{1}\n\n    Use {2}set download_command <command>{1} to specify a custom command to use for\n    downloading.\n\n    mps-youtube will make the following substitutions:\n\n    %u - url of the remote file to download\n    %d - download directory as set in DDIR in mps-youtube config\n    %f - filename (determined by title and filetype)\n    %F - full file path (%d/%f)\n    %i - youtube video id\n\n    for example, to download using aria2c (http://aria2.sourceforge.net), enter:\n\n        {2}set download_command aria2c --dir=%d --out=%f %u{1}\n\n    Note that using a custom download command does not support transcoding the\n    downloaded file to another format using mps-youtube.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n\n        (\"encode\", \"Encoding to MP3 and other formats\", \"\"\"\n    {0}Encoding to MP3 and other formats{1}\n\n    Enter {2}encoders{1} to view available encoding presets\n    Enter {2}set encoder <number>{1} to apply an encoding preset for downloads\n\n    This feature requires that ffmpeg or avconv is installed on your system and is\n    available in the system path.\n\n    The encoding presets can be modified by editing the text config file which\n    resides at:\n       {3}\n    \"\"\".format(c.ul, c.w, c.y, g.TCFILE)),\n\n        (\"playlists\", \"Using Local Playlists\", \"\"\"\n    {0}Using Local Playlists{1}\n\n    {2}add <number(s)>{1} - add items to the current playlist.\n    {2}add <number(s)> <playlist>{1} - add items to the specified playlist.\n         (<playlist> will be created if it doesn't already exist)\n\n    {2}vp{1} - view current playlist.\n    {2}ls{1} - list saved playlists.\n    {2}mv <old name or ID> <new name>{1} - rename a playlist.\n    {2}rmp <playlist_name or ID>{1} - delete a playlist from disk.\n\n    {2}open <name or ID>{1} - open a saved playlist as the current playlist.\n    {2}play <name or ID>{1} - play a saved playlist directly.\n    {2}view <name or ID>{1} - view a playlist (current playlist left intact).\n    {2}save{1} or {2}save <name>{1} - save the displayed items as a playlist.\n\n    {2}rm <number(s)>{1} - remove items from displayed results.\n    {2}sw <number>,<number>{1} - swap two items.\n    {2}mv <number>,<number>{1} - move item <number> to position <number>.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"history\", \"Accessing Local History\", \"\"\"\n    {0}Accessing Local History{1}\n\n    Access songs that have been played within yewtube\n\n        {2}history{1} - displays a list of songs contained in history\n        {2}history clear{1} - clears the song history\n        {2}history recent{1} - displays a list of recent played songs\n        {2}set history on|off{1} - toggles history recording\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"invoke\", \"Invocation Parameters\", \"\"\"\n    {0}Invocation{1}\n\n    All yewtube commands can be entered from the command line.  For example;\n\n      {2}yt dlurl <url or id>{1} to download a YouTube video by url or id\n      {2}yt playurl <url or id>{1} to play a YouTube video by url or id\n      {2}yt /mozart{1} to search\n      {2}yt //best songs of 2010{1} for a playlist search\n      {2}yt play <playlist name or ID>{1} to play a saved playlist\n      {2}yt ls{1} to list saved playlists\n\n    For further automation, a series of commands can be entered separated by\n    commas (,).  E.g.,\n\n      {2}yt open 1, 2-4{1} - play items 2-4 of first saved playlist\n      {2}yt //the doors, 1, all -a{1} - open YouTube playlist and play audio\n\n    If you need to enter an actual comma on the command line, use {2},,{1} instead.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"config\", \"Configuration Options\", \"\"\"\n    {0}Configuration{1}\n\n    {2}set{1} - view current configuration\n    {2}set <item> default{1} - set an item to its default value\n    {2}set all default{1} - restore default settings\n    {2}set checkupdate true|false{1} - check for updates on exit\n    {2}set columns <columns>{1} - select extra displayed fields in search results:\n         (valid: views comments rating date time user likes dislikes category ytid)\n    {2}set ddir <download direcory>{1} - set where downloads are saved\n    {2}set download_command <command>{1} - type {2}help dl-command{1} for info\n    {2}set encoder <number>{1} - set encoding preset for downloaded files\n    {2}set fullscreen true|false{1} - output video content in full-screen mode\n    {2}set always_repeat true|false{1} - always in repeat mode without repeat <number>\n    {2}set max_res <number>{1} - play / download maximum video resolution height{3}\n    {2}set notifier <notifier app>{1} - call <notifier app> with each new song title\n    {2}set order <relevance|date|views|rating>{1} search result ordering\n    {2}set user_order <<nothing>|relevance|date|views|rating>{1} user upload list\n        result ordering, leave blank for the same as order setting\n    {2}set overwrite true|false{1} - overwrite existing files (skip if false)\n    {2}set player <player app>{1} - use <player app> for playback\n    {2}set playerargs <args>{1} - use specified arguments with player\n    {2}set lookup_metadata true|false{1} - lookup metadata using Last.fm\n    {2}set lastfm_username <username>{1} - scrobble to this Last.fm userprofile\n    {2}set lastfm_password <password>{1} - Last.fm password (saved in hash form)\n    {2}set lastfm_api <key>{1} - API key needed for Last.fm mps-yt authorization\n    {2}set lastfm_secret <key>{1} - secret for the Last.fm API key\n    {2}set search_music true|false{1} - search only music (all categories if false)\n    {2}set show_mplayer_keys true|false{1} - show keyboard help for mplayer and mpv\n    {2}set show_status true|false{1} - show status messages and progress\n    {2}set show_video true|false{1} - show video output (audio only if false)\n    {2}set window_pos <top|bottom>-<left|right>{1} - set player window position\n    {2}set window_size <number>x<number>{1} - set player window width & height\n    {2}set audio_format <auto|m4a|webm>{1} - set default music audio format\n    {2}set video_format <auto|mp4|webm|3gp>{1} - set default music video format\n    {2}set set_title true|false{1} - change window title\n    {2}set show_qrcode true|false{1} - show qrcode of the URL in the video information panel\n    {2}set history true|false{1} - record play history\n    {2}set input_history true|false{1} - record command input history\n    {2}set vlc_dummy_interface true|false{1} - whether to hide VLC GUI or not (hides when true)\n\n    Additionally, {2}set -t{1} may be used to temporarily change a setting without\n    saving it to disk\n    \"\"\".format(c.ul, c.w, c.y, '\\n{0}set max_results <number>{1} - show <number> re'\n               'sults when searching (max 50)'.format(c.y, c.w) if not\n               g.detectable_size else '')),\n\n        (\"lastfm\", \"Last.fm configuration\", \"\"\"\n    {0}Configure Last.fm{1}\n\n    pylast needs to be installed for Last.fm support. See https://github.com/pylast/pylast.\n\n    Use {2}set{1} to set your Last.fm login credenditals, e.g. {2}set lastfm_username jane_doe{1}.\n    Similarly, you also have to provide an API key and it's corresponding secret.\n    An API key can be retrieved from https://www.last.fm/api/account/create.\n\n    Your Last.fm configuration is saved and automatically reloaded when mps-youtube starts.\n\n    After having set the required information, a connection can also be established\n    with {2}lastfm_connect{1}. Additionally, {2}lastfm_connect{1} provides verbose error messages.\n\n    For now, Last.fm support only works with the {2}album{1} command.\n    \"\"\".format(c.ul, c.w, c.y)),\n\n        (\"tips\", \"Advanced Tips\", \"\"\"\n    {0}Advanced Tips{1}\n\n    Use {2}-w{1}, {2}-f{1} or {2}-a{1} with your choice to override the configured\\\n     setting and\n    play items in windowed, fullscreen or audio modes.  E.g., 1-4 -a\n\n    When specifying columns with {2}set columns{1} command, append :N to set\\\n     width.\n        E.g.: {2}set columns date views user:17 likes{1}\n\n    When using {2}open{1}, {2}view{1} or {2}play{1} to access a local playlist, \\\n    you can enter\n    the first few characters instead of the whole name.\n\n    Use {2}5-{1} to select items 5 upward and {2}-5{1} to select up to item 5. \\\n    This can be\n    included with other choices. e.g., 5,3,7-,-2\n    You can use spaces instead of commas: 5 3 7- -2\n    Reversed ranges also work. eg., 5-2\n\n    {2}dump{1} - to show entire contents of an opened YouTube playlist.\n           (useful for playing or saving entire playlists, use {2}undump{1} to \\\n    undo)\n\n    {2}set player mpv{1} or {2}set player mplayer{1} - change player application\n\n    Use {2}1{1} and {2}0{1} in place of true and false when using the {2}set{1} \\\n    command\n\n    Use {2}clearcache{1} command to clear the cache.\n    \"\"\".format(\n                c.ul, c.w, c.y\n            ),\n        ),\n        (\n            \"new\",\n            \"Check if new version is available\",\n            \"\"\"{0}What's New{1}\\n{3}\"\"\".format(c.ul, c.w, c.y, \"get_changelog()\"),\n        ),\n        (\n            \"changelog\",\n            \"Check program changelog\",\n            \"\"\"{0}Changelog{1}\\n{3}\"\"\".format(c.ul, c.w, c.y, \"get_changelog_local()\"),\n        ),\n        (\n            \"tor\",\n            \"Check Tor Status. NOTE: Use this feature at your own risk. In case of any kind of damage we will not be responsible.\",\n            \"\"\"{0}Tor Status{1}\\n{3}\"\"\".format(c.ul, c.w, c.y, \"check_tor()\"),\n        ),\n    ]\n\n\ndef get_help(choice):\n    \"\"\" Return help message. \"\"\"\n    helps = {\"download\": (\"playback dl listen watch show repeat playing\"\n                          \"show_video playurl browserplay dlurl d da dv all *\"\n                          \" play browsersearch\".split()),\n\n             \"dl-command\": (\"dlcmd dl-cmd download-cmd dl_cmd download_cmd \"\n                            \"download-command download_command\".split()),\n\n             \"encode\": (\"encoding transcoding transcode wma mp3 format \"\n                        \"encode encoder\".split()),\n\n             \"invoke\": \"command commands yt invocation\".split(),\n\n             \"search\": (\"user userpl pl pls r n p url album \"\n                        \"editing result results related remove swop mkp --description\".split()),\n\n             \"edit\": (\"editing manupulate manipulating rm mv sw edit move \"\n                      \"swap shuffle\".split()),\n\n             \"tips\": (\"undump dump -f -w -a adv advanced\".split(\" \")),\n\n             \"basic\": (\"basic comment basics c copy clipboard comments u \"\n                       \"i\".split()),\n\n             \"config\": (\"set checkupdate colours colors ddir directory player \"\n                        \"arguments args playerargs music search_music keys \"\n                        \"status show_status show_video video configuration \"\n                        \"fullscreen full screen folder player mpv mplayer\"\n                        \" settings default reset configure audio results \"\n                        \"max_results size lines rows height window \"\n                        \"position window_pos quality resolution max_res \"\n                        \"columns width console overwrite\".split()),\n\n             \"playlists\": (\"save rename delete move rm ls mv sw add vp open\"\n                           \" view\".split())}\n\n    for topic, aliases in helps.items():\n\n        if choice in aliases:\n            choice = topic\n            break\n\n    choice = \"menu\" if not choice else choice\n    out, all_help = \"\", helptext()\n    help_names = [x[0] for x in all_help]\n    choice = get_near_name(choice, help_names)\n\n    def indent(x):\n        \"\"\" Indent. \"\"\"\n        return \"\\n  \".join(x.split(\"\\n\"))\n\n    if choice == \"menu\" or choice not in help_names:\n        out += \"  %sHelp Topics%s\" % (c.ul, c.w)\n        out += F('help topic', 2, 1)\n\n        for x in all_help:\n            out += (\"\\n%s     %-10s%s : %s\" % (c.y, x[0], c.w, x[1]))\n\n        out += \"\\n\"\n        return out\n\n    else:\n        if choice == 'tor':\n            output_text = check_tor()\n        elif choice == 'new':\n            output_text = get_changelog()\n        elif choice == \"changelog\":\n            output_text = get_changelog_local()\n        else:\n            choice = help_names.index(choice)\n            output_text = all_help[choice][2]\n\n        return indent(output_text)\n\ndef get_changelog():\n    try:\n        url = \"https://raw.githubusercontent.com/iamtalhaasghar/yewtube/master/CHANGELOG.md\"\n        v = urlopen(url, timeout=1).read().decode()\n        v = v.split('## v')[1]\n        return v\n    except (URLError, HTTPError, socket.timeout):\n        return \"read changelog timed out\"\n\n\ndef get_changelog_local():\n    cl_path = pathlib.Path(__file__).parent.parent / \"CHANGELOG.md\"\n    if cl_path.is_file():\n        return \"\\n\".join(reversed(cl_path.read_text().splitlines()))\n    else:\n        return \"can't find changelog file\"\n\n\ndef check_tor():\n    try:\n        url = \"https://check.torproject.org/?lang=en\"\n        v = urlopen(url, timeout=1).read().decode()\n        ip = re.findall('<strong>(.*)</strong>', v)\n        status = re.findall('Congratulations.(.*)', v)\n        if len(status) == 0:\n            status = re.findall('Sorry.(.*)', v)\n        return str({'ip' : ip, 'status': status[0]})\n    except (URLError, HTTPError, socket.timeout):\n        return \"read check tor status timed out\"\n"
  },
  {
    "path": "mps_youtube/history.py",
    "content": "import os\nimport pickle\n\nfrom . import g, c\nfrom .util import dbg\nfrom .playlist import Playlist\nfrom .playlists import read_m3u\n\n\ndef add(song):\n    \"\"\" Add song to history. \"\"\"\n    if not g.userhist.get('history'):\n        g.userhist['history'] = Playlist('history')\n\n    g.userhist['history'].songs.append(song)\n\n    save()\n\n\ndef load():\n    \"\"\" Open history. Called once on script invocation. \"\"\"\n    _convert_to_m3u()\n    try:\n        g.userhist['history'] = read_m3u(g.HISTFILE)\n\n    except FileNotFoundError:\n        # no playlist found, create a blank one\n        if not os.path.isfile(g.HISTFILE):\n            g.userhist = {}\n            save()\n\n\ndef save():\n    \"\"\" Save history.  Called each time history is updated. \"\"\"\n    with open(g.HISTFILE, 'w') as hf:\n        hf.write('#EXTM3U\\n\\n')\n        if 'history' in g.userhist:\n            for song in g.userhist['history'].songs:\n                hf.write('#EXTINF:%d,%s\\n' % (song.length, song.title))\n                hf.write('https://www.youtube.com/watch?v=%s\\n' % song.ytid)\n\n    dbg(c.r + \"History saved\\n---\" + c.w)\n\ndef _convert_to_m3u():\n    \"\"\" Converts the play_history file to the m3u format. \"\"\"\n    # Skip if m3u file already exists\n    if os.path.isfile(g.HISTFILE):\n        return\n\n    elif not os.path.isfile(g.OLDHISTFILE):\n        return\n\n    with open(g.OLDHISTFILE, \"rb\") as hf:\n        g.userhist = pickle.load(hf)\n\n    save()\n"
  },
  {
    "path": "mps_youtube/init.py",
    "content": "import argparse\nimport logging\nimport multiprocessing\nimport os\nimport platform\nimport re\nimport sys\nimport tempfile\n\ntry:\n    # pylint: disable=F0401\n    import colorama\n    has_colorama = True\n\nexcept ImportError:\n    has_colorama = False\n\ntry:\n    import readline\n    readline.set_history_length(2000)\n    has_readline = True\n\nexcept ImportError:\n    has_readline = False\n\nfrom . import __version__, c, cache, config, g, paths, screen\nfrom .helptext import helptext\nfrom .util import assign_player, dbg, has_exefile, load_player_info, xprint\n\nmswin = os.name == \"nt\"\n\n\ndef init():\n    \"\"\" Initial setup. \"\"\"\n\n    _process_cl_args()\n\n    # set player to mpv or mplayer if found, otherwise unset\n    suffix = \".exe\" if mswin else \"\"\n    vlc, mplayer, mpv = \"vlc\" + suffix, \"mplayer\" + suffix, \"mpv\" + suffix\n\n    # check for old pickled binary config and convert to json if so\n    config.convert_old_cf_to_json()\n\n    if not os.path.exists(g.CFFILE):\n\n        if has_exefile(vlc):\n            config.PLAYER.set(vlc)\n\n        elif has_exefile(mpv):\n            config.PLAYER.set(mpv)\n\n        elif has_exefile(mplayer):\n            config.PLAYER.set(mplayer)\n\n        config.save()\n\n    else:\n        config.load()\n        try:\n            assign_player(config.PLAYER.get)  # Player is not assigned when config is loaded\n        except Exception as ex:\n            g.message = \"%sFailed to get %s`s version. Probabily it is not installed. Try installing it again or change player using `set player <player_name>` %s\" %(c.y, config.PLAYER.get , c.w)\n            screen.update()\n            input(\"Press Enter to go back to main menu.\")\n\n    # Make pafy use the same api key\n    # pafy.set_api_key(config.API_KEY.get)\n\n    _init_readline()\n    cache.load()\n    _init_transcode()\n\n    # ensure encoder is not set beyond range of available presets\n    if config.ENCODER.get >= len(g.encoders):\n        config.ENCODER.set(\"0\")\n\n    # check mpv/mplayer version\n    if has_exefile(config.PLAYER.get):\n        load_player_info(config.PLAYER.get)\n\n    # setup colorama\n    if has_colorama and mswin:\n        # Colorama converts ansi escape codes to Windows system calls\n        colorama.init()\n\n    # find muxer app\n    if mswin:\n        g.muxapp = has_exefile(\"ffmpeg.exe\") or has_exefile(\"avconv.exe\")\n\n    else:\n        g.muxapp = has_exefile(\"ffmpeg\") or has_exefile(\"avconv\")\n\n    # initialize MPRIS2 interface\n    if config.MPRIS.get:\n        try:\n            from . import mpris\n            conn1, conn2 = multiprocessing.Pipe()\n            g.mprisctl = mpris.MprisConnection(conn1)\n            t = multiprocessing.Process(target=mpris.main, args=(conn2,))\n            t.daemon = True\n            t.start()\n        except ImportError:\n            print(\"could not load MPRIS interface. missing libraries.\")\n\n\ndef _init_transcode():\n    \"\"\" Create transcoding presets if not present.\n\n    Read transcoding presets.\n    \"\"\"\n    if not os.path.exists(g.TCFILE):\n        config_file_contents = \"\"\"\\\n# transcoding presets for mps-youtube\n# VERSION 0\n\n# change ENCODER_PATH to the path of ffmpeg / avconv or leave it as auto\n# to let mps-youtube attempt to find ffmpeg or avconv\nENCODER_PATH: auto\n\n# Delete original file after encoding it\n# Set to False to keep the original downloaded file\nDELETE_ORIGINAL: True\n\n# ENCODING PRESETS\n\n# Encode ogg or m4a to mp3 256k\nname: MP3 256k\nextension: mp3\nvalid for: ogg,m4a,webm\ncommand: ENCODER_PATH -i IN -codec:a libmp3lame -b:a 256k OUT.EXT\n\n# Encode ogg or m4a to mp3 192k\nname: MP3 192k\nextension: mp3\nvalid for: ogg,m4a,webm\ncommand: ENCODER_PATH -i IN -codec:a libmp3lame -b:a 192k OUT.EXT\n\n# Encode ogg or m4a to mp3 highest quality vbr\nname: MP3 VBR best\nextension: mp3\nvalid for: ogg,m4a,webm\ncommand: ENCODER_PATH -i IN -codec:a libmp3lame -q:a 0 OUT.EXT\n\n# Encode ogg or m4a to mp3 high quality vbr\nname: MP3 VBR good\nextension: mp3\nvalid for: ogg,m4a,webm\ncommand: ENCODER_PATH -i IN -codec:a libmp3lame -q:a 2 OUT.EXT\n\n# Encode m4a to ogg\nname: OGG 256k\nextension: ogg\nvalid for: m4a\ncommand: ENCODER_PATH -i IN -codec:a libvorbis -b:a 256k OUT.EXT\n\n# Encode ogg to m4a\nname: M4A 256k\nextension: m4a\nvalid for: ogg\ncommand: ENCODER_PATH -i IN -strict experimental -codec:a aac -b:a 256k OUT.EXT\n\n# Encode ogg or m4a to wma v2\nname: Windows Media Audio v2\nextension: wma\nvalid for: ogg,m4a\ncommand: ENCODER_PATH -i IN -codec:a wmav2 -q:a 0 OUT.EXT\"\"\"\n\n        with open(g.TCFILE, \"w\") as tcf:\n            tcf.write(config_file_contents)\n            dbg(\"generated transcoding config file\")\n\n    else:\n        dbg(\"transcoding config file exists\")\n\n    with open(g.TCFILE, \"r\") as tcf:\n        g.encoders = [dict(name=\"None\", ext=\"COPY\", valid=\"*\")]\n        e = {}\n\n        for line in tcf.readlines():\n\n            if line.startswith(\"TRANSCODER_PATH:\"):\n                m = re.match(\"TRANSCODER_PATH:(.*)\", line).group(1)\n                g.transcoder_path = m.strip()\n\n            elif line.startswith(\"DELETE_ORIGINAL:\"):\n                m = re.match(\"DELETE_ORIGINAL:(.*)\", line).group(1)\n                do = m.strip().lower() in (\"true\", \"yes\", \"enabled\", \"on\")\n                g.delete_orig = do\n\n            elif line.startswith(\"name:\"):\n                e['name'] = re.match(\"name:(.*)\", line).group(1).strip()\n\n            elif line.startswith(\"extension:\"):\n                e['ext'] = re.match(\"extension:(.*)\", line).group(1).strip()\n\n            elif line.startswith(\"valid for:\"):\n                e['valid'] = re.match(\"valid for:(.*)\", line).group(1).strip()\n\n            elif line.startswith(\"command:\"):\n                e['command'] = re.match(\"command:(.*)\", line).group(1).strip()\n\n                if \"name\" in e and \"ext\" in e and \"valid\" in e:\n                    g.encoders.append(e)\n                    e = {}\n\n\ndef _init_readline():\n    \"\"\" Enable readline for input history. \"\"\"\n    if g.command_line:\n        return\n\n    if has_readline:\n        g.READLINE_FILE = os.path.join(paths.get_config_dir(), \"input_history\")\n\n        if os.path.exists(g.READLINE_FILE):\n            readline.read_history_file(g.READLINE_FILE)\n            dbg(c.g + \"Read history file\" + c.w)\n\n\ndef _process_cl_args():\n    \"\"\" Process command line arguments. \"\"\"\n\n    parser = argparse.ArgumentParser(add_help=False)\n    parser.add_argument('commands', nargs='*')\n    parser.add_argument('--help', '-h', action='store_true')\n    parser.add_argument('--version', '-v', action='store_true')\n    parser.add_argument('--debug', '-d', action='store_true')\n    parser.add_argument('--logging', '-l', action='store_true')\n    parser.add_argument('--no-autosize', action='store_true')\n    parser.add_argument('--no-preload', action='store_true')\n    parser.add_argument('--no-textart', action='store_true')\n    args = parser.parse_args()\n\n    if args.version:\n        screen.msgexit(_get_version_info())\n\n    elif args.help:\n        screen.msgexit('\\n'.join(i[2] for i in helptext()))\n\n    if args.debug or os.environ.get(\"mpsytdebug\") == \"1\":\n        xprint(_get_version_info())\n        g.debug_mode = True\n        g.no_clear_screen = True\n\n    if args.logging or os.environ.get(\"mpsytlog\") == \"1\" or g.debug_mode:\n        logfile = os.path.join(tempfile.gettempdir(), \"mpsyt.log\")\n        logging.basicConfig(level=logging.DEBUG, filename=logfile)\n        logging.getLogger(\"pafy\").setLevel(logging.DEBUG)\n\n    if args.no_autosize:\n        g.detectable_size = False\n\n    g.command_line = \"playurl\" in args.commands or \"dlurl\" in args.commands\n    if g.command_line:\n        g.no_clear_screen = True\n\n    if args.no_preload:\n        g.preload_disabled = True\n\n    if args.no_textart:\n        g.no_textart = True\n\n    g.argument_commands = args.commands\n\n\ndef _get_version_info():\n    \"\"\" Return version and platform info. \"\"\"\n    # pafy_version = pafy.__version__\n    # youtube_dl_version = None\n    # if tuple(map(int, pafy_version.split('.'))) >= (0, 5, 0):\n    #     pafy_version += \" (\" + pafy.backend + \" backend)\"\n    #     if pafy.backend == \"youtube-dl\":\n\n    from yt_dlp.version import __version__ as ytdlp_version\n\n    dbus_version = None\n    glib = False\n    try:\n        import dbus\n\n        dbus_version = dbus.__version__\n    except Exception:\n        pass\n    try:\n        from gi.repository import GLib\n\n        glib = True\n    except Exception:\n        pass\n\n    out = \"yewtube version    : \" + __version__\n    out += \"\\nyt_dlp version     : \" + ytdlp_version\n    out += \"\\nPython version     : \" + sys.version\n    out += \"\\nProcessor          : \" + platform.processor()\n    out += \"\\nMachine type       : \" + platform.machine()\n    out += \"\\nArchitecture       : %s, %s\" % platform.architecture()\n    out += \"\\nPlatform           : \" + platform.platform()\n    out += \"\\nsys.stdout.enc     : \" + sys.stdout.encoding\n    out += \"\\ndefault enc        : \" + sys.getdefaultencoding()\n    out += \"\\nConfig dir         : \" + paths.get_config_dir()\n    out += \"\\ndbus               : \" + str(dbus_version)\n    out += \"\\nglib               : \" + str(glib)\n\n    for env in \"TERM SHELL LANG LANGUAGE\".split():\n        value = os.environ.get(env)\n        out += \"\\nenv:%-15s: %s\" % (env, value) if value else \"\"\n\n    return out\n"
  },
  {
    "path": "mps_youtube/listview/__init__.py",
    "content": "\"\"\"\n    DOCSTING COMES HERE\n\"\"\"\nimport re\nimport math\n\nfrom .. import c, g, util, content\nfrom .base import ListViewItem\nfrom .user import ListUser\nfrom .livestream import ListLiveStream\nfrom .songtitle import ListSongtitle\n\n\nclass ListView(content.PaginatedContent):\n    \"\"\" Content Agnostic Numbered List\n\n        This class, using ListViewItems as abstractions you can\n        give it a list of data and which columns to show and it will\n        show it.\n\n        Todo:\n            Currently we rely on the commands/play code to send information\n            about which elements are being picked.\n\n        Attributes:\n            func        The function that will be run on the selected items\n            objects     List of objects(or a ContentQuery object)\n            columns     A list of Hashes containing information about which\n                        columns to show\n            page        Current Page\n\n        Column format:\n            {\"name\": \"idx\", \"size\": 3, \"heading\": \"Num\"}\n            name:    The method name that will be called from the ListViewItem\n            size:    How much size is allocated to the columns,\n                     see ListView.content for more information about\n                     the dynamic options\n            heading: The text shown in the header\n\n            \"idx\" is generated in the content function, not by the ListViewItem\n    \"\"\"\n    func = None\n    objects = None\n    columns = None\n    page = 0\n\n    def __init__(self, columns, objects, function_call=None):\n        \"\"\" \"\"\"\n        self.func = function_call\n        self.objects = objects\n        self.columns = columns\n        self.object_type = None\n\n        # Ensure single type of object\n        types = len(set([obj.__class__ for obj in objects]))\n        if types == 0:\n            raise BaseException(\"No objects in list\")\n        if types > 1:\n            raise BaseException(\"More than one kind of objects in list\")\n\n        self.object_type = [obj.__class__ for obj in objects][0]\n\n    def numPages(self):\n        \"\"\" Returns # of pages \"\"\"\n        return max(1, math.ceil(len(self.objects) / self.views_per_page()))\n\n    def getPage(self, page):\n        self.page = page\n        return self.content()\n\n    def _page_slice(self):\n        chgt = self.views_per_page()\n        return slice(self.page * chgt, (self.page+1) * chgt)\n\n    def content(self):\n        \"\"\" Generates content\n\n            ===============\n            Dynamic fields\n            ===============\n\n            Column.size may instead of an integer be a string\n            containing either \"length\" or \"remaining\".\n\n            Length is for time formats like 20:40\n            Remaining will allocate all remaining space to that\n            column.\n\n            TODO: Make it so set columns can set \"remaining\" ?\n        \"\"\"\n        # Sums all ints, deal with strings later\n        remaining = (util.getxy().width) - sum(1 + (x['size'] if x['size'] and x['size'].__class__ == int else 0) for x in self.columns) - (len(self.columns))\n        lengthsize = 0\n        if \"length\" in [x['size'] for x in self.columns]:\n            max_l = max((getattr(x, \"length\")() for x in self.objects))\n            lengthsize = 8 if max_l > 35999 else 7\n            lengthsize = 6 if max_l < 6000 else lengthsize\n\n        for col in self.columns:\n            if col['size'] == \"remaining\":\n                col['size'] = remaining - lengthsize\n            if col['size'] == \"length\":\n                col['size'] = lengthsize\n\n        for num, column in enumerate(self.columns):\n            column['idx'] = num\n            column['sign'] = \"-\" if not column['name'] == \"length\" else \"\"\n\n        fmt = [\"%{}{}s  \".format(x['sign'], x['size']) for x in self.columns]\n        fmtrow = fmt[0:1] + [\"%s  \"] + fmt[2:]\n        fmt, fmtrow = \"\".join(fmt).strip(), \"\".join(fmtrow).strip()\n        titles = tuple([x['heading'][:x['size']] for x in self.columns])\n        out = \"\\n\" + (c.ul + fmt % titles + c.w) + \"\\n\"\n\n        for num, obj in enumerate(self.objects[self._page_slice()]):\n            col = (c.r if num % 2 == 0 else c.p)\n            idx = num + (self.views_per_page() * self.page) + 1\n\n            line = ''\n            for column in self.columns:\n                fieldsize, field = column['size'], column['name']\n                direction = \"<\" if column['sign'] == \"-\" else \">\"\n\n                if field == \"idx\":\n                    field = \"%2d\" % idx\n\n                else:\n                    field = getattr(obj, field)(fieldsize)\n                    field = str(field) if field.__class__ != str else field\n\n                line += util.uea_pad(fieldsize, field, direction)\n\n                if column != self.columns[-1]:\n                    line += \"  \"\n\n            line = col + line + c.w\n            out += line + \"\\n\"\n        \n        return out\n\n    def _play(self, _, choice, __):  # pre, choice, post\n        \"\"\" Handles what happends when a user selects something from the list\n            Currently this functions hooks into commands/play\n        \"\"\"\n\n        uids = []\n        for splitted_choice in choice.split(\",\"):\n            cho = splitted_choice.strip()\n            if cho.isdigit():\n                uids.append(int(cho) - 1)\n            else:\n                cho = cho.split(\"-\")\n                if cho[0].isdigit() and cho[1].isdigit():\n                    uids += list(range(int(cho[0]) - 1, int(cho[1])))\n\n        var = getattr(self.object_type, \"return_field\")()\n        self.func([getattr(self.objects[x], var)() for x in uids])\n\n    def views_per_page(self):\n        \"\"\" Determines how many views can be per page\n        \"\"\"\n        return util.getxy().max_results\n"
  },
  {
    "path": "mps_youtube/listview/base.py",
    "content": "class ListViewItem:\n    \"\"\" Base class for items\n        Used by Listview\n    \"\"\"\n    data = None\n\n    def __init__(self, data):\n        self.data = data\n\n    def __getattr__(self, key):\n        return self.data[key] if key in self.data.keys() else None\n\n    def length(self, _=0):\n        \"\"\" Returns length of ListViewItem\n            A LVI has to return something for length\n            even if the item does not have one.\n        \"\"\"\n        return 0\n"
  },
  {
    "path": "mps_youtube/listview/livestream.py",
    "content": "from .base import ListViewItem\nfrom .. import util\n\n\nclass ListLiveStream(ListViewItem):\n    \"\"\" Class exposing necessary components of a live stream \"\"\"\n    # pylint: disable=unused-argument\n    def ytid(self, lngt=10):\n        \"\"\" Exposes ytid(string) \"\"\"\n        return self.data.get(\"id\").get(\"videoId\")\n\n    def ret(self):\n        \"\"\" Returns content.video compatible tuple \"\"\"\n        return (self.ytid(), self.title(), self.length())\n\n    def title(self, lngt=10):\n        \"\"\" exposes title \"\"\"\n        return util.uea_pad(lngt, self.data.get(\"snippet\").get(\"title\"))\n    def description(self, lngt=10):\n        \"\"\" exposes description \"\"\"\n        return util.uea_pad(lngt, self.data.get(\"snippet\").get(\"description\"))\n       \n    @staticmethod\n    def return_field():\n        \"\"\" ret \"\"\"\n        return \"ret\"\n"
  },
  {
    "path": "mps_youtube/listview/songtitle.py",
    "content": "from .base import ListViewItem\nfrom .. import util as u\n\n\nclass ListSongtitle(ListViewItem):\n    \"\"\" Describes a user\n    \"\"\"\n    # pylint: disable=unused-argument\n    _checked = False\n    _certainty = 1.0\n\n    def __init__(self, data, certainty=1.0):\n        self._checked = True\n        self._certainty = certainty\n        super(ListSongtitle, self).__init__(data)\n\n    def artist(self, l=10):\n        \"\"\" Get artist \"\"\"\n        return u.uea_pad(l, self.data[0])\n\n    def title(self, l=10):\n        \"\"\" Get title \"\"\"\n        return u.uea_pad(l, self.data[1])\n\n    def checked(self, l=10):\n        \"\"\" String from for checked \"\"\"\n        return \"  X  \" if self._checked else \"     \"\n\n    def certainty(self):\n        \"\"\" Float \"\"\"\n        return self._certainty\n\n    def is_checked(self):\n        \"\"\" Returns true if checked \"\"\"\n        return self._checked\n\n    def toggle(self):\n        \"\"\" Toggle checked status \"\"\"\n        self._checked = not self._checked\n\n    def ret(self):\n        \"\"\" Used in the ListView play function \"\"\"\n        return \"%s - %s\" % (self.artist().strip(), self.title().strip())\n\n    @staticmethod\n    def return_field():\n        \"\"\" Determines which function will be called on selected items \"\"\"\n        return \"ret\"\n"
  },
  {
    "path": "mps_youtube/listview/user.py",
    "content": "from .base import ListViewItem\nfrom .. import util as u\n\nclass ListUser(ListViewItem):\n    \"\"\" Describes a user\n    \"\"\"\n    # pylint: disable=unused-argument\n    def id(self, length=0):\n        \"\"\" Returns YTID \"\"\"\n        return self.data.get(\"id\")\n\n    def name(self, length=10):\n        \"\"\" Returns channel name \"\"\"\n        return u.uea_pad(length, self.data.get(\"title\"))\n\n    def description(self, length=10):\n        \"\"\" Channel description\"\"\"\n        return u.uea_pad(length, self.data[\"descriptionSnippet\"][0]['text'] if self.data['descriptionSnippet'] is not None else 'No description found')\n\n    def kind(self, length=10):\n        \"\"\" Returns the youtube datatype\n            Example: youtube#channel, youtube#video\n        \"\"\"\n        return self.data.get(\"type\")\n\n    def ret(self):\n        \"\"\" Used in the ListView play function \"\"\"\n        return (self.name(), self.id(), \"\")\n\n    @staticmethod\n    def return_field():\n        \"\"\" Determines which function will be called on selected items \"\"\"\n        return \"ret\"\n"
  },
  {
    "path": "mps_youtube/main.py",
    "content": "\"\"\"\nmps-youtube.\n\nhttps://github.com/np1/mps-youtube\n\nCopyright (C) 2014, 2015 np1 and contributors\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\n\nimport locale\nimport logging\nimport os\nimport sys\nimport traceback as traceback_py\n\nfrom . import util\n\ncompleter = None\ntry:\n    import readline\n    readline.set_history_length(2000)\n    has_readline = True\n    completer = util.CommandCompleter()\n    readline.parse_and_bind('tab: complete')\n    readline.set_completer(completer.complete_command)\n    readline.set_completer_delims('')\n\nexcept ImportError:\n    has_readline = False\n\nfrom . import g, c, commands, screen, history, init\nfrom . import __version__, playlists, content, listview\nfrom . import config\n\nmswin = os.name == \"nt\"\n\ntry:\n    locale.setlocale(locale.LC_ALL, \"\")  # for date formatting\nexcept Exception as err:\n    logging.debug(f\"locale not set: {err}\")\n\n\ndef matchfunction(func, regex, userinput):\n    \"\"\" Match userinput against regex.\n\n    Call func, return True if matches.\n\n    \"\"\"\n    # Not supported in python 3.3 or lower\n    # match = regex.fullmatch(userinput)\n    # if match:\n    match = regex.match(userinput)\n    if match and match.group(0) == userinput:\n        matches = match.groups()\n        util.dbg(\"input: %s\", userinput)\n        util.dbg(\"function call: %s\", func.__name__)\n        util.dbg(\"regx matches: %s\", matches)\n\n        try:\n            func(*matches)\n\n        except IndexError:\n            if g.debug_mode:\n                g.content = ''.join(traceback_py.format_exception(\n                    *sys.exc_info()))\n            g.message = util.F('invalid range')\n            g.content = g.content or content.generate_songlist_display()\n\n        except (ValueError, IOError) as e:\n            if g.debug_mode:\n                g.content = ''.join(traceback_py.format_exception(\n                    *sys.exc_info()))\n            g.message = util.F('cant get track') % str(e)\n            g.content = g.content or\\\n                content.generate_songlist_display(zeromsg=g.message)\n\n        except Exception as e:#pafy.GdataError as e:\n            import traceback\n            traceback.print_exception(type(e), e, e.__traceback__)\n            if g.debug_mode:\n                g.content = ''.join(traceback.format_exception(\n                    *sys.exc_info()))\n            g.message = util.F('no data') % e\n            g.content = g.content\n\n        return True\n\n\ndef prompt_for_exit():\n    \"\"\" Ask for exit confirmation. \"\"\"\n    g.message = c.r + \"Press ctrl-c again to exit\" + c.w\n    g.content = content.generate_songlist_display()\n    screen.update()\n\n    try:\n        userinput = input(c.r + \" > \" + c.w)\n\n    except (KeyboardInterrupt, EOFError):\n        commands.misc.quits(showlogo=False)\n\n    return userinput\n\n\ndef main():\n    init.init()\n    \"\"\" Main control loop. \"\"\"\n    if config.SET_TITLE.get:\n        util.set_window_title(\"yewtube\")\n\n    if not g.command_line:\n        g.content = content.logo(col=c.g, version=__version__) + \"\\n\\n\"\n        g.message = \"Enter /search-term to search or [h]elp\"\n        screen.update()\n\n    # open playlists from file\n    playlists.load()\n\n    # open history from file\n    history.load()\n\n    # setup scrobbling\n    commands.lastfm.init_network(verbose=False)\n    prev_model = []\n    scrobble_funcs = [commands.album_search.search_album]\n\n    arg_inp = \" \".join(g.argument_commands)\n\n    prompt = \"> \"\n    arg_inp = arg_inp.replace(r\",,\", \"[mpsyt-comma]\")\n    arg_inp = arg_inp.split(\",\")\n\n    while True:\n        next_inp = \"\"\n\n        if len(arg_inp):\n            next_inp = arg_inp.pop(0).strip()\n            next_inp = next_inp.replace(\"[mpsyt-comma]\", \",\")\n\n        try:\n            userinput = next_inp or input(prompt).strip()\n\n        except (KeyboardInterrupt, EOFError):\n            userinput = prompt_for_exit()\n\n        for i in g.commands:\n            if matchfunction(i.function, i.regex, userinput):\n                if prev_model != g.model and not i.function in scrobble_funcs:\n                    g.scrobble = False\n                prev_model = g.model\n                break\n\n        else:\n            g.content = g.content or content.generate_songlist_display()\n\n            if g.command_line:\n                g.content = \"\"\n\n            if userinput and not g.command_line:\n                g.message = c.b + \"Bad syntax. Enter h for help\" + c.w\n\n            elif userinput and g.command_line:\n                sys.exit(\"Bad syntax\")\n\n        screen.update()\n"
  },
  {
    "path": "mps_youtube/mpris.py",
    "content": "\"\"\"\nmps-youtube.\n\nhttps://github.com/np1/mps-youtube\n\nCopyright (C) 2014 nagev\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\n\nimport copy\nimport json\nimport os\nimport re\nimport socket\nimport time\nimport typing as T\nfrom threading import Thread\n\nimport dbus\nimport dbus.service\nfrom dbus.mainloop.glib import DBusGMainLoop\n\nIDENTITY = 'mps-youtube'\n\nBUS_NAME = 'org.mpris.MediaPlayer2.' + IDENTITY + '.instance' + str(os.getpid())\nROOT_INTERFACE = 'org.mpris.MediaPlayer2'\nPLAYER_INTERFACE = 'org.mpris.MediaPlayer2.Player'\nPROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'\nMPRIS_PATH = '/org/mpris/MediaPlayer2'\n\nclass Mpris2Controller:\n\n    \"\"\"\n        Controller for various MPRIS objects.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"\n            Constructs an MPRIS controller. Note, you must call acquire()\n        \"\"\"\n        # Do not import in main process to prevent conflict with pyperclip\n        # (https://github.com/mps-youtube/mps-youtube/issues/461)\n        from gi.repository import GLib\n\n        self.mpris = None\n        self.bus = None\n        self.main_loop = GLib.MainLoop()\n\n    def release(self):\n        \"\"\"\n            Releases all objects from D-Bus and unregisters the bus\n        \"\"\"\n        if self.mpris is not None:\n            self.mpris.remove_from_connection()\n        self.mpris = None\n        if self.bus is not None:\n            self.bus.get_bus().release_name(self.bus.get_name())\n\n    def acquire(self):\n        \"\"\"\n            Connects to D-Bus and registers all components\n        \"\"\"\n        self._acquire_bus()\n        self._add_interfaces()\n\n    def run(self, connection):\n        \"\"\"\n            Runs main loop, processing all calls\n            binds on connection (Pipe) and listens player changes\n        \"\"\"\n        t = Thread(target=self._run_main_loop)\n        t.daemon = True\n        t.start()\n        self.listenstatus(connection)\n\n    def listenstatus(self, conn):\n        \"\"\"\n            Notifies interfaces that player connection changed\n        \"\"\"\n        while True:\n            try:\n                data = conn.recv()\n                if isinstance(data, tuple):\n                    name, val = data\n                    if name == 'socket':\n                        Thread(target=self.mpris.bindmpv, args=(val,)).start()\n                    elif name == 'mplayer-fifo':\n                        self.mpris.bindfifo(val)\n                    elif name == 'mpv-fifo':\n                        self.mpris.bindfifo(val, mpv=True)\n                    else:\n                        self.mpris.setproperty(name, val)\n            except IOError:\n                break\n            except KeyboardInterrupt:\n                pass\n\n    def _acquire_bus(self):\n        \"\"\"\n            Connect to D-Bus and set self.bus to be a valid connection\n        \"\"\"\n        if self.bus is not None:\n            self.bus.get_bus().request_name(BUS_NAME)\n        else:\n            self.bus = dbus.service.BusName(BUS_NAME,\n                bus=dbus.SessionBus(mainloop=DBusGMainLoop()))\n\n    def _add_interfaces(self):\n        \"\"\"\n            Connects all interfaces to D-Bus\n        \"\"\"\n        self.mpris = Mpris2MediaPlayer(self.bus)\n\n    def _run_main_loop(self):\n        \"\"\"\n            Runs glib main loop, ignoring keyboard interrupts\n        \"\"\"\n        while True:\n            try:\n                self.main_loop.run()\n            except KeyboardInterrupt:\n                pass\n\n\nclass Mpris2MediaPlayer(dbus.service.Object):\n\n    \"\"\"\n        main dbus object for MPRIS2\n        implementing interfaces:\n            org.mpris.MediaPlayer2\n            org.mpris.MediaPlayer2.Player\n    \"\"\"\n\n    def __init__(self, bus):\n        \"\"\"\n            initializes mpris object on dbus\n        \"\"\"\n        dbus.service.Object.__init__(self, bus, MPRIS_PATH)\n        self.socket = None\n        self.fifo = None\n        self.mpv = False\n        self.properties = {\n            ROOT_INTERFACE : {\n                'read_only' : {\n                    'CanQuit' : False,\n                    'CanSetFullscreen' : False,\n                    'CanRaise' : False,\n                    'HasTrackList' : False,\n                    'Identity' : IDENTITY,\n                    'DesktopEntry' : 'mps-youtube',\n                    'SupportedUriSchemes' : dbus.Array([], 's', 1),\n                    'SupportedMimeTypes' : dbus.Array([], 's', 1),\n                },\n                'read_write' : {\n                    'Fullscreen' : False,\n                },\n            },\n            PLAYER_INTERFACE : {\n                'read_only' : {\n                    'PlaybackStatus' : 'Stopped',\n                    'Metadata' : { 'mpris:trackid' : dbus.ObjectPath(\n                                '/CurrentPlaylist/UnknownTrack', variant_level=1) },\n                    'Position' : dbus.Int64(0),\n                    'MinimumRate' : 1.0,\n                    'MaximumRate' : 1.0,\n                    'CanGoNext' : True,\n                    'CanGoPrevious' : True,\n                    'CanPlay' : True,\n                    'CanPause' : True,\n                    'CanSeek' : True,\n                    'CanControl' : True,\n                },\n                'read_write' : {\n                    'Rate' : 1.0,\n                    'Volume' : 1.0,\n                },\n            },\n        }\n\n    def bindmpv(self, sockpath):\n        \"\"\"\n            init JSON IPC for new versions of mpv >= 0.7\n        \"\"\"\n        self.mpv = True\n        self.socket = socket.socket(socket.AF_UNIX)\n        # wait on socket initialization\n        tries = 0\n        while tries < 10:\n            time.sleep(.5)\n            try:\n                self.socket.connect(sockpath)\n                break\n            except socket.error:\n                pass\n            tries += 1\n        else:\n            return\n\n        try:\n            observe_full = False\n            self._sendcommand([\"observe_property\", 1, \"time-pos\"])\n\n            for line in self.socket.makefile():\n                resp = json.loads(line)\n\n                # deals with bug in mpv 0.7 - 0.7.3\n                if resp.get('event') == 'property-change' and not observe_full:\n                    self._sendcommand([\"observe_property\", 2, \"volume\"])\n                    self._sendcommand([\"observe_property\", 3, \"pause\"])\n                    self._sendcommand([\"observe_property\", 4, \"seeking\"])\n                    observe_full = True\n\n                if resp.get('event') == 'property-change':\n                    self.setproperty(resp['name'], resp.get('data'))\n\n        except socket.error:\n            self.socket = None\n            self.mpv = False\n\n    def bindfifo(self, fifopath, mpv=False):\n        \"\"\"\n            init command fifo for mplayer and old versions of mpv\n        \"\"\"\n        time.sleep(1) # give it some time so fifo could be properly created\n        try:\n            self.fifo = open(fifopath, 'w')\n            self._sendcommand(['get_property', 'volume'])\n            self.mpv = mpv\n\n        except IOError:\n            self.fifo = None\n\n    def setproperty(self, name: str, val: T.Optional[T.Any]):\n        \"\"\"\n            Properly sets properties on player interface\n\n            don't use this method from dbus interface, all values should\n            be set from player (to keep them correct)\n        \"\"\"\n        if name == 'pause':\n            oldval = self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus']\n            newval = None\n            if val:\n                newval = 'Paused'\n            else:\n                newval = 'Playing'\n\n            if newval != oldval:\n                self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus'] = newval\n                self.PropertiesChanged(PLAYER_INTERFACE, { 'PlaybackStatus': newval }, [])\n\n        elif name == 'stop':\n            oldval = self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus']\n            newval = None\n            if val:\n                newval = 'Stopped'\n            else:\n                newval = 'Playing'\n\n            if newval != oldval:\n                self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus'] = newval\n                self.PropertiesChanged(PLAYER_INTERFACE, { 'PlaybackStatus': newval },\n                    ['Metadata', 'Position'])\n\n        elif name == 'volume' and val is not None:\n            oldval = self.properties[PLAYER_INTERFACE]['read_write']['Volume']\n            newval = float(val) / 100\n\n            if newval != oldval:\n                self.properties[PLAYER_INTERFACE]['read_write']['Volume'] = newval\n                self.PropertiesChanged(PLAYER_INTERFACE, { 'Volume': newval }, [])\n\n        elif name == 'time-pos' and val:\n            oldval = self.properties[PLAYER_INTERFACE]['read_only']['Position']\n            newval = dbus.Int64(val * 10**6) if val else dbus.Int64(0)\n\n            if newval != oldval:\n                self.properties[PLAYER_INTERFACE]['read_only']['Position'] = newval\n            if abs(newval - oldval) >= 4 * 10**6:\n                self.Seeked(newval)\n\n        elif name == 'metadata' and val:\n            trackid, title, length, arturl, artist, album = val\n            # sanitize ytid - it uses '-_' which are not valid in dbus paths\n            trackid_sanitized = re.sub('[^a-zA-Z0-9]', '', trackid)\n            yturl = 'https://www.youtube.com/watch?v=' + trackid\n\n            oldval = self.properties[PLAYER_INTERFACE]['read_only']['Metadata']\n            newval = {\n                'mpris:trackid' : dbus.ObjectPath(\n                    '/CurrentPlaylist/ytid/' + trackid_sanitized, variant_level=1),\n                'mpris:length' : dbus.Int64(length * 10**6, variant_level=1),\n                'mpris:artUrl' : dbus.String(arturl, variant_level=1),\n                'xesam:title' : dbus.String(title, variant_level=1),\n                'xesam:artist' : dbus.Array(artist, 's', 1),\n                'xesam:album' : dbus.String(album, variant_level=1),\n                'xesam:url' : dbus.String(yturl, variant_level=1),\n            }\n\n            if newval != oldval:\n                self.properties[PLAYER_INTERFACE]['read_only']['Metadata'] = newval\n                self.PropertiesChanged(PLAYER_INTERFACE, { 'Metadata': newval }, [])\n\n        elif name == 'seeking':\n            # send signal to keep time-pos synced between player and client\n            if not val:\n                self.Seeked(self.properties[PLAYER_INTERFACE]['read_only']['Position'])\n\n    def _sendcommand(self, command):\n        \"\"\"\n            sends commands to binded player\n        \"\"\"\n        if self.socket:\n            self.socket.send(json.dumps({\"command\": command}).encode() + b'\\n')\n        elif self.fifo:\n            command = command[:]\n            for x, i in enumerate(command):\n                if i is True:\n                    command[x] = 'yes' if self.mpv else 1\n                elif i is False:\n                    command[x] = 'no' if self.mpv else 0\n\n            cmd = \" \".join([str(i) for i in command]) + '\\n'\n            self.fifo.write(cmd)\n            self.fifo.flush()\n\n    #\n    # implementing org.mpris.MediaPlayer2\n    #\n\n    @dbus.service.method(dbus_interface=ROOT_INTERFACE)\n    def Raise(self):\n        \"\"\"\n            Brings the media player's user interface to the front using\n            any appropriate mechanism available.\n        \"\"\"\n        pass\n\n    @dbus.service.method(dbus_interface=ROOT_INTERFACE)\n    def Quit(self):\n        \"\"\"\n            Causes the media player to stop running.\n        \"\"\"\n        pass\n\n    #\n    # implementing org.mpris.MediaPlayer2.Player\n    #\n\n    @dbus.service.method(dbus_interface=PLAYER_INTERFACE)\n    def Next(self):\n        \"\"\"\n            Skips to the next track in the tracklist.\n        \"\"\"\n        self._sendcommand([\"quit\"])\n\n    @dbus.service.method(PLAYER_INTERFACE)\n    def Previous(self):\n        \"\"\"\n            Skips to the previous track in the tracklist.\n        \"\"\"\n        self._sendcommand([\"quit\", 42])\n\n    @dbus.service.method(PLAYER_INTERFACE)\n    def Pause(self):\n        \"\"\"\n            Pauses playback.\n            If playback is already paused, this has no effect.\n        \"\"\"\n        if self.mpv:\n            self._sendcommand([\"set_property\", \"pause\", True])\n        else:\n            if self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus'] != 'Paused':\n                self._sendcommand(['pause'])\n\n    @dbus.service.method(PLAYER_INTERFACE)\n    def PlayPause(self):\n        \"\"\"\n            Pauses playback.\n            If playback is already paused, resumes playback.\n        \"\"\"\n        if self.mpv:\n            self._sendcommand([\"cycle\", \"pause\"])\n        else:\n            self._sendcommand([\"pause\"])\n\n    @dbus.service.method(PLAYER_INTERFACE)\n    def Stop(self):\n        \"\"\"\n            Stops playback.\n        \"\"\"\n        self._sendcommand([\"quit\", 43])\n\n    @dbus.service.method(PLAYER_INTERFACE)\n    def Play(self):\n        \"\"\"\n            Starts or resumes playback.\n        \"\"\"\n        if self.mpv:\n            self._sendcommand([\"set_property\", \"pause\", False])\n        else:\n            if self.properties[PLAYER_INTERFACE]['read_only']['PlaybackStatus'] != 'Playing':\n                self._sendcommand(['pause'])\n\n    @dbus.service.method(PLAYER_INTERFACE, in_signature='x')\n    def Seek(self, offset):\n        \"\"\"\n            Offset - x (offset)\n                The number of microseconds to seek forward.\n\n            Seeks forward in the current track by the specified number\n            of microseconds.\n        \"\"\"\n        self._sendcommand([\"seek\", offset / 10**6])\n\n    @dbus.service.method(PLAYER_INTERFACE, in_signature='ox')\n    def SetPosition(self, track_id, position):\n        \"\"\"\n            TrackId - o (track_id)\n                The currently playing track's identifier.\n                If this does not match the id of the currently-playing track,\n                the call is ignored as \"stale\".\n            Position - x (position)\n                Track position in microseconds.\n\n            Sets the current track position in microseconds.\n        \"\"\"\n        if track_id == self.properties[PLAYER_INTERFACE]['read_only']['Metadata']['mpris:trackid']:\n            self._sendcommand([\"seek\", position / 10**6, 'absolute' if self.mpv else 2])\n\n    @dbus.service.method(PLAYER_INTERFACE, in_signature='s')\n    def OpenUri(self, uri):\n        \"\"\"\n            Uri - s (uri)\n                Uri of the track to load.\n\n            Opens the Uri given as an argument.\n        \"\"\"\n        pass\n\n    @dbus.service.signal(PLAYER_INTERFACE, signature='x')\n    def Seeked(self, position):\n        \"\"\"\n            Position - x (position)\n                The new position, in microseconds.\n\n            Indicates that the track position has changed in a way that\n            is inconsistant with the current playing state.\n        \"\"\"\n        pass\n\n    #\n    # implementing org.freedesktop.DBus.Properties\n    #\n\n    @dbus.service.method(dbus_interface=PROPERTIES_INTERFACE,\n                         in_signature='ss', out_signature='v')\n    def Get(self, interface_name, property_name):\n        \"\"\"\n            getter for org.freedesktop.DBus.Properties on this object\n        \"\"\"\n        return self.GetAll(interface_name)[property_name]\n\n    @dbus.service.method(dbus_interface=PROPERTIES_INTERFACE,\n                         in_signature='s', out_signature='a{sv}')\n    def GetAll(self, interface_name):\n        \"\"\"\n            getter for org.freedesktop.DBus.Properties on this object\n        \"\"\"\n        if interface_name in self.properties:\n            t = copy.copy(self.properties[interface_name]['read_only'])\n            t.update(self.properties[interface_name]['read_write'])\n\n            return t\n        else:\n            raise dbus.exceptions.DBusException(\n                'com.example.UnknownInterface',\n                'This object does not implement the %s interface'\n                % interface_name)\n\n    @dbus.service.method(dbus_interface=PROPERTIES_INTERFACE,\n                         in_signature='ssv')\n    def Set(self, interface_name, property_name, new_value):\n        \"\"\"\n            setter for org.freedesktop.DBus.Properties on this object\n        \"\"\"\n        if interface_name in self.properties:\n            if property_name in self.properties[interface_name]['read_write']:\n                if property_name == 'Volume':\n                    self._sendcommand([\"set_property\", \"volume\", new_value * 100])\n                    if self.fifo: # fix for mplayer (force update)\n                        self._sendcommand(['get_property', 'volume'])\n        else:\n            raise dbus.exceptions.DBusException(\n                'com.example.UnknownInterface',\n                'This object does not implement the %s interface'\n                % interface_name)\n\n    @dbus.service.signal(dbus_interface=PROPERTIES_INTERFACE,\n                         signature='sa{sv}as')\n    def PropertiesChanged(self, interface_name, changed_properties,\n                          invalidated_properties):\n        \"\"\"\n            signal for org.freedesktop.DBus.Properties on this object\n\n            this informs of changed properties\n        \"\"\"\n        pass\n\nclass MprisConnection(object):\n    \"\"\"\n        Object encapsulating pipe for communication with Mpris2Controller.\n        This object wraps send to ensure communicating process never crashes,\n        even when Mpris2Controller existed or crashed.\n    \"\"\"\n    def __init__(self, connection):\n        super(MprisConnection, self).__init__()\n        self.connection = connection\n\n    def send(self, obj):\n        \"\"\"\n            Send an object to the other end of the connection\n        \"\"\"\n        if self.connection:\n            try:\n                self.connection.send(obj)\n            except BrokenPipeError:\n                self.connection = None\n                print('MPRIS process exited or crashed.')\n\n\ndef main(connection):\n    \"\"\"\n        runs mpris interface and listens for changes\n        connection - pipe to communicate with this module\n    \"\"\"\n\n    try:\n        mprisctl = Mpris2Controller()\n    except ImportError: # gi.repository import GLib\n        print(\"could not load MPRIS interface. missing libraries.\")\n        return\n    try:\n        mprisctl.acquire()\n    except dbus.exceptions.DBusException as e:\n        print('mpris interface couldn\\'t be initialized. reason: %s'\n               % e.get_dbus_message())\n        return\n    mprisctl.run(connection)\n    mprisctl.release()\n"
  },
  {
    "path": "mps_youtube/pafy.py",
    "content": "import json\nimport os\nimport random\nimport re\nfrom urllib.parse import parse_qs, urlparse\n\nimport requests\nimport yt_dlp\nfrom youtubesearchpython import *\n\n\nclass MyLogger:\n    def debug(self, msg):\n        # For compatibility with youtube-dl, both debug and info are passed into debug\n        # You can distinguish them by the prefix '[debug] '\n        if msg.startswith('[debug] '):\n            pass\n        else:\n            self.info(msg)\n\n    def info(self, msg):\n        pass\n\n    def warning(self, msg):\n        pass\n\n    def error(self, msg):\n        print(msg)\n\n\ndef get_video_streams(ytid):\n\n    '''\n    given a youtube video id returns different video / audio stream formats' \\\n    '''\n\n    with yt_dlp.YoutubeDL({'logger':MyLogger()}) as ydl:\n        info_dict = ydl.extract_info(ytid, download=False)\n        return [i for i in info_dict['formats'] if i.get('format_note') != 'storyboard']\n\ndef download_video(ytid, folder, audio_only=False):\n\n    '''\n    Given a youtube video id and target folder, this function will download video to that folder\n    '''\n\n    ytdl_format_options = {\n        'outtmpl': os.path.join(folder, '%(title)s-%(id)s.%(ext)s')\n    }\n    if audio_only:\n        ytdl_format_options['format'] = 'bestaudio/best'\n        ytdl_format_options['postprocessors'] =[{\n            'key': 'FFmpegExtractAudio',\n            'preferredcodec': 'mp3',\n            'preferredquality': '192',\n        }]\n\n    with yt_dlp.YoutubeDL(ytdl_format_options) as ydl:\n        ydl.download('https://www.youtube.com/watch?v=%s' % ytid)\n        return True\n\ndef search_videos(query, pages):\n\n    '''\n    Given a keyword / query this function will return youtube video results against those keywords / query\n    '''\n\n    videosSearch = VideosSearch(query, limit=50)\n    wdata = videosSearch.result()['result']\n    for i in range(pages-1):\n        videosSearch.next()\n        wdata.extend(videosSearch.result()['result'])\n    return wdata\n\n\ndef channel_search(query):\n\n    '''\n    Search channel based on keyword / query provided by user\n    '''\n\n    channelsSearch = ChannelsSearch(query, limit=50, region='US')\n    return channelsSearch.result()['result']\n\ndef playlist_search(query):\n\n    '''\n    Returns all playlists having similar names as keyword / query provided\n    '''\n\n    playlistsSearch = PlaylistsSearch(query, limit=50)\n    return playlistsSearch.result()['result']\n\ndef get_playlist(playlist_id):\n\n    '''\n    Get all videos of a playlist identified by playlist_id\n    '''\n\n    playlist = Playlist('https://www.youtube.com/playlist?list=%s' % playlist_id)\n    while playlist.hasMoreVideos:\n        playlist.getNextVideos()\n    return playlist\n\ndef get_video_title_suggestions(query):\n    suggestions = Suggestions(language = 'en', region = 'US')\n    related_searches = suggestions.get(query)['result']\n    return related_searches[random.randint(0,len(related_searches))]\n\ndef channel_id_from_name(query):\n    channel_info = channel_search(query)[0]\n    channel_id = channel_info['id']\n    channel_name = channel_info['title']\n    return (channel_id, channel_name)\n\ndef all_videos_from_channel(channel_id):\n    playlist = Playlist(playlist_from_channel_id(channel_id))\n    return playlist.videos\n\ndef search_videos_from_channel(channel_id, query):\n    search = ChannelSearch(query , channel_id)\n    return search.result()\n\ndef get_comments(video_id):\n    comments = Comments.get(video_id)\n    return comments['result']\n\ndef get_video_info(video_id):\n    videoInfo = Video.getInfo(video_id)\n    response = return_dislikes(video_id)\n    videoInfo['likes'] = response['likes']\n    videoInfo['dislikes'] = response['dislikes']\n    videoInfo['averageRating'] = response['rating']\n    return videoInfo\n\ndef return_dislikes(video_id):\n    return json.loads(requests.get('https://returnyoutubedislikeapi.com/votes?videoId=' + video_id).text)\n\n\ndef extract_video_id(url: str) -> str:\n    \"\"\"Extract the video id from a url, return video id as str.\n\n    Args:\n        url: url contain video id\n\n    Returns:\n        video id\n\n    Raises:\n        ValueError: If no video id found\n\n    Examples:\n\n        >>> extract_video_id('http://example.com')\n        >>> extract_video_id('https://www.youtube.com/watch?v=LDU_Txk06tM')\n        LDU_Txk06tM\n        >>> extract_video_id('https://youtu.be/LDU_Txk06tM')\n        LDU_Txk06tM\n    \"\"\"\n    idregx = re.compile(r'[\\w-]{11}$')\n    url = str(url).strip()\n\n    if idregx.match(url):\n        return url # ID of video\n\n    if '://' not in url:\n        url = '//' + url\n    parsedurl = urlparse(url)\n    if parsedurl.netloc in ('youtube.com', 'www.youtube.com', 'm.youtube.com', 'gaming.youtube.com'):\n        query = parse_qs(parsedurl.query)\n        if 'v' in query and idregx.match(query['v'][0]):\n            return query['v'][0]\n    elif parsedurl.netloc in ('youtu.be', 'www.youtu.be'):\n        vidid = parsedurl.path.split('/')[-1] if parsedurl.path else ''\n        if idregx.match(vidid):\n            return vidid\n\n    err = \"Need 11 character video id or the URL of the video. Got %s\"\n    raise ValueError(err % url)\n\ndef all_playlists_from_channel(channel_id):\n    channel = Channel(channel_id)\n    playlists = channel.result['playlists']\n    while channel.has_more_playlists():\n         channel.next()\n         playlists.extend(channel.result[\"playlists\"])\n    return playlists"
  },
  {
    "path": "mps_youtube/paths.py",
    "content": "import os\n\nmswin = os.name == \"nt\"\n\n\ndef get_default_ddir():\n    \"\"\" Get system default Download directory, append mps dir. \"\"\"\n    user_home = os.path.expanduser(\"~\")\n    join, exists = os.path.join, os.path.exists\n\n    if mswin:\n        return join(user_home, \"Downloads\", \"yewtube\")\n\n    USER_DIRS = join(user_home, \".config\", \"user-dirs.dirs\")\n    DOWNLOAD_HOME = join(user_home, \"Downloads\")\n\n    # define ddir by (1) env var, (2) user-dirs.dirs file,\n    #                (3) existing ~/Downloads dir (4) ~\n\n    if 'XDG_DOWNLOAD_DIR' in os.environ:\n        ddir = os.environ['XDG_DOWNLOAD_DIR']\n\n    elif exists(USER_DIRS):\n        lines = open(USER_DIRS).readlines()\n        defn = [x for x in lines if x.startswith(\"XDG_DOWNLOAD_DIR\")]\n\n        if len(defn) == 1:\n            ddir = defn[0].split(\"=\")[1].replace('\"', '')\n            ddir = ddir.replace(\"$HOME\", user_home).strip()\n\n        else:\n            ddir = DOWNLOAD_HOME if exists(DOWNLOAD_HOME) else user_home\n\n    else:\n        ddir = DOWNLOAD_HOME if exists(DOWNLOAD_HOME) else user_home\n\n    ddir = ddir\n    return os.path.join(ddir, \"mps\")\n\n\ndef get_config_dir():\n    \"\"\" Get user's configuration directory. Migrate to new mps name if old.\"\"\"\n    if mswin:\n        confdir = os.environ[\"APPDATA\"]\n\n    elif 'XDG_CONFIG_HOME' in os.environ:\n        confdir = os.environ['XDG_CONFIG_HOME']\n\n    else:\n        confdir = os.path.join(os.path.expanduser(\"~\"), '.config')\n\n    mps_confdir = os.path.join(confdir, \"mps-youtube\")\n\n    os.makedirs(mps_confdir, exist_ok=True)\n\n    return mps_confdir\n"
  },
  {
    "path": "mps_youtube/player.py",
    "content": "import logging\nimport math\nimport os\nimport random\nimport shlex\nimport socket\nimport subprocess\nimport sys\nimport time\nfrom abc import ABCMeta, abstractmethod\nfrom urllib.error import HTTPError, URLError\n\nfrom . import c, config, content, g, history, screen, streams, util\nfrom .commands import lastfm\nfrom .util import not_utf8_environment\n\nmswin = os.name == \"nt\"\n\nclass BasePlayer:\n    _playbackStatus = \"Paused\"\n    _last_displayed_line = None\n\n    @property\n    def PlaybackStatus(self):\n        return self._playbackStatus\n\n    @PlaybackStatus.setter\n    def PlaybackStatus(self, value):\n        self._playbackStatus = value\n        if value == 'Playing':\n            paused = False\n        else:\n            paused = True\n        g.mprisctl.send(('pause', paused))\n\n    def play(self, songlist, shuffle=False, repeat=False, override=False):\n        \"\"\" Play a range of songs, exit cleanly on keyboard interrupt. \"\"\"\n\n        if config.ALWAYS_REPEAT.get:\n            repeat = True\n\n        self.songlist = songlist\n        self.shuffle = shuffle\n        self.repeat = repeat\n        self.override = override\n        if shuffle:\n            random.shuffle(self.songlist)\n\n        self.song_no = 0\n        while 0 <= self.song_no <= len(self.songlist)-1:\n            self.song = self.songlist[self.song_no]\n            g.content = self._playback_progress(self.song_no, self.songlist,\n                                                repeat=repeat)\n\n            if not g.command_line:\n                screen.update(fill_blank=False)\n\n            hasnext = len(self.songlist) > self.song_no + 1\n\n            if hasnext:\n                streams.preload(self.songlist[self.song_no + 1],\n                                override=self.override)\n\n            if config.SET_TITLE.get:\n                util.set_window_title(self.song.title + \" - yewtube\")\n\n            self.softrepeat = repeat and len(self.songlist) == 1\n\n            if g.scrobble:\n                lastfm.set_now_playing(g.artist, g.scrobble_queue[self.song_no])\n\n            try:\n                self.video, self.stream, self.override = stream_details(\n                                                            self.song,\n                                                            override=self.override,\n                                                            softrepeat=self.softrepeat)\n                self._playsong()\n\n            except KeyboardInterrupt:\n                logging.info(\"Keyboard Interrupt\")\n                util.xprint(c.w + \"Stopping...                          \")\n                screen.reset_terminal()\n                g.message = c.y + \"Playback halted\" + c.w\n                raise KeyboardInterrupt\n                break\n\n            # skip forbidden, video removed/no longer available, etc. tracks\n            except TypeError as e:\n                import traceback\n                traceback.print_exception(type(e), e, e.__traceback__)\n                self.song_no += 1\n                pass\n\n            if config.SET_TITLE.get:\n                util.set_window_title(\"yewtube\")\n\n            if self.song_no == -1:\n                self.song_no = len(songlist) - 1 if repeat else 0\n            elif self.song_no == len(self.songlist) and repeat:\n                self.song_no = 0\n\n    # To be defined by subclass based on being cmd player or library\n    # When overriding next and previous don't forget to add the following\n    # if g.scrobble:\n    #   lastfm.scrobble_track(g.artist, g.album, g.scrobble_queue[self.song_no])\n    def next(self):\n        pass\n\n    def previous(self):\n        pass\n\n    def stop(self):\n        pass\n    ###############\n\n    def seek(self):\n        pass\n\n    def _playsong(self, failcount=0, softrepeat=False):\n        \"\"\" Play song using config.PLAYER called with args config.PLAYERARGS.\n\n        \"\"\"\n        # pylint: disable=R0911,R0912\n        if not config.PLAYER.get or not util.has_exefile(config.PLAYER.get):\n            g.message = \"Player not configured! Enter %sset player <player_app> \"\\\n                \"%s to set a player\" % (c.g, c.w)\n            return\n\n        if config.NOTIFIER.get:\n            subprocess.Popen(shlex.split(config.NOTIFIER.get) + [self.song.title])\n\n        size = streams.get_size(self.song.ytid, self.stream['url'])\n        songdata = (self.song.ytid, '' if self.stream.get('ext') is None else self.stream.get('ext') + \" \" + self.stream['quality'],\n                    int(size / (1024 ** 2)))\n        self.songdata = \"%s; %s; %s Mb\" % songdata\n        screen.writestatus(self.songdata)\n\n        self._launch_player()\n\n        if config.HISTORY.get:\n            history.add(self.song)\n\n    def _launch_player(self):\n        \"\"\" Launch player application. \"\"\"\n        pass\n\n    def send_metadata_mpris(self):\n        metadata = util._get_metadata(self.song.title) if config.LOOKUP_METADATA.get else None\n\n        if metadata is None:\n            arturl = \"https://i.ytimg.com/vi/%s/default.jpg\" % self.song.ytid\n            metadata = (self.song.ytid, self.song.title, self.song.length,\n                        arturl, [''], '')\n        else:\n            arturl = metadata['album_art_url']\n            metadata = (self.song.ytid, metadata['track_title'],\n                        self.song.length, arturl,\n                        [metadata['artist']], metadata['album'])\n\n        if g.mprisctl:\n            g.mprisctl.send(('metadata', metadata))\n\n    def _playback_progress(self, idx, allsongs, repeat=False):\n        \"\"\" Generate string to show selected tracks, indicate current track. \"\"\"\n        # pylint: disable=R0914\n        # too many local variables\n        cw = util.getxy().width\n        out = \"  %s%-XXs%s%s\\n\".replace(\"XX\", str(cw - 9))\n        out = out % (c.ul, \"Title\", \"Time\", c.w)\n        multi = len(allsongs) > 1\n\n        for n, song in enumerate(allsongs):\n            length_orig = util.fmt_time(song.length)\n            length = \" \" * (8 - len(length_orig)) + length_orig\n            i = util.uea_pad(cw - 14, song.title), length, length_orig\n            fmt = (c.w, \"  \", c.b, i[0], c.w, c.y, i[1], c.w)\n\n            if n == idx:\n                fmt = (c.y, \"> \", c.p, i[0], c.w, c.p, i[1], c.w)\n                cur = i\n\n            out += \"%s%s%s%s%s %s%s%s\\n\" % fmt\n\n        out += \"\\n\" * (3 - len(allsongs))\n        pos = 8 * \" \", c.y, idx + 1, c.w, c.y, len(allsongs), c.w\n        playing = \"{}{}{}{} of {}{}{}\\n\\n\".format(*pos) if multi else \"\\n\\n\"\n        keys = self._help(short=(not multi and not repeat))\n        out = out if multi else content.generate_songlist_display(song=allsongs[0])\n\n        if config.SHOW_PLAYER_KEYS.get and keys is not None:\n            out += \"\\n\" + keys\n\n        else:\n            playing = \"{}{}{}{} of {}{}{}\\n\".format(*pos) if multi else \"\\n\"\n            out += \"\\n\" + \" \" * (cw - 19) if multi else \"\"\n\n        fmt = playing, c.r, cur[0].strip()[:cw - 19], c.w, c.w, cur[2], c.w\n        out += \"%s    %s%s%s %s[%s]%s\" % fmt\n        out += \"    REPEAT MODE\" if repeat else \"\"\n        return out\n\n    def make_status_line(self, elapsed_s, prefix, songlength=0, volume=None):\n        self._line = self._make_status_line(elapsed_s, prefix, songlength,\n                                            volume=volume)\n\n        if self._line != self._last_displayed_line:\n            screen.writestatus(self._line)\n            self._last_displayed_line = self._line\n\n    def _make_status_line(self, elapsed_s, prefix, songlength=0, volume=None):\n        \"\"\" Format progress line output.  \"\"\"\n        # pylint: disable=R0914\n\n        display_s = elapsed_s\n        display_h = display_m = 0\n\n        if elapsed_s >= 60:\n            display_m = display_s // 60\n            display_s %= 60\n\n            if display_m >= 60:\n                display_h = display_m // 60\n                display_m %= 60\n\n        pct = (float(elapsed_s) / songlength * 100) if songlength else 0\n\n        status_line = \"%02i:%02i:%02i %s\" % (\n            display_h, display_m, display_s,\n            (\"[%.0f%%]\" % pct).ljust(6)\n        )\n\n        if volume:\n            vol_suffix = \" vol: %d%%\" % volume\n\n        else:\n            vol_suffix = \"\"\n\n        cw = util.getxy().width\n        prog_bar_size = cw - len(prefix) - len(status_line) - len(vol_suffix) - 7\n        progress = int(math.ceil(pct / 100 * prog_bar_size))\n        status_line += \" [%s]\" % (\"=\" * (progress - 1) +\n                                  \">\").ljust(prog_bar_size, ' ')\n        return prefix + status_line + vol_suffix\n\n\nclass CmdPlayer(BasePlayer):\n\n    def next(self):\n        if g.scrobble:\n            lastfm.scrobble_track(g.artist, g.album,\n                                  g.scrobble_queue[self.song_no])\n        self.terminate_process()\n        self.song_no += 1\n\n    def previous(self):\n        if g.scrobble:\n            lastfm.scrobble_track(g.artist, g.album,\n                                  g.scrobble_queue[self.song_no])\n        self.terminate_process()\n        self.song_no -= 1\n\n    def stop(self):\n        self.terminate_process()\n        self.song_no = len(self.songlist)\n\n    def terminate_process(self):\n        self.p.terminate()\n        # If using shell=True or the player\n        # requires some obscure way of killing the process\n        # the child class can define this function\n\n    def _generate_real_playerargs(self):\n        pass\n\n    def clean_up(self):\n        pass\n\n    def launch_player(self, cmd):\n        pass\n\n    def _help(self, short=True):\n        pass\n\n    def _launch_player(self):\n        \"\"\" Launch player application. \"\"\"\n\n        cmd = self._generate_real_playerargs()\n\n        util.dbg(\"playing %s\", self.song.title)\n        util.dbg(\"calling %s\", \" \".join(cmd))\n\n        # Fix UnicodeEncodeError when title has characters\n        # not supported by encoding\n        cmd = [util.xenc(i) for i in cmd]\n\n        self.send_metadata_mpris()\n        try:\n            self.launch_player(cmd)\n\n        except OSError:\n            g.message = util.F('no player') % config.PLAYER.get\n            return None\n\n        finally:\n            if g.mprisctl:\n                g.mprisctl.send(('stop', True))\n\n            if self.p and self.p.poll() is None:\n                self.p.terminate()  # make sure to kill mplayer if yewtube crashes\n\n            self.clean_up()\n\n\ndef stream_details(song, failcount=0, override=False, softrepeat=False):\n    \"\"\"Fetch stream details for a song.\"\"\"\n    # don't interrupt preloading:\n    while song.ytid in g.preloading:\n        screen.writestatus(\"fetching item..\")\n        time.sleep(0.1)\n\n    try:\n        streams.get(song, force=failcount, callback=screen.writestatus)\n\n    except (IOError, URLError, HTTPError, socket.timeout) as e:\n        util.dbg(\"--ioerror in stream_details call to streams.get %s\", str(e))\n\n        if \"Youtube says\" in str(e):\n            g.message = util.F('cant get track') % (song.title + \" \" + str(e))\n            return\n\n        elif failcount < g.max_retries:\n            util.dbg(\"--ioerror - trying next stream\")\n            failcount += 1\n            return stream_details(song, failcount=failcount, override=override, softrepeat=softrepeat)\n\n        elif \"pafy\" in str(e):\n            g.message = str(e) + \" - \" + song.ytid\n            return\n\n    except ValueError:\n        g.message = util.F('track unresolved')\n        util.dbg(\"----valueerror in stream_details call to streams.get\")\n        return\n\n    if failcount == g.max_retries:\n        raise TypeError()\n\n    try:\n        video = ((config.SHOW_VIDEO.get and override != \"audio\") or\n                 (override in (\"fullscreen\", \"window\", \"forcevid\")))\n        m4a = \"mplayer\" not in config.PLAYER.get\n        cached = g.streams[song.ytid]\n        stream = streams.select(cached, q=failcount, audio=(not video), m4a_ok=m4a)\n\n        # handle no audio stream available, or m4a with mplayer\n        # by switching to video stream and suppressing video output.\n        if (not stream or failcount) and not video:\n            util.dbg(c.r + \"no audio or mplayer m4a, using video stream\" + c.w)\n            override = \"a-v\"\n            video = True\n            stream = streams.select(cached, q=failcount, audio=False, maxres=1600)\n\n        if not stream:\n            raise IOError(\"No streams available\")\n\n        return (video, stream, override)\n\n    except (HTTPError) as e:\n\n        # Fix for invalid streams (gh-65)\n        util.dbg(\"----htterror in stream_details call to gen_real_args %s\", str(e))\n        if failcount < g.max_retries:\n            failcount += 1\n            return stream_details(song, failcount=failcount,\n                                  override=override, softrepeat=softrepeat)\n        else:\n            g.message = str(e)\n            return\n\n    except IOError as e:\n        # this may be cause by attempting to play a https stream with\n        # mplayer\n        # ====\n        errmsg = e.message if hasattr(e, \"message\") else str(e)\n        g.message = c.r + str(errmsg) + c.w\n        return\n"
  },
  {
    "path": "mps_youtube/players/GenericPlayer.py",
    "content": "import os\nimport subprocess\n\nfrom .. import config\n\nfrom ..player import CmdPlayer\n\n#\n# This class can be used as a templete for new players\n#\n# NOTE:\n# If you're defining a new player donot forget\n# to name both the class and file the same as your player\n#\n\n\nclass GenericPlayer(CmdPlayer):\n    def __init__(self, player):\n        self.player = player\n\n    def _generate_real_playerargs(self):\n        '''Generates player arguments to called using Popen\n\n        '''\n        args = config.PLAYERARGS.get.strip().split()\n\n        ############################################\n        # Define your arguments below this line\n\n        ###########################################\n\n        return [self.player] + args + [self.stream['url']]\n\n    def clean_up(self):\n        ''' Cleans up temp files after process exits.\n\n        '''\n        pass\n\n    def launch_player(self, cmd):\n\n        ##################################################\n        # Change this however you want\n\n        with open(os.devnull, \"w\") as devnull:\n            self.p = subprocess.Popen(cmd, shell=False, stderr=devnull)\n        self.p.wait()\n\n        ##################################################\n\n        # Donot forget self.next()\n        self.next()\n\n    def _help(self, short=True):\n        ''' Help keys shown when the song is played.\n\n        See mpv.py for reference.\n\n        '''\n        pass\n"
  },
  {
    "path": "mps_youtube/players/__init__.py",
    "content": ""
  },
  {
    "path": "mps_youtube/players/mplayer.py",
    "content": "import os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nimport typing as T\n\nfrom .. import c, config, g, paths, screen, util\nfrom ..player import CmdPlayer\nfrom ..util import not_utf8_environment\n\nmswin = os.name == \"nt\"\n\n\nclass mplayer(CmdPlayer):\n    def __init__(self, player):\n        self.player = player\n        self.mplayer_version = _get_mplayer_version(player)\n\n    def _generate_real_playerargs(self):\n        \"\"\" Generate args for player command.\n\n        Return args.\n\n        \"\"\"\n\n        if \"uiressl=yes\" in self.stream['url']:\n            ver = self.mplayer_version\n            # Mplayer too old to support https\n            if not (ver > (1, 1) if isinstance(ver, tuple) else ver >= 37294):\n                raise IOError(\"%s : Sorry mplayer doesn't support this stream. \"\n                              \"Use mpv or update mplayer to a newer version\" % self.song.title)\n\n        args = config.PLAYERARGS.get.strip().split()\n\n        pd = g.playerargs_defaults['mplayer']\n        args.extend((pd[\"title\"], '\"{0}\"'.format(self.song.title)))\n\n        if pd['geo'] not in args:\n            geometry = config.WINDOW_SIZE.get or \"\"\n\n            if config.WINDOW_POS.get:\n                wp = config.WINDOW_POS.get\n                xx = \"+1\" if \"left\" in wp else \"-1\"\n                yy = \"+1\" if \"top\" in wp else \"-1\"\n                geometry += xx + yy\n\n            if geometry:\n                args.extend((pd['geo'], geometry))\n\n        # handle no audio stream available\n        if self.override == \"a-v\":\n            util.list_update(pd[\"novid\"], args)\n\n        elif ((config.FULLSCREEN.get and self.override != \"window\")\n                or self.override == \"fullscreen\"):\n            util.list_update(pd[\"fs\"], args)\n\n        # prevent ffmpeg issue (https://github.com/mpv-player/mpv/issues/579)\n        if not self.video and self.stream['ext'] == \"m4a\":\n            util.dbg(\"%susing ignidx flag%s\")\n            util.list_update(pd[\"ignidx\"], args)\n\n        if g.volume:\n            util.list_update(\"-volume\", args)\n            util.list_update(str(g.volume), args)\n        util.list_update(\"-really-quiet\", args, remove=True)\n        util.list_update(\"-noquiet\", args)\n        util.list_update(\"-prefer-ipv4\", args)\n        util.list_update(\"-cache\", args)\n        util.list_update(\"4096\", args)\n\n        return [self.player] + args + [self.stream['url']]\n\n    def clean_up(self):\n        if self.fifopath:\n            os.unlink(self.fifopath)\n\n    def launch_player(self, cmd):\n        self.input_file = _get_input_file()\n        self.sockpath = None\n        self.fifopath = None\n\n        cmd.append('-input')\n\n        if mswin:\n            # Mplayer does not recognize path starting with drive letter,\n            # or with backslashes as a delimiter.\n            self.input_file = self.input_file[2:].replace('\\\\', '/')\n\n        cmd.append('conf=' + self.input_file)\n\n        if g.mprisctl:\n            self.fifopath = tempfile.mktemp('.fifo', 'mpsyt-mplayer')\n            os.mkfifo(self.fifopath)\n            cmd.extend(['-input', 'file=' + self.fifopath])\n            g.mprisctl.send(('mplayer-fifo', self.fifopath))\n\n        self.p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE,\n                              stderr=subprocess.STDOUT, bufsize=0)\n        self._player_status(self.songdata + \"; \", self.song.length)\n        returncode = self.p.wait()\n        print(returncode)\n\n        if returncode == 42:\n            self.previous()\n\n        elif returncode == 43:\n            self.stop()\n\n        else:\n            self.next()\n\n    def _player_status(self, prefix, songlength=0):\n        \"\"\" Capture time progress from player output. Write status line. \"\"\"\n        # pylint: disable=R0914, R0912\n        re_player = re.compile(r\"A:\\s*(?P<elapsed_s>\\d+)\\.\\d\\s*\")\n        re_volume = re.compile(r\"Volume:\\s*(?P<volume>\\d+)\\s*%\")\n        last_displayed_line = None\n        buff = ''\n        volume_level = None\n        last_pos = None\n\n        elapsed_s = 0\n        while self.p.poll() is None:\n            stdstream = self.p.stdout\n            char = stdstream.read(1).decode(\"utf-8\", errors=\"ignore\")\n\n            if char in '\\r\\n':\n\n                mv = re_volume.search(buff)\n\n                if mv:\n                    volume_level = int(mv.group(\"volume\"))\n\n                match_object = re_player.match(buff)\n\n                if match_object:\n\n                    try:\n                        h, m, s = map(int, match_object.groups())\n                        elapsed_s = h * 3600 + m * 60 + s\n\n                    except ValueError:\n\n                        try:\n                            elapsed_s = int(match_object.group('elapsed_s') or\n                                            '0')\n\n                        except ValueError:\n                            continue\n\n                    if volume_level and volume_level != g.volume:\n                        g.volume = volume_level\n                    self.make_status_line(elapsed_s, prefix, songlength,\n                                          volume=volume_level)\n\n                if buff.startswith('ANS_volume='):\n                    volume_level = round(float(buff.split('=')[1]))\n\n                paused = (\"PAUSE\" in buff) or (\"Paused\" in buff)\n                if (elapsed_s != last_pos or paused) and g.mprisctl:\n                    last_pos = elapsed_s\n                    g.mprisctl.send(('pause', paused))\n                    g.mprisctl.send(('volume', volume_level))\n                    g.mprisctl.send(('time-pos', elapsed_s))\n\n                buff = ''\n\n            else:\n                buff += char\n\n    def _help(self, short=True):\n        \"\"\" Mplayer help.  \"\"\"\n\n        volume = \"[{0}9{1}] volume [{0}0{1}]      [{0}CTRL-C{1}] return\"\n        seek = \"[{0}\\u2190{1}] seek [{0}\\u2192{1}]\"\n        pause = \"[{0}\\u2193{1}] SEEK [{0}\\u2191{1}]       [{0}space{1}] pause\"\n\n        if not_utf8_environment:\n            seek = \"[{0}<-{1}] seek [{0}->{1}]\"\n            pause = \"[{0}DN{1}] SEEK [{0}UP{1}]       [{0}space{1}] pause\"\n\n        single = \"[{0}q{1}] next\"\n        next_prev = \"[{0}>{1}] next/prev [{0}<{1}]\"\n        # ret = \"[{0}q{1}] %s\" % (\"return\" if short else \"next track\")\n        ret = single if short and config.AUTOPLAY.get else \"\"\n        ret = next_prev if not short else ret\n        fmt = \"    %-20s       %-20s\"\n        lines = fmt % (seek, volume) + \"\\n\" + fmt % (pause, ret)\n        return lines.format(c.g, c.w)\n\n\ndef _get_input_file():\n    \"\"\" Check for existence of custom input file.\n\n    Return file name of temp input file with yewtube mappings included\n    \"\"\"\n    confpath = conf = ''\n\n    confpath = os.path.join(paths.get_config_dir(), \"mplayer-input.conf\")\n\n    if os.path.isfile(confpath):\n        util.dbg(\"using %s for input key file\", confpath)\n\n        with open(confpath) as conffile:\n            conf = conffile.read() + '\\n'\n\n    conf = conf.replace(\"quit\", \"quit 43\")\n    conf = conf.replace(\"playlist_prev\", \"quit 42\")\n    conf = conf.replace(\"pt_step -1\", \"quit 42\")\n    conf = conf.replace(\"playlist_next\", \"quit\")\n    conf = conf.replace(\"pt_step 1\", \"quit\")\n    standard_cmds = ['q quit 43\\n', '> quit\\n', '< quit 42\\n', 'NEXT quit\\n',\n                     'PREV quit 42\\n', 'ENTER quit\\n']\n    bound_keys = [i.split()[0] for i in conf.splitlines() if i.split()]\n\n    for i in standard_cmds:\n        key = i.split()[0]\n\n        if key not in bound_keys:\n            conf += i\n\n    with tempfile.NamedTemporaryFile('w', prefix='mpsyt-input',\n                                     delete=False) as tmpfile:\n        tmpfile.write(conf)\n        return tmpfile.name\n\n\ndef _get_mplayer_version(exename: str) -> T.Union[int, T.Tuple[int, ...]]:\n    \"\"\"get mplayer version.\n\n    Args:\n        exename: mplayer executable name.\n\n    Returns:\n       single integer value or tuple of mplayer version. Return `0` if failed\n\n    Raises:\n        OSError: if `exename` is invalid\n        FileNotFoundError: if no mplayer found\n        PermissionError: if user dont have permission to run `exename`\n        TypeError: if `exename` return invalid type\n    \"\"\"\n    try:\n        o = subprocess.check_output([exename]).decode()\n    except FileNotFoundError:\n        raise\n\n    m = re.search(r\"MPlayer \\S*?SVN[\\s-]r([0-9]+)\", o, re.MULTILINE | re.IGNORECASE)\n\n    ver = 0\n    if m:\n        ver = int(m.groups()[0])\n    else:\n        m = re.search('MPlayer ([0-9])+.([0-9]+)', o, re.MULTILINE)\n        if m:\n            ver = tuple(int(i) for i in m.groups())\n\n        else:\n            util.dbg(\"%sFailed to detect mplayer version%s\", c.r, c.w)\n\n    return ver\n"
  },
  {
    "path": "mps_youtube/players/mpv.py",
    "content": "import json\nimport os\nimport re\nimport socket\nimport subprocess\nimport sys\nimport tempfile\nimport time\n\nfrom .. import c, config, g, paths, screen, util\nfrom ..player import CmdPlayer\nfrom ..util import not_utf8_environment\n\nmswin = os.name == \"nt\"\n\n\nclass mpv(CmdPlayer):\n    def __init__(self, player):\n        self.player = player\n        self.mpv_version = _get_mpv_version(player)\n        self.mpv_options = subprocess.check_output(\n                [player, \"--list-options\"]).decode()\n\n        self.mpv_usesock = \"\"\n        if not mswin:\n            if \"--input-unix-socket\" in self.mpv_options:\n                self.mpv_usesock = \"--input-unix-socket\"\n                util.dbg(c.g + \"mpv supports --input-unix-socket\" + c.w)\n            elif \"--input-ipc-server\" in self.mpv_options:\n                self.mpv_usesock = \"--input-ipc-server\"\n                util.dbg(c.g + \"mpv supports --input-ipc-server\" + c.w)\n\n    def _generate_real_playerargs(self):\n        \"\"\" Generate args for player command.\n\n        Return args.\n\n        \"\"\"\n\n        args = config.PLAYERARGS.get.strip().split()\n\n        pd = g.playerargs_defaults['mpv']\n        # Use new mpv syntax\n        # https://github.com/mps-youtube/mps-youtube/issues/1052\n        completetitle = '='.join((pd[\"title\"], '\"{0}\"'.format(self.song.title)))\n        util.list_update(completetitle, args)\n\n        if pd['geo'] not in args:\n            geometry = config.WINDOW_SIZE.get or \"\"\n\n            if config.WINDOW_POS.get:\n                wp = config.WINDOW_POS.get\n                xx = \"+1\" if \"left\" in wp else \"-1\"\n                yy = \"+1\" if \"top\" in wp else \"-1\"\n                geometry += xx + yy\n\n            if geometry:\n                # Use new mpv syntax\n                # See: https://github.com/mps-youtube/mps-youtube/issues/1052\n                newgeometry = '='.join((pd['geo'], geometry))\n                util.list_update(newgeometry, args)\n\n        # handle no audio stream available\n        if self.override == \"a-v\":\n            util.list_update(pd[\"novid\"], args)\n\n        elif ((config.FULLSCREEN.get and self.override != \"window\")\n                or self.override == \"fullscreen\"):\n            util.list_update(pd[\"fs\"], args)\n\n        # prevent ffmpeg issue (https://github.com/mpv-player/mpv/issues/579)\n        if not self.video and self.stream['ext'] == \"m4a\":\n            util.dbg(\"%susing ignidx flag%s\")\n            util.list_update(pd[\"ignidx\"], args)\n\n        if \"--ytdl\" in self.mpv_options:\n            util.list_update(\"--no-ytdl\", args)\n\n        msglevel = pd[\"msglevel\"][\"<0.4\"]\n\n        #  undetected (negative) version number assumed up-to-date\n        if self.mpv_version[0:2] < (0, 0) or self.mpv_version[0:2] >= (0, 4):\n            msglevel = pd[\"msglevel\"][\">=0.4\"]\n\n        if not g.debug_mode:\n            if self.mpv_usesock:\n                util.list_update(\"--really-quiet\", args)\n            else:\n                util.list_update(\"--really-quiet\", args, remove=True)\n                util.list_update(msglevel, args)\n\n        if g.volume:\n            util.list_update(\"--volume=\" + str(g.volume), args)\n        if self.softrepeat:\n            util.list_update(\"--loop-file\", args)\n\n        if not config.SHOW_VIDEO.get:\n            util.list_update('--no-video', args)\n            util.list_update('--vid=no', args)\n\n        return [self.player] + args + [self.stream['url']]\n\n    def clean_up(self):\n        if self.input_file:\n            os.unlink(self.input_file)\n\n        if self.sockpath and os.path.exists(self.sockpath):\n            os.unlink(self.sockpath)\n\n        if self.fifopath and os.path.exists(self.fifopath):\n            os.unlink(self.fifopath)\n\n    def launch_player(self, cmd):\n        self.input_file = _get_input_file()\n        cmd.append('--input-conf=' + self.input_file)\n        self.sockpath = None\n        self.fifopath = None\n\n        if self.mpv_usesock:\n            self.sockpath = tempfile.mktemp('.sock', 'mpsyt-mpv')\n            cmd.append(self.mpv_usesock + '=' + self.sockpath)\n\n            with open(os.devnull, \"w\") as devnull:\n                self.p = subprocess.Popen(cmd, shell=False, stderr=devnull)\n\n            if g.mprisctl:\n                g.mprisctl.send(('socket', self.sockpath))\n        else:\n            if g.mprisctl:\n                self.fifopath = tempfile.mktemp('.fifo', 'mpsyt-mpv')\n                os.mkfifo(self.fifopath)\n                cmd.append('--input-file=' + self.fifopath)\n                g.mprisctl.send(('mpv-fifo', self.fifopath))\n\n            self.p = subprocess.Popen(cmd, shell=False, stderr=subprocess.PIPE,\n                                      bufsize=0)\n\n        self._player_status(self.songdata + \"; \", self.song.length)\n        returncode = self.p.wait()\n\n        if returncode == 42:\n            self.previous()\n\n        elif returncode == 43:\n            self.stop()\n\n        else:\n            self.next()\n\n    def _player_status(self, prefix, songlength=0):\n        \"\"\" Capture time progress from player output. Write status line. \"\"\"\n        # pylint: disable=R0914, R0912\n        re_player = re.compile(r\".{,15}AV?:\\s*(\\d\\d):(\\d\\d):(\\d\\d)\")\n        re_volume = re.compile(r\"Volume:\\s*(?P<volume>\\d+)\\s*%\")\n        last_displayed_line = None\n        buff = ''\n        volume_level = None\n        last_pos = None\n\n        if self.sockpath:\n            s = socket.socket(socket.AF_UNIX)\n\n            tries = 0\n            while tries < 10 and self.p.poll() is None:\n                time.sleep(.5)\n                try:\n                    s.connect(self.sockpath)\n                    break\n                except socket.error:\n                    pass\n                tries += 1\n            else:\n                return\n\n            try:\n                observe_full = False\n                cmd = {\"command\": [\"observe_property\", 1, \"time-pos\"]}\n                s.send(json.dumps(cmd).encode() + b'\\n')\n                volume_level = elapsed_s = None\n\n                for line in s.makefile():\n                    resp = json.loads(line)\n\n                    # deals with bug in mpv 0.7 - 0.7.3\n                    if resp.get('event') == 'property-change' and not observe_full:\n                        cmd = {\"command\": [\"observe_property\", 2, \"volume\"]}\n                        s.send(json.dumps(cmd).encode() + b'\\n')\n                        observe_full = True\n\n                    if resp.get('event') == 'property-change' and resp['id'] == 1:\n                        if resp.get('data') is not None:\n                            elapsed_s = int(resp['data'])\n\n                    elif resp.get('event') == 'property-change' and resp['id'] == 2:\n                        volume_level = int(resp['data'])\n\n                    if(volume_level and volume_level != g.volume):\n                        g.volume = volume_level\n                    if elapsed_s:\n                        self.make_status_line(elapsed_s, prefix, songlength,\n                                              volume=volume_level)\n\n            except socket.error:\n                pass\n\n        else:\n            elapsed_s = 0\n\n            while self.p.poll() is None:\n                stdstream = self.p.stderr\n                char = stdstream.read(1).decode(\"utf-8\", errors=\"ignore\")\n\n                if char in '\\r\\n':\n\n                    mv = re_volume.search(buff)\n\n                    if mv:\n                        volume_level = int(mv.group(\"volume\"))\n\n                    match_object = re_player.match(buff)\n\n                    if match_object:\n\n                        try:\n                            h, m, s = map(int, match_object.groups())\n                            elapsed_s = h * 3600 + m * 60 + s\n\n                        except ValueError:\n\n                            try:\n                                elapsed_s = int(match_object.group('elapsed_s')\n                                                or '0')\n\n                            except ValueError:\n                                continue\n\n                        if volume_level and volume_level != g.volume:\n                            g.volume = volume_level\n                        self.make_status_line(elapsed_s, prefix, songlength,\n                                              volume=volume_level)\n\n                    if buff.startswith('ANS_volume='):\n                        volume_level = round(float(buff.split('=')[1]))\n\n                    paused = (\"PAUSE\" in buff) or (\"Paused\" in buff)\n                    if (elapsed_s != last_pos or paused) and g.mprisctl:\n                        last_pos = elapsed_s\n                        g.mprisctl.send(('pause', paused))\n                        g.mprisctl.send(('volume', volume_level))\n                        g.mprisctl.send(('time-pos', elapsed_s))\n\n                    buff = ''\n\n                else:\n                    buff += char\n\n    def _help(self, short=True):\n        \"\"\" Mplayer help.  \"\"\"\n\n        volume = \"[{0}9{1}] volume [{0}0{1}]      [{0}CTRL-C{1}] return\"\n        seek = \"[{0}\\u2190{1}] seek [{0}\\u2192{1}]\"\n        pause = \"[{0}\\u2193{1}] SEEK [{0}\\u2191{1}]       [{0}space{1}] pause\"\n\n        if not_utf8_environment:\n            seek = \"[{0}<-{1}] seek [{0}->{1}]\"\n            pause = \"[{0}DN{1}] SEEK [{0}UP{1}]       [{0}space{1}] pause\"\n\n        single = \"[{0}q{1}] next\"\n        next_prev = \"[{0}>{1}] next/prev [{0}<{1}]\"\n        # ret = \"[{0}q{1}] %s\" % (\"return\" if short else \"next track\")\n        ret = single if short and config.AUTOPLAY.get else \"\"\n        ret = next_prev if not short else ret\n        fmt = \"    %-20s       %-20s\"\n        lines = fmt % (seek, volume) + \"\\n\" + fmt % (pause, ret)\n        return lines.format(c.g, c.w)\n\n\ndef _get_input_file():\n    \"\"\" Check for existence of custom input file.\n\n    Return file name of temp input file with yewtube mappings included\n    \"\"\"\n    confpath = conf = ''\n\n    confpath = os.path.join(paths.get_config_dir(), \"mpv-input.conf\")\n\n    if os.path.isfile(confpath):\n        util.dbg(\"using %s for input key file\", confpath)\n\n        with open(confpath) as conffile:\n            conf = conffile.read() + '\\n'\n\n    conf = conf.replace(\"quit\", \"quit 43\")\n    conf = conf.replace(\"playlist_prev\", \"quit 42\")\n    conf = conf.replace(\"pt_step -1\", \"quit 42\")\n    conf = conf.replace(\"playlist_next\", \"quit\")\n    conf = conf.replace(\"pt_step 1\", \"quit\")\n    standard_cmds = ['q quit 43\\n', '> quit\\n', '< quit 42\\n', 'NEXT quit\\n',\n                     'PREV quit 42\\n', 'ENTER quit\\n', 'Q quit-watch-later']\n    bound_keys = [i.split()[0] for i in conf.splitlines() if i.split()]\n\n    for i in standard_cmds:\n        key = i.split()[0]\n\n        if key not in bound_keys:\n            conf += i\n\n    with tempfile.NamedTemporaryFile('w', prefix='mpsyt-input',\n                                     delete=False) as tmpfile:\n        tmpfile.write(conf)\n        return tmpfile.name\n\n\ndef _get_mpv_version(exename):\n    \"\"\" Get version of mpv as 3-tuple. \"\"\"\n    o = subprocess.check_output([exename, \"--version\"]).decode()\n    re_ver = re.compile(r\"mpv (\\d+)\\.(\\d+)\\.(\\d+)\")\n\n    for line in o.split(\"\\n\"):\n        m = re_ver.match(line)\n\n        if m:\n            v = tuple(map(int, m.groups()))\n            util.dbg(\"%s version %s.%s.%s detected\", exename, *v)\n            return v\n\n    util.dbg(\"%sFailed to detect mpv version%s\", c.r, c.w)\n    return -1, 0, 0\n"
  },
  {
    "path": "mps_youtube/players/vlc.py",
    "content": "import os\nimport subprocess\n\nfrom .. import config, g, util\nfrom ..player import CmdPlayer\n\n\nclass vlc(CmdPlayer):\n    def __init__(self, player):\n        self.player = player\n\n    def _generate_real_playerargs(self):\n        args = config.PLAYERARGS.get.strip().split()\n\n        pd = g.playerargs_defaults['vlc']\n        args.extend((pd[\"title\"], '\"{0}\"'.format(self.song.title)))\n\n        if config.VLC_DUMMY_INTERFACE.get:\n            print('[VLC DUMMY INTERFACE] Playing \"{0}\" ...'.format(self.song.title))\n            args.extend(('-I', 'dummy')) # vlc without gui\n        if not config.SHOW_VIDEO.get:\n            args.extend((\"--no-video\",))\n\n        util.list_update(\"--play-and-exit\", args)\n\n        return [self.player] + args + [self.stream['url']]\n\n    def clean_up(self):\n        self._kill_instance()\n\n    def launch_player(self, cmd):\n        with open(os.devnull, \"w\") as devnull:\n            self.p = subprocess.Popen(cmd, shell=False, stderr=devnull)\n        self.p.wait()\n        self.next()\n\n    def _help(self, short=True):\n        pass\n\n    def _kill_instance(self):\n        import os\n        from sys import platform\n        if platform == \"linux\" or platform == \"linux2\":\n            os.system('pkill -f vlc')\n        elif platform == \"darwin\":\n            os.system('killall vlc')\n        elif platform == \"win32\":\n            os.system('taskkill /im vlc.exe /f') # https://stackoverflow.com/questions/49988/really-killing-a-process-in-windows\n"
  },
  {
    "path": "mps_youtube/playlist.py",
    "content": "class Playlist:\n\n    \"\"\" Representation of a playist, has list of songs. \"\"\"\n\n    def __init__(self, name=None, songs=None):\n        \"\"\" class members. \"\"\"\n        self.name = name\n        self.songs = songs or []\n\n    def __len__(self):\n        \"\"\" Return number of tracks. \"\"\"\n        return len(self.songs)\n\n    def __getitem__(self, sliced):\n        return self.songs[sliced]\n\n    def __setitem__(self, position, item):\n        self.songs[position] = item\n\n    def __iter__(self):\n        for i in self.songs:\n            yield i\n\n    @property\n    def duration(self):\n        \"\"\" Sum duration of the playlist. \"\"\"\n        duration = sum(s.length for s in self.songs)\n        mins, secs = divmod(duration, 60)\n        hours, mins = divmod(mins, 60)\n        duration = '{H:02}:{M:02}:{S:02}'.format(H=hours, M=mins, S=secs)\n        return duration\n\n\nclass Video:\n\n    \"\"\" Class to represent a YouTube video. \"\"\"\n    description = \"\"\n    def __init__(self, ytid, title, length):\n        \"\"\" class members. \"\"\"\n        self.ytid = ytid\n        self.title = title\n        self.length = int(length)\n"
  },
  {
    "path": "mps_youtube/playlists.py",
    "content": "import os\nimport sys\nimport pickle\n\nfrom . import g, c, screen, util, pafy\nfrom .playlist import Playlist, Video\n\n\ndef save():\n    \"\"\" Save playlists.  Called each time a playlist is saved or deleted. \"\"\"\n    for pl in g.userpl:\n        with open(os.path.join(g.PLFOLDER, pl+'.m3u'), 'w') as plf:\n            plf.write('#EXTM3U\\n\\n')\n            for song in g.userpl[pl].songs:\n                plf.write('#EXTINF:%d,%s\\n' % (song.length, song.title))\n                plf.write('https://www.youtube.com/watch?v=%s\\n' % song.ytid)\n\n    util.dbg(c.r + \"Playlist saved\\n---\" + c.w)\n\n\ndef load():\n    \"\"\" Open playlists. Called once on script invocation. \"\"\"\n    _convert_playlist_to_v2()\n    _convert_playlist_to_m3u()\n    try:\n        # Loop through all files ending in '.m3u'\n        for m3u in [m3u for m3u in os.listdir(g.PLFOLDER) if m3u[-4:] == '.m3u']:\n            g.userpl[m3u[:-4]] = read_m3u(os.path.join(g.PLFOLDER, m3u))\n\n    except FileNotFoundError:\n        # No playlist folder, create an empty one\n        if not os.path.isdir(g.PLFOLDER):\n            g.userpl = {}\n            os.mkdir(g.PLFOLDER)\n            save()\n\n    # remove any cached urls from playlist file, these are now\n    # stored in a separate cache file\n\n    do_save = False\n\n    for k, v in g.userpl.items():\n        for song in v.songs:\n            if hasattr(song, \"urls\"):\n                util.dbg(\"remove %s: %s\", k, song.urls)\n                del song.urls\n                do_save = True\n\n    if do_save:\n        save()\n\n\ndef delete(name):\n    \"\"\" Delete playlist, including m3u file. \"\"\"\n    del g.userpl[name]\n    os.remove(os.path.join(g.PLFOLDER, name + '.m3u'))\n    \n\ndef read_m3u(m3u):\n    \"\"\" Processes an m3u file into a Playlist object. \"\"\"\n    name = os.path.basename(m3u)[:-4]\n    songs = []\n    expect_ytid = False\n\n    with open(m3u, 'r') as plf:\n        if plf.readline().startswith('#EXTM3U'):\n            for line in plf:\n                if line.startswith('#EXTINF:') and not expect_ytid:\n                    duration, title = line.replace('#EXTINF:', '').strip().split(',', 1)\n                    expect_ytid = True\n                elif not line.startswith('\\n') and not line.startswith('#') and expect_ytid:\n                    try:\n                        expect_ytid = False\n                        ytid = pafy.extract_video_id(line).strip()\n                        songs.append(Video(ytid, title, int(duration)))\n                    except ValueError as ex:\n                        util.dbg(c.r + str(ex) + c.w)\n        # Handles a simple m3u file which should just be a list of urls\n        else:\n            plf.seek(0)\n            for line in plf:\n                if not line.startswith('#'):\n                    try:\n                        p = util.get_pafy(line)\n                        songs.append(Video(p.videoid, p.title, p.length))\n                    except (IOError, ValueError) as e:\n                        util.dbg(c.r + \"Error loading video: \" + str(e) + c.w)\n\n    return Playlist(name, songs)\n\n\ndef _convert_playlist_to_v2():\n    \"\"\" Convert previous playlist file to v2 playlist. \"\"\"\n    # skip if previously done\n    if os.path.isfile(g.PLFILE):\n        return\n\n    # skip if no playlist files exist\n    elif not os.path.isfile(g.OLD_PLFILE):\n        return\n\n    try:\n        with open(g.OLD_PLFILE, \"rb\") as plf:\n            old_playlists = pickle.load(plf)\n\n    except IOError:\n        sys.exit(\"Couldn't open old playlist file\")\n\n    # rename old playlist file\n    backup = g.OLD_PLFILE + \"_v1_backup\"\n\n    if os.path.isfile(backup):\n        sys.exit(\"Error, backup exists but new playlist exists not!\")\n\n    os.rename(g.OLD_PLFILE, backup)\n\n    # do the conversion\n    for plname, plitem in old_playlists.items():\n\n        songs = []\n\n        for video in plitem.songs:\n            v = Video(video['link'], video['title'], video['duration'])\n            songs.append(v)\n\n        g.userpl[plname] = Playlist(plname, songs)\n\n    # save as v2\n    os.mkdir(g.PLFOLDER)\n    save()\n\n\ndef _convert_playlist_to_m3u():\n    \"\"\" Convert playlist_v2 file to the m3u format. \n        This should create a .m3u playlist for each playlist in playlist_v2. \"\"\"\n    # Skip if playlists folder exists\n    if os.path.isdir(g.PLFOLDER):\n        return\n\n    # Skip if no playlist files exist\n    elif not os.path.isfile(g.PLFILE):\n        return\n\n    try: \n        with open(g.PLFILE, 'rb') as plf:\n            old_playlists = pickle.load(plf)\n\n    except AttributeError:\n        # playlist is from a time when this module was __main__\n        # https://github.com/np1/mps-youtube/issues/214\n        import __main__\n        __main__.Playlist = Playlist\n        __main__.Video = Video\n\n        from . import main\n        main.Playlist = Playlist\n        main.Video = Video\n\n        with open(g.PLFILE, \"rb\") as plf:\n            g.userpl = pickle.load(plf)\n\n        os.mkdir(g.PLFOLDER)\n        save()\n        screen.msgexit(\"Updated playlist file. Please restart yewtube\", 1)\n\n    except EOFError:\n        screen.msgexit(\"Error opening playlists from %s\" % g.PLFILE, 1)\n\n    except IOError:\n        sys.exit(\"Couldn't open old playlist file\")\n\n    for pl in old_playlists:\n        songs = []\n        for song in old_playlists[pl]:\n            songs.append(song)\n\n        g.userpl[pl] = Playlist(pl, songs)\n\n    os.mkdir(g.PLFOLDER)\n    save()\n"
  },
  {
    "path": "mps_youtube/screen.py",
    "content": "import subprocess\nimport os\nimport sys\n\nfrom . import g, content, config, util\n\n\nmswin = os.name == \"nt\"\n\n\ndef update(fill_blank=True):\n    \"\"\" Display content, show message, blank screen.\"\"\"\n    clear()\n\n    if isinstance(g.content, content.PaginatedContent):\n        util.xprint(g.content.getPage(g.current_page))\n        g.rprompt = content.page_msg(g.current_page)\n    elif g.content:\n        util.xprint(g.content)\n        g.content = False\n\n    if g.message or g.rprompt:\n        out = g.message or ''\n        blanks = util.getxy().width - len(out) - len(g.rprompt or '')\n        out += ' ' * blanks + (g.rprompt or '')\n        util.xprint(out)\n\n    elif fill_blank:\n        util.xprint(\"\")\n\n    g.message = g.rprompt = False\n\n\ndef clear():\n    \"\"\"Clear all text from screen.\"\"\"\n    if g.no_clear_screen:\n        util.xprint('--\\n')\n    else:\n        util.xprint('\\n' * 200)\n\n\ndef reset_terminal():\n    \"\"\" Reset terminal control character and modes for non Win OS's. \"\"\"\n    if not mswin:\n        subprocess.call([\"tset\", \"-c\"])\n\n\ndef writestatus(text, mute=False):\n    \"\"\" Update status line. \"\"\"\n    if not mute and config.SHOW_STATUS.get:\n        _writeline(text)\n\n\ndef _writeline(text):\n    \"\"\" Print text on same line. \"\"\"\n    width = util.getxy().width\n    spaces = width - len(text) - 1\n    if mswin:\n        # Avoids creating new line every time it is run\n        # TODO: Figure out why this is needed\n        spaces =- 1\n    text = text[:width - 3]\n    sys.stdout.write(\" \" + text + (\" \" * spaces) + \"\\r\")\n    sys.stdout.flush()\n\n\ndef msgexit(msg, code=0):\n    \"\"\" Print a message and exit. \"\"\"\n    util.xprint(msg)\n    sys.exit(code)\n"
  },
  {
    "path": "mps_youtube/streams.py",
    "content": "import time\nimport threading\nfrom urllib.request import urlopen\nfrom . import pafy\nfrom . import g, c, screen, config, util\n\n\ndef prune():\n    \"\"\" Keep cache size in check. \"\"\"\n    while len(g.pafs) > g.max_cached_streams:\n        g.pafs.popitem(last=False)\n\n    while len(g.streams) > g.max_cached_streams:\n        g.streams.popitem(last=False)\n\n    # prune time expired items\n\n    now = time.time()\n    oldpafs = [k for k in g.pafs if g.pafs[k] is not None and g.pafs[k].expiry < now]\n\n    if len(oldpafs):\n        util.dbg(c.r + \"%s old pafy items pruned%s\", len(oldpafs), c.w)\n\n    for oldpaf in oldpafs:\n        g.pafs.pop(oldpaf, 0)\n\n    oldstreams = [k for k in g.streams if g.streams[k]['expiry'] is None or g.streams[k]['expiry'] < now]\n\n    if len(oldstreams):\n        util.dbg(c.r + \"%s old stream items pruned%s\", len(oldstreams), c.w)\n\n    for oldstream in oldstreams:\n        g.streams.pop(oldstream, 0)\n\n    util.dbg(c.b + \"paf: %s, streams: %s%s\", len(g.pafs), len(g.streams), c.w)\n\n\ndef get(vid, force=False, callback=None, threeD=False):\n    \"\"\" Get all streams as a dict.  callback function passed to get_pafy. \"\"\"\n    now = time.time()\n    ytid = vid.ytid\n    have_stream = g.streams.get(ytid) and (g.streams[ytid]['expiry'] > now if g.streams[ytid]['expiry'] is not None else False)\n    prfx = \"preload: \" if not callback else \"\"\n\n    if not force and have_stream:\n        ss = str(int(g.streams[ytid]['expiry'] - now) // 60)\n        util.dbg(\"%s%sGot streams from cache (%s mins left)%s\",\n                c.g, prfx, ss, c.w)\n        return g.streams.get(ytid)['meta']\n\n\n    #p = None#util.get_pafy(vid, force=force, callback=callback)\n    #ps = p.allstreams if threeD else [x for x in p.allstreams if not x.threed]\n    ps = pafy.get_video_streams(ytid)\n\n    try:\n        # test urls are valid\n        [x['url'] for x in ps]\n\n    except TypeError:\n        # refetch if problem\n        util.dbg(\"%s****Type Error in get_streams. Retrying%s\", c.r, c.w)\n        p = util.get_pafy(vid, force=True, callback=callback)\n        ps = p.allstreams if threeD else [x for x in p.allstreams\n                                          if not x.threed]\n\n    streams = [{\"url\": s['url'],\n                \"ext\": s['ext'],\n                \"quality\": s['resolution'],\n                \"rawbitrate\": s.get('bitrate',-1),\n                \"mtype\": 'audio' if 'audio' in s['resolution'] else ('video' if s['acodec'] != 'none' else '?'),\n                \"size\": int(s.get('filesize') if s.get('filesize') is not None else s.get('filesize_approx', -1))} for s in ps]\n\n\n    if 'manifest' in streams[0]['url']:\n        expiry = float(streams[0]['url'].split('/expire/')[1].split('/')[0])\n    else:\n        temp = streams[0]['url'].split('expire=')[1]\n        expiry = float(temp[:temp.find('&')])\n\n    g.streams[ytid] = dict(expiry=expiry, meta=streams)\n    prune()\n    return streams\n\n\ndef select(slist, q=0, audio=False, m4a_ok=True, maxres=None):\n    \"\"\" Select a stream from stream list. \"\"\"\n    maxres = maxres or config.MAX_RES.get\n    slist = slist['meta'] if isinstance(slist, dict) else slist\n\n    def okres(x):\n        \"\"\" Return True if resolution is within user specified maxres. \"\"\"\n        return int(x['quality'].split(\"x\")[1]) <= maxres\n\n    def getq(x):\n        \"\"\" Return height aspect of resolution, eg 640x480 => 480. \"\"\"\n        return int(x['quality'].split(\"x\")[1])\n\n    def getbitrate(x):\n        \"\"\"Return the bitrate of a stream.\"\"\"\n        return x['rawbitrate']\n\n    if audio:\n        streams = [x for x in slist if x['mtype'] == \"audio\"]\n        if not m4a_ok:\n            streams = [x for x in streams if not x['ext'] == \"m4a\"]\n        if not config.AUDIO_FORMAT.get == \"auto\":\n            if m4a_ok and config.AUDIO_FORMAT.get == \"m4a\":\n                streams = [x for x in streams if x['ext'] == \"m4a\"]\n            if config.AUDIO_FORMAT.get == \"webm\":\n                streams = [x for x in streams if x['ext'] == \"webm\"]\n            if not streams:\n                streams = [x for x in slist if x['mtype'] == \"audio\"]\n        streams = sorted(streams, key=getbitrate, reverse=True)\n    else:\n        streams = [x for x in slist if x['mtype'] == \"video\" and okres(x)]\n        if not config.VIDEO_FORMAT.get == \"auto\":\n            if config.VIDEO_FORMAT.get == \"mp4\":\n                streams = [x for x in streams if x['ext'] == \"mp4\"]\n            if config.VIDEO_FORMAT.get == \"webm\":\n                streams = [x for x in streams if x['ext'] == \"webm\"]\n            if config.VIDEO_FORMAT.get == \"3gp\":\n                streams = [x for x in streams if x['ext'] == \"3gp\"]\n            if not streams:\n                streams = [x for x in slist if x['mtype'] == \"video\" and okres(x)]\n        streams = sorted(streams, key=getq, reverse=True)\n\n    util.dbg(\"select stream, q: %s, audio: %s, len: %s\", q, audio, len(streams))\n\n    try:\n        ret = streams[q]\n\n    except IndexError:\n        ret = streams[0] if q and len(streams) else None\n\n    return ret\n\n\ndef get_size(ytid, url, preloading=False):\n    \"\"\" Get size of stream, try stream cache first. \"\"\"\n    # try cached value\n    stream = [x for x in g.streams[ytid]['meta'] if x['url'] == url][0]\n    size = stream['size']\n    prefix = \"preload: \" if preloading else \"\"\n\n    if not size == -1:\n        util.dbg(\"%s%susing cached size: %s%s\", c.g, prefix, size, c.w)\n\n    else:\n        screen.writestatus(\"Getting content length\", mute=preloading)\n        stream['size'] = _get_content_length(url, preloading=preloading)\n        util.dbg(\"%s%s - content-length: %s%s\", c.y, prefix, stream['size'], c.w)\n\n    return stream['size']\n\n\ndef _get_content_length(url, preloading=False):\n    \"\"\" Return content length of a url. \"\"\"\n    prefix = \"preload: \" if preloading else \"\"\n    util.dbg(c.y + prefix + \"getting content-length header\" + c.w)\n    response = urlopen(url)\n    headers = response.headers\n    cl = headers['content-length']\n    return int(cl)\n\n\ndef preload(song, delay=2, override=False):\n    \"\"\"  Get streams. \"\"\"\n    args = (song, delay, override)\n    t = threading.Thread(target=_preload, args=args)\n    t.daemon = True\n    t.start()\n\n\ndef _preload(song, delay, override):\n    \"\"\"  Get streams (runs in separate thread). \"\"\"\n    if g.preload_disabled:\n        return\n\n    ytid = song.ytid\n    g.preloading.append(ytid)\n    time.sleep(delay)\n    video = config.SHOW_VIDEO.get\n    video = True if override in (\"fullscreen\", \"window\", \"forcevid\") else video\n    video = False if override == \"audio\" else video\n\n    try:\n        m4a = \"mplayer\" not in config.PLAYER.get\n        streamlist = get(song)\n        stream = select(streamlist, audio=not video, m4a_ok=m4a)\n\n        if not stream and not video:\n            # preload video stream, no audio available\n            stream = select(streamlist, audio=False)\n\n        get_size(ytid, stream['url'], preloading=True)\n\n    except (ValueError, AttributeError, IOError) as e:\n        import traceback\n        traceback.print_exception(type(e), e, e.__traceback__)\n        input(\"Press any key to continue...\")\n        util.dbg(e)  # Fail silently on preload\n\n    finally:\n        g.preloading.remove(song.ytid)\n"
  },
  {
    "path": "mps_youtube/terminalsize.py",
    "content": "# https://gist.github.com/jtriley/1108174\n\n\"\"\" Terminal Size. \"\"\"\n\nimport os\nimport sys\nimport shlex\nimport shutil\nimport struct\nimport platform\nimport subprocess\n\n\ndef get_terminal_size():\n    \"\"\" getTerminalSize().\n\n    - get width and height of console\n    - works on linux,os x,windows,cygwin(windows)\n    originally retrieved from:\n    http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python\n    \"\"\"\n\n    if sys.version_info >= (3,3):\n        return shutil.get_terminal_size()\n\n    current_os = platform.system()\n    tuple_xy = None\n\n    if current_os == 'Windows':\n        tuple_xy = _get_terminal_size_windows()\n\n        if tuple_xy is None:\n            tuple_xy = _get_terminal_size_tput()\n            # needed for window's python in cygwin's xterm!\n\n    else:\n        tuple_xy = _get_terminal_size_linux()\n\n    if tuple_xy is None:\n        tuple_xy = (80, 25)      # default value\n\n    return tuple_xy\n\n\ndef _get_terminal_size_windows():\n    \"\"\" Get terminal size on MS Windows. \"\"\"\n    # pylint: disable=R0914\n    # too many local variables\n    try:\n        from ctypes import windll, create_string_buffer\n        # stdin handle is -10\n        # stdout handle is -11\n        # stderr handle is -12\n        h = windll.kernel32.GetStdHandle(-12)\n        csbi = create_string_buffer(22)\n        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\n        if res:\n            (bufx, bufy, curx, cury, wattr,\n             left, top, right, bottom,\n             maxx, maxy) = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n            sizex = right - left + 1\n            sizey = bottom - top + 1\n            return sizex, sizey\n\n    except:\n        pass\n\n\ndef _get_terminal_size_tput():\n    \"\"\" Get terminal size using tput. \"\"\"\n    # src: http://stackoverflow.com/questions/263890/\n    # how-do-i-find-the-width-height-of-a-terminal-window\n    try:\n        cols = int(subprocess.check_call(shlex.split('tput cols')))\n        rows = int(subprocess.check_call(shlex.split('tput lines')))\n        return (cols, rows)\n    except:\n        pass\n\n\ndef _get_terminal_size_linux():\n    \"\"\" Get terminal size Linux. \"\"\"\n    def ioctl_GWINSZ(fd):\n        \"\"\" ioctl_GWINSZ. \"\"\"\n        try:\n            import fcntl\n            import termios\n            cr = struct.unpack('hh',\n                               fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))\n            return cr\n\n        except:\n            pass\n\n    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)\n\n    if not cr or cr == (0, 0):\n\n        try:\n            fd = os.open(os.ctermid(), os.O_RDONLY)\n            cr = ioctl_GWINSZ(fd)\n            os.close(fd)\n\n        except:\n            pass\n\n    if not cr or cr == (0, 0):\n\n        try:\n            cr = (os.environ['LINES'], os.environ['COLUMNS'])\n\n        except:\n            return\n\n    return int(cr[1]), int(cr[0])\n"
  },
  {
    "path": "mps_youtube/test/test_main.py",
    "content": "import unittest\n\nimport pytest\n\nimport mps_youtube.main as mps\n\n\nclass TestMain(unittest.TestCase):\n    def test_fmt_time(self):\n        pytest.skip('main not have tested attribute')\n        self.assertEqual(mps.fmt_time(0), '00:00')\n        self.assertEqual(mps.fmt_time(59), '00:59')\n        self.assertEqual(mps.fmt_time(100), '01:40')\n        self.assertEqual(mps.fmt_time(1000), '16:40')\n        self.assertEqual(mps.fmt_time(5000), '83:20')\n        self.assertEqual(mps.fmt_time(6500), '1:48:20')\n\n    def test_num_repr(self):\n        pytest.skip('main not have tested attribute')\n        self.assertEqual(mps.num_repr(0), '0')\n        self.assertEqual(mps.num_repr(1001), '1001')\n        self.assertEqual(mps.num_repr(10001), '10k')\n        self.assertEqual(mps.num_repr(100001), '100k')\n        self.assertEqual(mps.num_repr(1000001), '1.0m')\n        self.assertEqual(mps.num_repr(10000001), '10m')\n        self.assertEqual(mps.num_repr(100000001), '100m')\n        self.assertEqual(mps.num_repr(1000000001), '1.0B')\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "mps_youtube/test/test_mpris.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom unittest.mock import MagicMock\n\nimport dbus\nimport pytest\n\nfrom mps_youtube import mpris\n\n\ndef test_mprsi2controller_init():\n    assert mpris.Mpris2Controller()\n\n\ndef test_mpris2mediaplayer_init():\n    bus = MagicMock()\n    obj = mpris.Mpris2MediaPlayer(bus)\n    assert obj\n    v_obj = vars(obj)\n    v_obj.pop(\"_locations_lock\")\n    #  '_locations_lock': <unlocked _thread.lock object at 0x7f0af1d20240>,\n    assert vars(obj) == {\n        \"_connection\": bus,\n        \"_fallback\": False,\n        \"_locations\": [(bus, \"/org/mpris/MediaPlayer2\", False)],\n        \"_name\": None,\n        \"_object_path\": \"/org/mpris/MediaPlayer2\",\n        \"fifo\": None,\n        \"mpv\": False,\n        \"properties\": {\n            \"org.mpris.MediaPlayer2\": {\n                \"read_only\": {\n                    \"CanQuit\": False,\n                    \"CanRaise\": False,\n                    \"CanSetFullscreen\": False,\n                    \"DesktopEntry\": \"mps-youtube\",\n                    \"HasTrackList\": False,\n                    \"Identity\": \"mps-youtube\",\n                    \"SupportedMimeTypes\": dbus.Array([], signature=dbus.Signature(\"s\")),\n                    \"SupportedUriSchemes\": dbus.Array(\n                        [], signature=dbus.Signature(\"s\")\n                    ),\n                },\n                \"read_write\": {\"Fullscreen\": False},\n            },\n            \"org.mpris.MediaPlayer2.Player\": {\n                \"read_only\": {\n                    \"CanControl\": True,\n                    \"CanGoNext\": True,\n                    \"CanGoPrevious\": True,\n                    \"CanPause\": True,\n                    \"CanPlay\": True,\n                    \"CanSeek\": True,\n                    \"MaximumRate\": 1.0,\n                    \"Metadata\": {\n                        \"mpris:trackid\": dbus.ObjectPath(\n                            \"/CurrentPlaylist/UnknownTrack\", variant_level=1\n                        )\n                    },\n                    \"MinimumRate\": 1.0,\n                    \"PlaybackStatus\": \"Stopped\",\n                    \"Position\": dbus.Int64(0),\n                },\n                \"read_write\": {\"Rate\": 1.0, \"Volume\": 1.0},\n            },\n        },\n        \"socket\": None,\n    }\n\n\n@pytest.mark.parametrize(\"val\", (None, 0, 3, 5))\ndef test_mpris2mediaplayer_set_property_time_pos(val):\n    obj = mpris.Mpris2MediaPlayer(MagicMock())\n    obj.Seeked = MagicMock()\n    obj.setproperty(\"time-pos\", val)\n    exp_res = dbus.Int64(val * 10**6) if val else dbus.Int64(0)\n    assert obj.properties[mpris.PLAYER_INTERFACE][\"read_only\"][\"Position\"] == exp_res\n    seeked_call_args = None\n    try:\n        seeked_call_args = obj.Seeked.mock_calls[0].args\n    except IndexError:\n        pass\n    if val and val >= 4:\n        assert seeked_call_args == (exp_res,)\n    else:\n        assert seeked_call_args is None\n\n\n@pytest.mark.parametrize(\n    \"val1, val2\",\n    (\n        (0, 2),\n        (2, 6),\n        (2, 5),\n        (2, 7),\n    ),\n)\ndef test_mpris2mediaplayer_set_property_time_pos_seeked(val1, val2):\n    obj = mpris.Mpris2MediaPlayer(MagicMock())\n    obj.Seeked = MagicMock()\n    obj.setproperty(\"time-pos\", val1)\n    obj.setproperty(\"time-pos\", val2)\n    seeked_call_args = None\n    try:\n        seeked_call_args = obj.Seeked.mock_calls[0].args\n    except IndexError:\n        pass\n    d2 = dbus.Int64(val2 * 10**6)\n    if abs(d2 - dbus.Int64(val1 * 10**6)) >= 4 * 10**6:\n        assert seeked_call_args == (d2,)\n    else:\n        assert seeked_call_args is None\n"
  },
  {
    "path": "mps_youtube/test/test_players_mplayer.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom unittest import mock\n\nimport pytest\n\nfrom mps_youtube.players import mplayer\n\n\n@pytest.mark.parametrize(\n    \"exename, exp_err\",\n    [\n        (\"\", (OSError, PermissionError)),\n        (\"mplayersomething\", FileNotFoundError),\n    ],\n)\ndef test_get_mplayer_version_no_mplayer(exename, exp_err):\n    with pytest.raises(exp_err):\n        mplayer._get_mplayer_version(exename)\n\n\ndef test_get_mplayer_version_invalid_input():\n    with mock.patch(\"mps_youtube.players.mplayer.subprocess\"), pytest.raises(TypeError):\n        mplayer._get_mplayer_version(mock.MagicMock())\n\n\n@pytest.mark.parametrize(\n    \"output, exp_res\",\n    [\n        (\n            \"MPlayer Redxii-SVN-r38151-6.2.0 (x86_64) (C) 2000-2019 MPlayer Team...\",\n            38151,\n        ),\n        (\"MPlayer SVN-r38151-6.2.0 (x86_64) (C) 2000-2019 MPlayer Team...\", 38151),\n        (\"MPlayer 1.4 (Debian), built with gcc-10 (C) 2000-2019 MPlayer Team\", (1, 4)),\n    ],\n)\ndef test_get_mplayer_version(output, exp_res):\n    with mock.patch(\"mps_youtube.players.mplayer.subprocess\") as m_subprocess:\n        m_subprocess.check_output.return_value.decode.return_value = output\n        assert mplayer._get_mplayer_version(mock.MagicMock()) == exp_res\n"
  },
  {
    "path": "mps_youtube/test/test_util.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pytest\n\nimport mps_youtube.util as util\n\n\n@pytest.mark.parametrize(\n    \"num,t,exp_res\",\n    (\n        (0, \"\", \"\"),\n        (0, None, \"\"),\n    ),\n)\ndef test_uea_pad(num, t, exp_res):\n    res = util.uea_pad(num, t)\n    assert res == exp_res\n"
  },
  {
    "path": "mps_youtube/util.py",
    "content": "import collections\nimport ctypes\nimport json\nimport logging\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport time\nimport unicodedata\nimport urllib\nfrom datetime import datetime, timezone\nfrom importlib import import_module\n\nfrom . import c, description_parser, g, terminalsize\nfrom .playlist import Video\n\nmacos = platform.system() == \"Darwin\"\n\nmswin = os.name == \"nt\"\nnot_utf8_environment = mswin or (\n    \"UTF-8\" not in sys.stdout.encoding if sys.stdout.encoding else False\n)\n\nXYTuple = collections.namedtuple('XYTuple', 'width height max_results')\n\n\nclass IterSlicer():\n    \"\"\" Class that takes an iterable and allows slicing,\n        loading from the iterable as needed.\"\"\"\n\n    def __init__(self, iterable, length=None):\n        self.ilist = []\n        self.iterable = iter(iterable)\n        self.length = length\n        if length is None:\n            try:\n                self.length = len(iterable)\n            except TypeError:\n                pass\n\n    def __getitem__(self, sliced):\n        if isinstance(sliced, slice):\n            stop = sliced.stop\n        else:\n            stop = sliced\n        # To get the last item in an iterable, must iterate over all items\n        if (stop is None) or (stop < 0):\n            stop = None\n        while (stop is None) or (stop > len(self.ilist) - 1):\n            try:\n                self.ilist.append(next(self.iterable))\n            except StopIteration:\n                break\n\n        return self.ilist[sliced]\n\n    def __len__(self):\n        if self.length is None:\n            self.length = len(self[:])\n        return self.length\n\n\ndef has_exefile(filename):\n    \"\"\" Check whether file exists in path and is executable.\n\n    :param filename: name of executable\n    :type filename: str\n    :returns: Path to file or False if not found\n    :rtype: str or False\n    \"\"\"\n    paths = [os.getcwd()] + os.environ.get(\"PATH\", '').split(os.pathsep)\n    paths = [i for i in paths if i]\n    dbg(\"searching path for %s\", filename)\n\n    for path in paths:\n        exepath = os.path.join(path, filename)\n\n        if os.path.isfile(exepath):\n            if os.access(exepath, os.X_OK):\n                dbg(\"found at %s\", exepath)\n                return exepath\n\n    return False\n\n\ndef dbg(*args):\n    \"\"\"Emit a debug message.\"\"\"\n    # Uses xenc to deal with UnicodeEncodeError when writing to terminal\n    logging.debug(*(xenc(i) for i in args))\n\n\ndef utf8_replace(txt):\n    \"\"\"\n    Replace unsupported characters in unicode string.\n\n    :param txt: text to filter\n    :type txt: str\n    :returns: Unicode text without any characters unsupported by locale\n    :rtype: str\n    \"\"\"\n    sse = sys.stdout.encoding\n    txt = str(txt)\n    txt = txt.encode(sse, \"replace\").decode(sse)\n    return txt\n\n\ndef xenc(stuff):\n    \"\"\" Replace unsupported characters. \"\"\"\n    return utf8_replace(stuff) if not_utf8_environment else stuff\n\n\ndef xprint(stuff, end=None):\n    \"\"\" Compatible print. \"\"\"\n    print(xenc(stuff), end=end)\n\n\ndef mswinfn(filename):\n    \"\"\" Fix filename for Windows. \"\"\"\n    if mswin:\n        filename = utf8_replace(filename) if not_utf8_environment else filename\n        allowed = re.compile(r'[^\\\\/?*$\\'\"%&:<>|]')\n        filename = \"\".join(x if allowed.match(x) else \"_\" for x in filename)\n\n    return filename\n\ndef sanitize_filename(filename, ignore_slashes=False):\n    \"\"\" Sanitize filename \"\"\"\n    if not ignore_slashes:\n        filename = filename.replace('/', '-')\n    if macos:\n        filename = filename.replace(':', '_')\n    if mswin:\n        filename = utf8_replace(filename) if not_utf8_environment else filename\n        allowed = re.compile(r'[^\\\\?*$\\'\"%&:<>|]')\n        filename = \"\".join(x if allowed.match(x) else \"_\" for x in filename)\n\n    return filename\n\ndef set_window_title(title):\n    \"\"\" Set terminal window title. \"\"\"\n    if mswin:\n        ctypes.windll.kernel32.SetConsoleTitleW(xenc(title))\n    else:\n        sys.stdout.write(xenc('\\x1b]2;' + title + '\\x07'))\n\n\ndef list_update(item, lst, remove=False):\n    \"\"\" Add or remove item from list, checking first to avoid exceptions. \"\"\"\n    if not remove and item not in lst:\n        lst.append(item)\n\n    elif remove and item in lst:\n        lst.remove(item)\n\n\ndef get_near_name(begin, items):\n    \"\"\" Return the closest matching playlist name that starts with begin. \"\"\"\n    for name in sorted(items):\n        if name.lower().startswith(begin.lower()):\n            return name\n    return begin\n\n\ndef F(key, nb=0, na=0, textlib=None):\n    \"\"\"Format text.\n\n    :param nb: newline before\n    :type nb: int\n    :param na: newline after\n    :type na: int\n    :param textlib: the dictionary to use (defaults to g.text if not given)\n    :type textlib: dict\n    :returns: A string, potentially containing one or more %s\n    :rtype: str\n    \"\"\"\n    textlib = textlib or g.text\n\n    assert key in textlib\n    text = textlib[key]\n    percent_fmt = textlib.get(key + \"_\")\n\n    if percent_fmt:\n        text = re.sub(r\"\\*\", r\"%s\", text) % percent_fmt\n\n    text = text.replace(\"&&\", \"%s\")\n\n    return \"\\n\" * nb + text + c.w + \"\\n\" * na\n\n\ndef get_pafy(item, force=False, callback=None):\n    \"\"\"\n    Get pafy object for an item.\n\n    :param item: video to retrieve\n    :type item: :class:`mps_youtube.playlist.Video` or str\n    :param force: ignore cache and retrieve anyway\n    :type force: bool\n    :param callback: callpack to pass to pafy\n    :type callback: func\n    :rtype: Pafy\n    \"\"\"\n\n    if isinstance(item, Video):\n        ytid = item.ytid\n    else:\n        ytid = item\n    callback_fn = callback or (lambda x: None)\n    cached = g.pafs.get(ytid)\n\n    if not force and cached and cached.expiry > time.time():\n        dbg(\"get pafy cache hit for %s\", cached.title)\n        cached.fresh = False\n        return cached\n\n    else:\n\n        try:\n            p = None#pafy.new(ytid, callback=callback_fn)\n\n        except IOError as e:\n\n            if \"pafy\" in str(e):\n                dbg(c.p + \"retrying failed pafy get: \" + ytid + c.w)\n                p = None#pafy.new(ytid, callback=callback)\n\n            else:\n                raise\n\n        g.pafs[ytid] = p\n        p.fresh = True\n        thread = \"preload: \" if not callback else \"\"\n        dbg(\"%s%sgot new pafy object: %s%s\" % (c.y, thread, p.title[:26], c.w))\n        dbg(\"%s%sgot new pafy object: %s%s\" % (c.y, thread, p.videoid, c.w))\n        return p\n\n\ndef getxy():\n    \"\"\"\n    Get terminal size, terminal width and max-results.\n\n    :rtype: :class:`XYTuple`\n    \"\"\"\n    # Import here to avoid circular dependency\n    from . import config\n    if g.detectable_size:\n        x, y = terminalsize.get_terminal_size()\n        max_results = y - 4 if y < 54 else 50\n        max_results = 1 if y <= 5 else max_results\n\n    else:\n        x, max_results = config.CONSOLE_WIDTH.get, config.MAX_RESULTS.get\n        y = max_results + 4\n\n    return XYTuple(x, y, max_results)\n\n\ndef fmt_time(seconds):\n    \"\"\" Format number of seconds to %H:%M:%S. \"\"\"\n    hms = time.strftime('%H:%M:%S', time.gmtime(int(seconds)))\n    H, M, S = hms.split(\":\")\n\n    if H == \"00\":\n        hms = M + \":\" + S\n\n    elif H == \"01\" and int(M) < 40:\n        hms = str(int(M) + 60) + \":\" + S\n\n    elif H.startswith(\"0\"):\n        hms = \":\".join([H[1], M, S])\n\n    return hms\n\ndef correct_truncate(text, max_len):\n    \"\"\" Truncate a string taking into account East Asian width chars.\"\"\"\n    str_len, out = 0, ''\n\n    for c in text:\n        str_len += real_len(c)\n\n        if str_len <= max_len:\n            out += c\n\n        else:\n            break\n\n    return out\n\n\ndef uea_pad(num, t, direction=\"<\", notrunc=False):\n    \"\"\" Right pad with spaces taking into account East Asian width chars. \"\"\"\n    direction = direction.strip() or \"<\"\n\n    t = ' '.join(str(t).split('\\n'))\n\n    # TODO: Find better way of dealing with this?\n    if num <= 0:\n        return ''\n\n    if not notrunc:\n        # Truncate to max of num characters\n        t = correct_truncate(t, num)\n\n    if real_len(t) < num:\n        spaces = num - real_len(t)\n\n        if direction == \"<\":\n            t = t + (\" \" * spaces)\n\n        elif direction == \">\":\n            t = (\" \" * spaces) + t\n\n        elif direction == \"^\":\n            right = False\n\n            while real_len(t) < num:\n                t = t + \" \" if right else \" \" + t\n                right = not right\n\n    return t\n\n\ndef real_len(u, alt=False):\n    \"\"\" Try to determine width of strings displayed with monospace font. \"\"\"\n    if not isinstance(u, str):\n        u = u.decode(\"utf8\")\n\n    u = xenc(u) # Handle replacements of unsuported characters\n\n    ueaw = unicodedata.east_asian_width\n\n    if alt:\n        # widths = dict(W=2, F=2, A=1, N=0.75, H=0.5)  # original\n        widths = dict(N=.75, Na=1, W=2, F=2, A=1)\n\n    else:\n        widths = dict(W=2, F=2, A=1, N=1, H=0.5)\n\n    return int(round(sum(widths.get(ueaw(char), 1) for char in u)))\n\n\ndef yt_datetime(yt_date_time):\n    \"\"\" Return a time object, locale formated date string and locale formatted time string. \"\"\"\n    if yt_date_time is None:\n        return ['Unknown', 'Unknown', 'Unknown']\n    time_obj = time.strptime(yt_date_time, \"%Y-%m-%dT%H:%M:%SZ\")\n    locale_date = time.strftime(\"%x\", time_obj)\n    locale_time = time.strftime(\"%X\", time_obj)\n    # strip first two digits of four digit year\n    short_date = re.sub(r\"(\\d\\d\\D\\d\\d\\D)20(\\d\\d)$\", r\"\\1\\2\", locale_date)\n    return time_obj, short_date, locale_time\n\n\ndef yt_datetime_local(yt_date_time):\n    \"\"\" Return a datetime object, locale converted and formated date string and locale converted and formatted time string. \"\"\"\n    datetime_obj = datetime.strptime(yt_date_time, \"%Y-%m-%dT%H:%M:%SZ\")\n    datetime_obj = utc2local(datetime_obj)\n    locale_date = datetime_obj.strftime(\"%x\")\n    locale_time = datetime_obj.strftime(\"%X\")\n    # strip first two digits of four digit year\n    short_date = re.sub(r\"(\\d\\d\\D\\d\\d\\D)20(\\d\\d)$\", r\"\\1\\2\", locale_date)\n    return datetime_obj, short_date, locale_time\n\n\ndef utc2local(utc):\n    return utc.replace(tzinfo=timezone.utc).astimezone(tz=None)\n\n\ndef parse_multi(choice, end=None):\n    \"\"\"\n    Handle ranges like 5-9, 9-5, 5- and -5 with optional repetitions number [n]\n\n    eg. 2-4[2] is the same as 2 3 4 2 3 4 and 3[4] is 3 3 3 3\n\n    Return list of ints.\n\n    \"\"\"\n    end = end or str(len(g.model))\n    pattern = r'(?<![-\\d\\[\\]])(\\d+-\\d+|-\\d+|\\d+-|\\d+)(?:\\[(\\d+)\\])?(?![-\\d\\[\\]])'\n    items = re.findall(pattern, choice)\n    alltracks = []\n\n    for x, nreps in items:\n        # nreps is in the inclusive range [1,100]\n        nreps = min(int(nreps), 100) if nreps else 1\n        for _ in range(nreps):\n\n            if x.startswith(\"-\"):\n                x = \"1\" + x\n\n            elif x.endswith(\"-\"):\n                x = x + str(end)\n\n            if \"-\" in x:\n                nrange = x.split(\"-\")\n                startend = map(int, nrange)\n                alltracks += _bi_range(*startend)\n\n            else:\n                alltracks.append(int(x))\n\n    return alltracks\n\n\ndef _bi_range(start, end):\n    \"\"\"\n    Inclusive range function, works for reverse ranges.\n\n    eg. 5,2 returns [5,4,3,2] and 2, 4 returns [2,3,4]\n\n    \"\"\"\n    if start == end:\n        return (start,)\n\n    elif end < start:\n        return reversed(range(end, start + 1))\n\n    else:\n        return range(start, end + 1)\n\n\ndef is_known_player(player):\n    \"\"\" Return true if the set player is known. \"\"\"\n    for allowed_player in g.playerargs_defaults:\n        regex = r'(?:\\b%s($|\\.[a-zA-Z0-9]+$))' % re.escape(allowed_player)\n        match = re.search(regex, player)\n\n        if mswin:\n            match = re.search(regex, player, re.IGNORECASE)\n\n        if match:\n            return allowed_player\n\n    return None\n\n\ndef load_player_info(player):\n    if \"mpv\" in player:\n        g.mpv_version = _get_mpv_version(player)\n        g.mpv_options = subprocess.check_output(\n                [player, \"--list-options\"]).decode()\n\n        if not mswin:\n            if \"--input-unix-socket\" in g.mpv_options:\n                g.mpv_usesock = \"--input-unix-socket\"\n                dbg(c.g + \"mpv supports --input-unix-socket\" + c.w)\n            elif \"--input-ipc-server\" in g.mpv_options:\n                g.mpv_usesock = \"--input-ipc-server\"\n                dbg(c.g + \"mpv supports --input-ipc-server\" + c.w)\n\n    elif \"mplayer\" in player:\n        g.mplayer_version = _get_mplayer_version(player)\n\n\ndef fetch_songs(text, title=\"Unknown\"):\n    return description_parser.parse(text, title)\n\n\ndef number_string_to_list(text):\n    \"\"\" Parses comma separated lists \"\"\"\n    text = [x.strip() for x in text.split(\",\")]\n    vals = []\n    for line in text:\n        k = line\n        if \"-\" in line:\n            separated = [int(x.strip()) for x in k.split(\"-\")]\n            for number in list(range(separated[0]-1, separated[1])):\n                vals.append(number)\n        else:\n            vals.append(k)\n\n    return [int(x) - 1 for x in vals]\n\n\ndef _get_mpv_version(exename):\n    \"\"\" Get version of mpv as 3-tuple. \"\"\"\n    o = subprocess.check_output([exename, \"--version\"]).decode()\n    re_ver = re.compile(r\"mpv (\\d+)\\.(\\d+)\\.(\\d+)\")\n\n    for line in o.split(\"\\n\"):\n        m = re_ver.match(line)\n\n        if m:\n            v = tuple(map(int, m.groups()))\n            dbg(\"%s version %s.%s.%s detected\", exename, *v)\n            return v\n\n    dbg(\"%sFailed to detect mpv version%s\", c.r, c.w)\n    return -1, 0, 0\n\n\ndef _get_mplayer_version(exename):\n    o = subprocess.check_output([exename]).decode()\n    m = re.search('MPlayer SVN[\\s-]r([0-9]+)', o, re.MULTILINE|re.IGNORECASE)\n\n    ver = 0\n    if m:\n        ver = int(m.groups()[0])\n    else:\n        m = re.search('MPlayer ([0-9])+.([0-9]+)', o, re.MULTILINE)\n        if m:\n            ver = tuple(int(i) for i in m.groups())\n\n        else:\n            dbg(\"%sFailed to detect mplayer version%s\", c.r, c.w)\n\n    return ver\n\n\ndef _get_metadata(song_title):\n    ''' Get metadata from a song title '''\n    t = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", song_title.lower())\n    t = t.split('-')\n\n    if len(t) != 2:  # If len is not 2, no way of properly knowing title for sure\n        t = t[0]\n        t = t.split(':')\n        if len(t) != 2:  # Ugly, but to be safe in case all these chars exist, Will improve\n            t = t[0]\n            t = t.split('|')\n            if len(t) != 2:\n                return None\n\n    t[0] = re.sub(\"(ft |ft.|feat |feat.).*.\", \"\", t[0])\n    t[1] = re.sub(\"(ft |ft.|feat |feat.).*.\", \"\", t[1])\n\n    t[0] = t[0].strip()\n    t[1] = t[1].strip()\n\n    metadata = _get_metadata_from_lastfm(t[0], t[1])\n\n    if metadata is not None:\n        return metadata\n\n    metadata = _get_metadata_from_lastfm(t[1], t[0])\n    return metadata\n\n\ndef _get_metadata_from_lastfm(artist, track):\n    ''' Try to get metadata with a given artist and track '''\n    url = 'https://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=12dec50313f885d407cf8132697b8712&'\n    url += urllib.parse.urlencode({\"artist\":  artist}) + '&'\n    url += urllib.parse.urlencode({\"track\":  track}) + '&'\n    url += '&format=json'\n\n    try:\n        resp = urllib.request.urlopen(url)\n        metadata = dict()\n        # Prior to Python 3.6, json.loads cannot take a bytes object\n        data = json.loads(resp.read().decode('utf-8'))\n        metadata['track_title'] = data['track']['name']\n        metadata['artist'] = data['track']['artist']['name']\n        metadata['album'] = data['track']['album']['title']\n        metadata['album_art_url'] = data['track']['album']['image'][-1]['#text']\n    except (KeyError, IndexError):\n        return None\n    except (urllib.error.HTTPError, urllib.error.URLError):\n        return None\n    return metadata\n\n\ndef assign_player(player):\n    module_name = player\n\n    if '/' in module_name:\n        module_name = module_name.split('/')[-1]\n    if module_name.endswith('.com') or module_name.endswith('.exe'):\n        module_name = module_name.split('.')[0]\n\n    try:\n        module = import_module('mps_youtube.players.{0}'.format(module_name))\n        pl = getattr(module, module_name)\n        g.PLAYER_OBJ = pl(player)\n\n    except ImportError:\n        from mps_youtube.players import GenericPlayer\n        g.PLAYER_OBJ = GenericPlayer.GenericPlayer(player)\n\n\nclass CommandCompleter:\n\n    COMMANDS = []\n\n    def __init__(self):\n        from . import config\n        self.SET_COMMANDS = ['set ' + i.lower() for i in config]\n\n    def complete_command(self, text, state):\n        if text.startswith('set'):\n            results = [x for x in self.SET_COMMANDS if x.startswith(text)] + [None]\n        else:\n            results = [x for x in self.COMMANDS if x.startswith(text)] + [None]\n        return results[state]\n    def add_cmd(self, val):\n        if(not val in self.COMMANDS):\n            self.COMMANDS.append(val)\n\ndef parse_video_length(duration):\n    '''\n    Converts HH:MM:SS to a single integer .i.e. total number of seconds\n    '''\n    if duration:\n        duration_tokens = duration.split(\":\")\n        if len(duration_tokens) == 2:\n            return int(duration_tokens[0]) * 60 + int(duration_tokens[1])\n        else:\n            return int(duration_tokens[0]) * 3600 + int(duration_tokens[1]) * 60 + int(duration_tokens[2])\n    else:\n        return 10\n"
  },
  {
    "path": "requirements.txt",
    "content": "requests\npyreadline3 ; platform_system==\"Windows\"\npyperclip\nyoutube-search-python>=1.6.5\nyt-dlp\ncolorama ; platform_system==\"Windows\"\n"
  },
  {
    "path": "setup.cfg",
    "content": "[semantic_release]\nversion_variable = setup.py:__version__\n\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/python3\n\n\"\"\" setup.py for yewtube.\n\nhttps://github.com/iamtalhaasghar/yewtube\n\npython setup.py sdist bdist_wheel\n\"\"\"\n\nimport os\nimport sys\n\nif sys.version_info < (3, 6):\n    sys.exit(\"yewtube requires minimum python 3.6\")\n\nfrom setuptools import setup\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n    long_description = fh.read()\n\nwith open('requirements.txt', 'r') as fh:\n    requirements = fh.readlines()\n\n__version__ = \"2.9.2\"\n\noptions = dict(\n    name=\"yewtube\",\n    version=__version__,\n    description=\"A Terminal based YouTube player and downloader. No Youtube API key required. Forked from mps-youtube\",\n    keywords=[\"video\", \"music\", \"audio\", \"youtube\", \"stream\", \"download\"],\n    author=\"talha_programmer\",\n    author_email=\"talhaasghar.contact@simplelogin.fr\",\n    url=\"https://github.com/iamtalhaasghar/yewtube\",\n    download_url=\"https://github.com/iamtalhaasghar/yewtube/releases\",\n    packages=['mps_youtube', 'mps_youtube.commands', 'mps_youtube.listview', 'mps_youtube.players'],\n    entry_points={'console_scripts': ['yt = mps_youtube:main.main']},\n    python_requires='>=3.6',\n    install_requires=requirements,\n    extras_require={\n        \"mpris\": [\n            \"dbus-python>=1.2.18\",\n            \"PyGObject>=3.42.0\",\n        ],\n        \"docs\": [\n            \"mkdocs-gen-files>=0.3.4\",\n            \"mkdocs-literate-nav>=0.4.1\",\n            \"mkdocs-macros-plugin>=0.6.4\",\n            \"mkdocs-material>=8.2.1\",\n            \"mkdocstrings-python-legacy>=0.2.2\",\n            \"mkdocstrings>=0.18.0\",\n        ],\n    },\n    classifiers=[\n        \"Topic :: Utilities\",\n        \"Topic :: Internet :: WWW/HTTP\",\n        \"Topic :: Multimedia :: Sound/Audio :: Players\",\n        \"Topic :: Multimedia :: Video\",\n        \"Environment :: Console\",\n        \"Environment :: Win32 (MS Windows)\",\n        \"Environment :: MacOS X\",\n        \"Operating System :: POSIX :: Linux\",\n        \"Operating System :: MacOS\",\n        \"Operating System :: MacOS :: MacOS 9\",\n        \"Operating System :: MacOS :: MacOS X\",\n        \"Operating System :: Microsoft\",\n        \"Operating System :: Microsoft :: Windows :: Windows 7\",\n        \"Operating System :: Microsoft :: Windows :: Windows XP\",\n        \"Operating System :: Microsoft :: Windows :: Windows Vista\",\n        \"Intended Audience :: End Users/Desktop\",\n        \"Programming Language :: Python\",\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.3\",\n        \"Programming Language :: Python :: 3.4\",\n        \"Programming Language :: Python :: 3 :: Only\",\n        \"Development Status :: 5 - Production/Stable\",\n        \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\"\n    ],\n    options={\n        \"py2exe\": {\n            \"excludes\": (\"readline, win32api, win32con, dbus, gi,\"\n                         \" urllib.unquote_plus, urllib.urlencode,\"\n                         \" PyQt4, gtk\"),\n            \"bundle_files\": 1\n        }\n    },\n    package_data={\"\": [\"LICENSE\", \"README.md\", \"CHANGELOG.md\"]},\n    long_description_content_type='text/markdown',\n    long_description=long_description\n)\n\nif sys.platform.startswith('linux'):\n    # Install desktop file. Required for mpris on Ubuntu\n    options['data_files'] = [('share/applications/', ['yewtube.desktop'])]\n\nif os.name == \"nt\":\n    try:\n        import py2exe\n\n        # Only setting these when py2exe imports successfully prevents warnings\n        # in easy_install\n        options['console'] = ['yt']\n        options['zipfile'] = None\n    except ImportError:\n        pass\n\nsetup(**options)\n"
  },
  {
    "path": "wheel_recipe.sh",
    "content": "rm -rf dist/\npython -m build --sdist\npython -m build --wheel\ntwine upload --verbose dist/*"
  },
  {
    "path": "yewtube.desktop",
    "content": "[Desktop Entry]\nName=yewtube\nGenericName=Music Player\nKeywords=Audio;Song;Podcast;Playlist;youtube.com;\nExec=yt %U\nTerminal=true\nIcon=terminal\nType=Application\nCategories=AudioVideo;Audio;Player;\nStartupNotify=true\nNoDisplay=true\n"
  },
  {
    "path": "yt",
    "content": "#!/usr/bin/env python3\nimport mps_youtube.main\nmps_youtube.main.main()"
  }
]