pax_global_header00006660000000000000000000000064127554031150014515gustar00rootroot0000000000000052 comment=388db45729f26e986041862c9cd0c16dd902f895 pafy-0.5.2/000077500000000000000000000000001275540311500124605ustar00rootroot00000000000000pafy-0.5.2/.gitignore000066400000000000000000000001431275540311500144460ustar00rootroot00000000000000MANIFEST doc/_build/ *.help .tox .coverage htmlcov/ dev/ /dist .test *.pyc .pypi vi.py __pycache__ pafy-0.5.2/.travis.yml000066400000000000000000000013501275540311500145700ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" - "3.3" - "3.4" install: - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - pip install coveralls > /dev/null - pip install youtube-dl > /dev/null before_script: - printenv - ls -l - coverage debug sys - pip install wheel - python setup.py sdist bdist_wheel - python setup.py install script: coverage run --omit="/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/unittest2/*,/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/six.py,/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/argparse.py" tests/test.py after_success: - coverage report - coveralls sudo: false pafy-0.5.2/AUTHORS000066400000000000000000000001421275540311500135250ustar00rootroot00000000000000np1 ElegantMonkey kewitz davidfischer-ch sadolit Dav1dde stav hugovk ids1024 williamroot trygveaa pafy-0.5.2/CHANGELOG000066400000000000000000000312541275540311500136770ustar00rootroot0000000000000018 August 2016 Version 0.5.2 [Bugfix] - Fix internal backend (#140) [Update] - Support liked video playlist (#149) [Update] - Add spaces to file name format (@ghost) (#145) ------------------------------------------------------------------------------- 31 May 2016 Version 0.5.1 [Bugfix] - Fix python 2 import (#134) [Bugfix] - Fix two bugs in the internal backend (major bug remains unfixed) [Update] - Remove deprecated signature argument ------------------------------------------------------------------------------- 28 February 2016 Version 0.5.0 [Feature] - Support both youtube-dl backend and internal backend (old 0.3.x branch. This makes youtube-dl an optional dependency, though it is more stable and thus recommended. There will be no more 0.3.x releases, as this eliminates the need for them. To use the internal backend even if youtube-dl is installed, set the environmental variable PAFY_BACKEND to "internal". [Bugfix] - Fix UnicodeDecodeError(krishnawhite) (#129) [Bugfix] - Fix quality property ------------------------------------------------------------------------------- 1 January 2016 Version 0.4.3 [Feature] - get_playlist2() command with new interface and support for playlists longer than 200 videos (ids1024) [Bugfix] - Fix ZeroDivisionError (cpnielsen) (#125) ------------------------------------------------------------------------------- 11 November 2015 Version 0.4.2 [Bugfix] - Fix crash when snippet has no tags property [Bugfix] - Fix issue with get_filesize on some streams [Bugfix] - Fix bigthumb and bigthumbhd (#118) [Feature] - Allow specifying youtube-dl arguments (#115 #120) ------------------------------------------------------------------------------- 4 October 2015 Version 0.4.1 [Bugfix] - Fix Pafy.streams ------------------------------------------------------------------------------- 4 October 2015 Version 0.4.0 [Major Update!] - Pull in youtube-dl as a dependency, replacing current stream code [#109] This is a major change, and will likely prove controversial, so version 0.3.76 has been released concurrently with all the changes not related to youtube-dl. This makes the code simpler and easier to maintain while fixing various bugs, but has some disadvantages. If this is a problem for you, please use version 0.3.76 AND state your reasons and suggestions at issue #110 on Github. https://github.com/mps-youtube/pafy/issues/110 ------------------------------------------------------------------------------- 4 October 2015 Version 0.3.76 [Bugfix] - Fix bug in ytdl (#101 #102) [Update] - Use better method for matching urls (#104) [Bugfix] - Use .opus extension for opus audio (#108) ------------------------------------------------------------------------------- 1 June 2015 Version 0.3.74 [Bugfix] - Update to use gdata 3 instead of broken gdata 2 (#78) [Bugfix] - Fix ZeroDivisionError (#80) [Bugfix] - Fix ytdl with non-unicode terminal (#67) [Bugfix] - Fix 503 errors by retrying [Update] - Added mix method ------------------------------------------------------------------------------- 3 February 2015 Version 0.3.72 [Bugfix] - Fix issue with country restricted items (#74) ------------------------------------------------------------------------------- 1 February 2015 Version 0.3.70 [Bugfix] - Fix "Sign in to confirm your age" message on some videos ------------------------------------------------------------------------------- 13 January 2015 Version 0.3.68 [Update] - changed to LGPL license (was GPL) (#68) [Update] - Added getbestvideo function (#70) ------------------------------------------------------------------------------- 23 November 2014 Version 0.3.66 [Update] - Added new itags for 60fps and VP9 streams (298, 299, 302, 303) [Bugfix] - Fixed failure on certain video items (#59) [Update] - Added start/end data for playlist items (Dav1dde) (#62, #63) ------------------------------------------------------------------------------- 19 October 2014 Version 0.3.64 [Update] - Cache javascript file locally to temp dir (less fetching) [Update] - Added itag 278 (low-res VP9) [Feature] - Retrieve DASH streams (more streams, higher quality audio) [Feature] - added remux_audio parameter to download function to remux audio files if ffmpeg or avconv is installed (better compatibility) ------------------------------------------------------------------------------- 27 August 2014 Version 0.3.62 [Feature] - Added url_https property to return https url ------------------------------------------------------------------------------- 15 August 2014 Version 0.3.60 [Bugfix] - Add Opus audio itags 249/250/251 [Bugfix] - Warn instead of fail on unrecognised itags ------------------------------------------------------------------------------- 24 July 2014 Version 0.3.58 [Feature] - Added cancel download function (stav) (#47) [Bugfix] - Update signature decryption to work with YouTube changes (#48) ------------------------------------------------------------------------------- 16 July 2014 Version 0.3.56 [Bugfix] - Update signature decryption to work with YouTube changes (#43) ------------------------------------------------------------------------------- 12 July 2014 Version 0.3.54 [Bufix] - Fix issues with Windows filenames (issues #35, #38, #39) ------------------------------------------------------------------------------- 22 June 2014 Version 0.3.52 [Bugfix] - Added unrecognised itags (issue #34) ------------------------------------------------------------------------------- 19 June 2014 Version 0.3.50 [Feature] - Resume partially downloaded files (issue #32) [Bugfix] - Fix javascript function extraction ------------------------------------------------------------------------------- 12 June 2014 Version 0.3.48 [Bugfix] - Added new itag (271) ------------------------------------------------------------------------------- 5 June 2014 Version 0.3.46 - Bugfix release [Bugfix] - Fix truncated rawbitrate stream property [Bugfix] - Use unicode literals in ytdl (#31) ------------------------------------------------------------------------------- 21 May 2014 Version 0.3.44 [Bugfix] - Fixed m4astreams and oggstreams return empty lists [Bugfix] - Fixed get_playlist() returns a tuple for playlist_id [Bugfix] - Fixed TypeError on getting url (issue #30) [Update] - Properties now return Unicode in both Python 2 and 3 [Update] - Package now includes wheel (PEP 427) ------------------------------------------------------------------------------- 30 April 2014 Version 0.3.42 [Feature] - Added support for age-restricted videos with encrypted signatures [Feature] - Added likes and dislikes properties [Bugfix] - Fix incorrectly formatted published date [Bugfix] - Fix incorrect media type for itags 242 - 248 ------------------------------------------------------------------------------- 5 March 2014 Version 0.3.41 [Feature] - Fetch updated time for playlist items [Feature] - Added Python 2.6 compatibility (requires argparse from PyPI) [Bugfix] - Handle location-specific number formats (thousands separator) ------------------------------------------------------------------------------- 2 March 2014 Version 0.3.39 [Feature] - Add username property (fetched from gdata) [Update] - Improved and documented get_playlist() feature ------------------------------------------------------------------------------- 27 February 2014 Version 0.3.38 [Update] - Use http instead of https [Update] - Add missing itags 167-170 ------------------------------------------------------------------------------- 25 February 2014 Version 0.3.37 [Feature] - Added signature, gdata, basic and size parameters to new() These parameters can be used to restrict the data fetched on instantiation of Pafy objects and can significantly reduce the time taken to create new instances. Any missing data will be fetched when needed. [Feature] - Javascript is released internally once functions are extracted Smaller memory footprint for Pafy / Stream objects [Bugfix] - release unneeded internal data, smaller pafy objects [Update] - getbest and getbestaudio() return None if no streams available [Update] - Pafy raises ValueError or IOError. RuntimeError removed [Update] - len() has been removed. use .length property instead ------------------------------------------------------------------------------- 20 February 2014 Version 0.3.36 [Feature] - Added published date field [Bugfix] - Added missing notes field to itag 264 ------------------------------------------------------------------------------- 17 February 2014 Version 0.3.35 [Feature] - Added notes attribute to Stream class for further stream info [Feature] - Added function to fetch playlists (leokewitz) [Bugfix] - Add missing itag (83) ------------------------------------------------------------------------------- 11 February 2014 Version 0.3.34 [Bugfix] - getbest() and getbestaudio() now return False if no streams available ------------------------------------------------------------------------------- 7 February 2014 Version 0.3.33 Authors: leokewitz, np1 [Feature] - Store html5player js data in memory to reduce repeat fetches [Feature] - Removed redundant looping in js function extraction [Bugfix] - Display correct units for data rate ------------------------------------------------------------------------------- 4 February 2014 Version 0.3.31 Authors: np1 [Bugfix] - Handle error getting stream map [Bugfix] - Handle dollar character in js function name ------------------------------------------------------------------------------- 3 February 2014 Version 0.3.30 Authors: np1 [Bugfix] - Fix regex for decrypting signatures [Feature] - Added callback function for status reporting ------------------------------------------------------------------------------- 14 January 2014 Version 0.3.26 Authors: np1 [Feature] - Change dimensions property from (str, str) to (int, int) [Bugfix] - Replace bad characters in filenames ------------------------------------------------------------------------------- 15 December 2013 Version 0.3.25 Authors: np1 [Feature] Get video category metadata. ------------------------------------------------------------------------------- 12 December 2013 Version 0.3.24 Authors: hugovk, np1 [Feature] Download function to return the name of file saved [Feature] Get video description [Bugfix] Fix for js file without protocol specifier ------------------------------------------------------------------------------- 14 November 2013 Version 0.3.23 Authors: davidfischer-ch, np1 [Bugfix] Fixed issue when no keywords specified for YouTube video [Bugfix] added UTF8 encoding declaration [Bugfix] Update shebang to /usr/bin/env python instead of /usr/bin/python [Docs] Added README to PyPI ------------------------------------------------------------------------------- 27 October 2013 Version 0.3.22 Authors: np1 [Feature] Added Pafy.oggstreams and Pafy.m4astreams codec specific stream lists [Feature] Added Pafy.dimensions attribute to return resolution as a 2-tuple [Feature] Added Pafy.rawbitrate attribute for more precise bitrates of audio streams [Feature] Added Pafy.threed attribute to reflect whether a stream is 3D [Feature] Added Stream.__repr__() to output more meaningful info when printing Stream objects [Bugfix] Fix for getbest() and getbestaudio() returning wrong filetype in some cases [Bugfix] Fixed some incorrect reporting of resolutions [Docs] Using reStructured text instead of GitHub markdown for README [Docs] Added full documentation at http://pythonhosted.org/Pafy/ ------------------------------------------------------------------------------- 19 October 2013 Version 0.3.20 Authors: np1 [Feature] Added support for audio-only stream download (m4a and ogg vorbis) [Feature] Added support for video-only stream download (m4v) [Feature] Added bitrate property for audio streams [Feature] Added quality property to return bitrate or resolution depending on stream type (audio or video) [Feature] Updated ytdl command line tool to incorporate download choices from above streams [Feature] Added getbestaudio() function to automatically select best quality audio stream [Bugfix] Allow downloading of videos with no title [Docs] Updated documentation for pafy and ytdl demonstrating usage of above features (README.md) [Docs] Added this changelog file Notes: This version should be fully backward compatible with the previous version. Pafy objects retain the pafy.streams list containing regular streams as before (video + audio) In addition, there are now two new stream lists; pafy.audiostreams is a list of audio only streams (m4a and ogg vorbis where available) pafy.videostreams is a list of video only streams (m4v) Further, there is a pafy.allstreams list containing the union of all three aforementioned lists pafy-0.5.2/CONTRIBUTING000066400000000000000000000014011275540311500143060ustar00rootroot00000000000000Contributions are very much appreciated! Pull requests should be based on and submitted to the "develop" branch Please raise an issue to discuss what you plan to implement or change before you start if it is going to involve a lot of work on your part. Please keep pull requests specific, do not make many disparate changes or new features in one request. A separate pull request for each feature change is preferred. Please ensure your changes work in Python 2.6+, 3.3+ and Windows. Please add your github id to the AUTHORS file Code conventions: ----------------- Maximum line length is 80 characters Follow the line-spacing style that is already in place. Ensure all functions and classes have a PEP257 compliant docstring and the code is PEP8 compliant. pafy-0.5.2/GPLv3000066400000000000000000000773311275540311500133110ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS pafy-0.5.2/LICENSE000066400000000000000000000167431275540311500135000ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. pafy-0.5.2/README.rst000066400000000000000000000210111275540311500141420ustar00rootroot00000000000000.. image:: https://img.shields.io/pypi/v/Pafy.svg :target: https://pypi.python.org/pypi/pafy .. image:: https://img.shields.io/pypi/dm/Pafy.svg :target: https://pypi.python.org/pypi/pafy .. image:: https://img.shields.io/coveralls/np1/pafy/develop.svg :target: https://coveralls.io/r/np1/pafy?branch=develop .. image:: https://landscape.io/github/mps-youtube/pafy/develop/landscape.svg :target: https://landscape.io/github/mps-youtube/pafy/develop :alt: Code Health .. image:: https://travis-ci.org/mps-youtube/pafy.svg?branch=develop :target: https://travis-ci.org/mps-youtube/pafy .. image:: https://img.shields.io/pypi/wheel/Pafy.svg :target: http://pythonwheels.com/ :alt: Wheel Status Features -------- - Retreive metadata such as viewcount, duration, rating, author, thumbnail, keywords - Download video or audio at requested resolution / bitrate / format / filesize - Command line tool (ytdl) for downloading directly from the command line - Retrieve the URL to stream the video in a player such as vlc or mplayer - Works with age-restricted videos and non-embeddable videos - Small, standalone, single importable module file (pafy.py) - Select highest quality stream for download or streaming - Download video only (no audio) in m4v or webm format - Download audio only (no video) in ogg or m4a format - Retreive playlists and playlist metadata - Works with Python 2.6+ and 3.3+ - Optionally depends on youtube-dl (recommended; more stable) Documentation ------------- Full documentation is available at http://pythonhosted.org/pafy Usage Examples -------------- Here is how to use the module in your own python code. For command line tool (ytdl) instructions, see further below .. code-block:: pycon >>> import pafy create a video instance from a YouTube url: .. code-block:: pycon >>> url = "https://www.youtube.com/watch?v=bMt47wvK6u0" >>> video = pafy.new(url) get certain attributes: .. code-block:: pycon >>> video.title 'Richard Jones: Introduction to game programming - PyCon 2014' >>> video.rating 5.0 >>> video.viewcount, video.author, video.length (1916, 'PyCon 2014', 10394) >>> video.duration, video.likes, video.dislikes ('02:53:14', 25, 0) >>> print(video.description) Speaker: Richard Jones This tutorial will walk the attendees through development of a simple game using PyGame with time left over for some experimentation and exploration of different types of games. Slides can be found at: https://speakerdeck.com/pycon2014 and https://github.com/PyCon/2014-slides list available streams for a video: .. code-block:: pycon >>> streams = video.streams >>> for s in streams: ... print(s) ... normal:mp4@1280x720 normal:webm@640x360 normal:mp4@640x360 normal:flv@320x240 normal:3gp@320x240 normal:3gp@176x144 show all formats, file-sizes and their download url: .. code-block:: pycon >>> for s in streams: ... print(s.resolution, s.extension, s.get_filesize(), s.url) ... 1280x720 mp4 2421958510 https://r1---sn-aiglln7e.googlevideo.com/videoplayba[...] 640x360 webm 547015732 https://r1---sn-aiglln7e.googlevideo.com/videoplaybac[...] 640x360 mp4 470655850 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...] 320x240 flv 345455674 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...] 320x240 3gp 208603447 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...] 176x144 3gp 60905732 https://r1---sn-aiglln7e.googlevideo.com/videoplayback?[...] get best resolution regardless of file format: .. code-block:: pycon >>> best = video.getbest() >>> best.resolution, best.extension ('1280x720', 'mp4') get best resolution for a particular file format: (mp4, webm, flv or 3gp) .. code-block:: pycon >>> best = video.getbest(preftype="webm") >>> best.resolution, best.extension ('640x360', 'webm') get url, for download or streaming in mplayer / vlc etc: .. code-block:: pycon >>> best.url 'http://r12---sn-aig7kner.c.youtube.com/videoplayback?expire=1369... Download video and show progress: .. code-block:: pycon >>> best.download(quiet=False) 3,734,976 Bytes [0.20%] received. Rate: [ 719 KB/s]. ETA: [3284 secs] Download video, use specific directory and/or filename: .. code-block:: pycon >>> filename = best.download(filepath="/tmp/") >>> filename = best.download(filepath="/tmp/Game." + best.extension) Get audio-only streams (m4a and/or ogg vorbis): .. code-block:: pycon >>> audiostreams = video.audiostreams >>> for a in audiostreams: ... print(a.bitrate, a.extension, a.get_filesize()) ... 256k m4a 331379079 192k ogg 172524223 128k m4a 166863001 128k ogg 108981120 48k m4a 62700449 Download the 2nd audio stream from the above list: .. code-block:: pycon >>> audiostreams[1].download() Get the best quality audio stream: .. code-block:: pycon >>> bestaudio = video.getbestaudio() >>> bestaudio.bitrate '256' Download the best quality audio file: .. code-block:: pycon >>> bestaudio.download() show all media types for a video (video+audio, video-only and audio-only): .. code-block:: pycon >>> allstreams = video.allstreams >>> for s in allstreams: ... print(s.mediatype, s.extension, s.quality) ... normal mp4 1280x720 normal webm 640x360 normal mp4 640x360 normal flv 320x240 normal 3gp 320x240 normal 3gp 176x144 video m4v 1280x720 video webm 1280x720 video m4v 854x480 video webm 854x480 video m4v 640x360 video webm 640x360 video m4v 426x240 video webm 426x240 video m4v 256x144 video webm 256x144 audio m4a 256k audio ogg 192k audio m4a 128k audio ogg 128k audio m4a 48k Installation ------------ pafy can be installed using `pip `_: .. code-block:: bash $ [sudo] pip install pafy or use a `virtualenv `_ if you don't want to install it system-wide: .. code-block:: bash $ virtualenv venv $ source venv/bin/activate $ pip install pafy Alternatively you can just grab the pafy.py file and import it in your python code: .. code-block:: bash wget https://raw.githubusercontent.com/np1/pafy/master/pafy/pafy.py Command Line Tool (ytdl) Usage ------------------------------ .. code-block:: bash usage: ytdl [-h] [-i] [-s] [-t {audio,video,normal,all} [{audio,video,normal,all} ...]] [-n N] [-b] [-a] url YouTube Download Tool positional arguments: url YouTube video URL to download optional arguments: -h, --help show this help message and exit -i Display vid info -s Display available streams -t {audio,video,normal,all} [{audio,video,normal,all} ...] Stream types to display -n N Specify stream to download by stream number (use -s to list available streams) -b Download the best quality video (ignores -n) -a Download the best quality audio (ignores -n) ytdl Examples ------------- Download best available resolution (-b): .. code-block:: bash $ ytdl -b "http://www.youtube.com/watch?v=cyMHZVT91Dw" Download best available audio stream (-a) (note; the full url is not required, just the video id will suffice): .. code-block:: bash $ ytdl -a cyMHZVT91Dw get video info (-i): .. code-block:: bash $ ytdl -i cyMHZVT91Dw list available dowload streams: .. code-block:: bash $ ytdl cyMHZVT91Dw Stream Type Format Quality Size ------ ---- ------ ------- ---- 1 normal webm [640x360] 33 MB 2 normal mp4 [640x360] 23 MB 3 normal flv [320x240] 14 MB 4 normal 3gp [320x240] 9 MB 5 normal 3gp [176x144] 3 MB 6 audio m4a [48k] 2 MB 7 audio m4a [128k] 5 MB 8 audio ogg [128k] 5 MB 9 audio ogg [192k] 7 MB 10 audio m4a [256k] 10 MB Download mp4 640x360 (ie. stream number 2): .. code-block:: bash $ ytdl -n2 cyMHZVT91Dw Download m4a audio stream at 256k bitrate: .. code-block:: bash $ ytdl -n10 cyMHZVT91Dw IRC --- The mps-youtube irc channel (`#mps-youtube` on Freenode) can be used for discussion of pafy. pafy-0.5.2/doc/000077500000000000000000000000001275540311500132255ustar00rootroot00000000000000pafy-0.5.2/doc/Makefile000066400000000000000000000151421275540311500146700ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pafy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pafy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pafy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pafy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." pafy-0.5.2/doc/_static/000077500000000000000000000000001275540311500146535ustar00rootroot00000000000000pafy-0.5.2/doc/_static/favicon.ico000066400000000000000000000353561275540311500170100ustar00rootroot00000000000000 h6  00 %F(  @5BGE8?L9/&{;ND:0&@  XND:0%A5, !<5bXN=4*!yA u@os=p:KlbXNC9/$z4}CרyAt=K2[olaWMC9.$AF}Dx@g6NnjaWMB8.$GJG|Cv?i6E1\LHGAEkA8-#FMIF{Bu>p;j7i6h5`2OEB7-=ÏPLHEyAt=o:i6i6i6`2CKA6$ƑROKH}Dx@s=m9i6i6i6HUJ> ďN~LH}Ct=l9f6l8i6i6HIF{Bu>p;j7i6ALEyAt>o:i6( NJH~Dx@q94/*% |D!OMHC>94/*%s{z3 WRMHC>94/*:[VRMHC=94/;`[VQMHC=83/*% , e`[VQLGC=83.)%'$7AF6je`[VQLZNHHHHHHHHHFA6!  v>vzBبy@xAv?Hoje`[VQLGB=83.)${C!}DFE|CzBx@Htojd_[VQLGB=83.)${9HHGF~D|CyAIusojd_ZUQLGB=83.)$HIJIGF}D{BMuusnid_ZUPLGB=82.)$ud-KKJHGE}CuR+otuusnid_ZUPKFB=82-($8M׼LKIHF~Ep=a؃uuusnid_ZUPKFA<82-(#ÏPOMKJHGE}Dp:bF#eLIHHHHHHHGفMKFA<72-("<őQÏPNMKJHFE|CzBx@v?s=qs=p;n:l8j6i6i6h5dF$pMKFA<72*.ǓSǒRĐPOMLJIGF~D{ByAw?t>r* ̓U~ʕTǒRĐQŽONLJIGF~D|CyAw@u>s=p;n9l8i6i6H^YTOJA̖SkǓRƒRďPOMLJIGE}D{ByAw?t>rs=q;o:l8HONLJIGF~D{CyAw?u>rrm9ɐOCƐPĐPOMLJIGF~D{ByAt=ǛXĐRO˿MؾMKJHF~CتzBw?\(0` % #.6:=BEA=:3+!  3,s.,+&%#ݞ oL@. 9C<<:730-)&# `|Z>BPFC@=:730-)&#  r>K3LJGC@=9630-)&"C$ a~Y+ RPMJGC@=9630-)&"^ݞ9VTPMJGC@=9630,)iAZWTPMJFC@=963/,^G]ZWTPMIFC@=962/,II`]ZWTPMIFC@=962/,)&"Id`]ZVSPMIFC?<962/,(%"7 gd`]YVSPMIFC?<962/,(%"+-?GIII7jgd`]YVSPMI\PIIIIIIIIIIIIIIIIF;'j;+u>zBzByAw@v?t>Imjfc`]YVSOLIFC?<952/,(%" ӓL2nD%}D~E}C{BzAx@w?u>Ipmjfc`]YVSOLIFC?<852/,(%! O+ EرFE~D|C{ByAx@v?Itpmjfc`]YVSOLIFB?<852/+(%!ڟCDoHGFE}D|CzByAw@Iuspmjfc`\YVSOLIEB?<852.+(%! a~Y+ IضIHGF~E}D{CzBxAIuuspmjfc_\YVSOLHEB?<852.+(%! ӓ=KKJIGFE~D|C{BzAKsuuspmjfc_\YVSOLHEB?<852.+(%!JHmKJIHGFE~D|C{BS<Yruuusplifc_\YUROLHEB>;852.+'$! yc)LLKJIHGFE}D|C_4juuuusolifc_\YUROLHEB>;852.+'$!Ւ2LؽMLKJIHGF~E}DwAPruuuusolifc_\YUROLHEB>;851.+'$!:N㿋NLKJIHGFE~D|Ce7J`ruuuusolieb_\YUROKHEB>;841.+'$!<ŽONMLKJIHGFE~D|Ce7<{Yjruuusolieb_\YURNKHEB>;841.+'$!<ÏPONMLKJIHGFE}D|Cv?م_4QKIIIIIIIIIIIG9YLMKHEB>;841.+'$<ŐQÎPONMLKJIHGF~E}C{BzAx@w?u>t=r;841-*'"9ŏPĐQŽPONLKJIHGFE~D|C{ByAx@v?u>s=r;841-*%1ƑQőQďPŽONMLKJIHGFE~D|C{ByAw@v?t>s=q;741-%)ǑQǒRŐQÏPONMLKJIHGFE}D|CzByAw@v?t>s=qt=rs=rs=qs=qt=rs=rs=qs=qt=rs=rs=qt=rs=rs=qs=l8ǐRƑRĐQǕ[ܿƧXLKJIHGF~E}C{BzAx@w?u>r<^3F ǛXŒPƑQĐPŽONMLKJIHGFE~D|C{ByAx@t>j7e ǛXőQďOÏPONMLKJIHGFE}D|CzBw?؝n v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = "favicon.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pafydoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'pafy.tex', u'pafy Documentation', u'np1', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pafy', u'pafy Documentation', [u'np1'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pafy', u'pafy Documentation', u'np1', 'pafy', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False pafy-0.5.2/doc/index.rst000066400000000000000000000417751275540311500151040ustar00rootroot00000000000000Pafy Documentation ****************** .. module:: Pafy This is the documentation for pafy - a Python library to download YouTube content and retrieve metadata A quick start intro with usage examples is available in the `README `_ Development / Source code / Bug reporting: `github.com/np1/pafy `_ Homepage: `np1.github.io/pafy `_ API Keys ======== Specifying an API key is optional, as pafy includes one. However, it is prefered that software calling pafy provides it's own API key, and the default may be removed in the future. `Information from Google about obtaining an API key `_ .. function:: pafy.set_api_key(key) "Sets the API key for pafy to use." :param key: API key to use Pafy Objects and Stream Objects =============================== Pafy objects relate to videos hosted on YouTube. They hold metadata such as *title*, *viewcount*, *author* and *video ID* Stream objects relate to individual streams of a YouTube video. They hold stream-specific data such as *resolution*, *bitrate* and *url*. Each Pafy object contains multiple stream objects. Pafy Objects ============ Create a Pafy object using the :func:`pafy.new` function, giving a YouTube video URL as the argument. .. function:: pafy.new(video_url[, basic=True][, gdata=False][, signature=True][, size=False][, callback=None]) Creates a new Pafy object. All optional arguments (apart from callback) are used to specify which data items are fetched on initialisation. :param url: The YouTube url or 11 character video id of the video :type url: str :param basic: fetch basic metadata and streams :type basic: bool :param gdata: fetch gdata info (upload date, description, category, username, likes, dislikes) :type gdata: bool :param signature: Note: The signature argument now has no effect and will be removed in a future version :type signature: bool :param size: fetch the size of each stream (slow)(decrypts urls if needed) :type size: bool :param callback: a callback function to receive status strings :type callback: function :rtype: :class:`pafy.Pafy` If any of **basic**, **gdata** or **size** are *False*, those data items will be fetched only when first called for. The defaults are recommended for most cases. If you wish to create many video objects at once, you may want to set all to *False*, eg:: vid = pafy.new(basic=False) This will be quick because no http requests will be made on initialisation. Setting **size** to *True* will override the **basic** argument and force basic data to be fetched too (basic data is required to obtain Stream objects) Example:: import pafy myvid = pafy.new("http://www.youtube.com/watch?v=dQw4w9WgXc") Pafy Attributes --------------- Once you have created a Pafy object using :func:`pafy.new`, several data attributes are available .. attribute:: Pafy.author The author of the video (*str*) .. attribute:: Pafy.bigthumb (*str*) The url of the video's display image (not always available) .. attribute:: Pafy.bigthumbhd The url of the video's larger display image (not always available) (*str*) .. attribute:: Pafy.category The category of the video (*str*) .. attribute:: Pafy.description The video description text (*str*) .. attribute:: Pafy.dislikes The number of dislikes received for the video (*int*) .. attribute:: Pafy.duration The duration of the stream (*string formatted as HH:MM:SS*) .. attribute:: Pafy.keywords A list of the video's keywords (not always available) (*[str]*) .. attribute:: Pafy.length The duration of the streams in seconds (*int*) .. attribute:: Pafy.likes The number of likes received for the video (*int*) .. attribute:: Pafy.published The upload date of the video (e.g., 2012-10-02 17:17:24) (*str*) .. attribute:: Pafy.mix The mix playlist provided by youtube for this video (*dict*) .. attribute:: Pafy.rating The rating of the video (0-5), (*float*) .. attribute:: Pafy.thumb The url of the video's thumbnail image (*str*) .. attribute:: Pafy.title The title of the video (*str*) .. attribute:: Pafy.username The username of the uploader (*str*) .. attribute:: Pafy.videoid The 11-character video id (*str*) .. attribute:: Pafy.viewcount The viewcount of the video (*int*) An example of accessing this video metadata is shown below:: import pafy v = pafy.new("dQw4w9WgXcQ") print(v.title) print(v.duration) print(v.rating) print(v.author) print(v.length) print(v.keywords) print(v.thumb) print(v.videoid) print(v.viewcount) Which will result in this output:: Rick Astley - Never Gonna Give You Up 00:03:33 4.75177729422 RickAstleyVEVO 213 ['Rick', 'Astley', 'Sony', 'BMG', 'Music', 'UK', 'Pop'] https://i1.ytimg.com/vi/dQw4w9WgXcQ/default.jpg dQw4w9WgXcQ 69788014 Pafy Methods ------------ The :func:`Pafy.getbest`, :func:`Pafy.getbestaudio` and :func:`Pafy.getbestvideo` methods are a quick way to access the highest quality streams for a particular video without needing to query the stream lists. .. function:: Pafy.getbest([preftype="any"][, ftypestrict=True]) Selects the stream with the highest resolution. This will return a "normal" stream (ie. one with video and audio) :param preftype: Preferred type, set to *mp4*, *webm*, *flv*, *3gp* or *any* :type preftype: str :param ftypestrict: Set to *False* to return a type other than that specified in preftype if it has a higher resolution :type ftypestrict: boolean :rtype: :class:`pafy.Stream` .. function:: Pafy.getbestaudio([preftype="any"][, ftypestrict=True]) Selects the audio stream with the highest bitrate. :param preftype: Preferred type, set to *ogg* or *m4a* or *any* :type preftype: str :param ftypestrict: Set to *False* to return a type other than that specified in preftype if that has the highest bitrate :type ftypestrict: boolean :rtype: :class:`pafy.Stream` .. function:: Pafy.getbestvideo([preftype="any"][, ftypestrict=True]) Selects the video-only stream with the highest resolution. This will return a "video" stream (ie. one with no audio) :param preftype: Preferred type, set to *m4v*, *webm* or *any* :type preftype: str :param ftypestrict: Set to *False* to return a type other than that specified in preftype if it has a higher resolution :type ftypestrict: boolean :rtype: :class:`pafy.Stream` Stream Lists ------------ A Pafy object provides multiple stream lists. These are: .. attribute:: Pafy.streams A list of regular streams (streams containing both audio and video) .. attribute:: Pafy.audiostreams A list of audio-only streams; aac streams (.m4a) and ogg vorbis streams (.ogg) if available .. attribute:: Pafy.videostreams A list of video-only streams (Note: these streams have no audio data) .. attribute:: Pafy.oggstreams A list of ogg vorbis encoded audio streams (Note: may be empty for some videos) .. attribute:: Pafy.m4astreams A list of aac encoded audio streams .. attribute:: Pafy.allstreams A list of all available streams An example of accessing stream lists:: >>> import pafy >>> v = pafy.new("cyMHZVT91Dw") >>> v.audiostreams [audio:m4a@48k, audio:m4a@128k, audio:m4a@256k] >>> v.streams [normal:webm@640x360, normal:mp4@640x360, normal:flv@320x240, normal:3gp@320x240, normal:3gp@176x144] >>> v.allstreams [normal:webm@640x360, normal:mp4@640x360, normal:flv@320x240, normal:3gp@320x240, normal:3gp@176x144, video:m4v@854x480, video:m4v@640x360, video:m4v@426x240, video:m4v@256x144, audio:m4a@48k, audio:m4a@128k, audio:m4a@256k] Stream Objects ============== .. class:: pafy.Stream After you have created a :class:`Pafy` object using :func:`new`, you can then access the streams using one of the `Stream Lists`_, or by calling :func:`Pafy.getbest` or :func:`Pafy.getbestaudio` on the object. Stream Attributes ----------------- A Stream object can be used to access the following attributes .. attribute:: Stream.url The direct access URL of the stream. This can be used to stream the media in mplayer or vlc, or for downloading with wget or curl. To download directly, use the :func:`Stream.download` method. .. attribute:: Stream.url_https The direct access HTTPS URL of the stream. .. attribute:: Stream.bitrate The bitrate of the stream - if it is an audio stream, otherwise None, This is a string of the form *"192k"*. .. attribute:: Stream.dimensions A 2-tuple (x, y) representing the resolution of a video stream. .. attribute:: Stream.extension The format of the stream, will be one of: ``'ogg'``, ``'m4a'``, ``'mp4'``, ``'flv'``, ``'webm'``, ``'3gp'`` .. attribute:: Stream.mediatype A string attribute that is ``'normal'``, ``'audio'`` or ``'video'``, depending on the content of the stream .. attribute:: Stream.quality The resolution or the bitrate of the stream, depending on whether the stream is video or audio respectively .. attribute:: Stream.resolution The resolution of a video as a string, eg: "820x640". Note if the stream is 3D this will be appended; eg: "820x640-3D". For audio streams, this will be set to "0x0" .. attribute:: Stream.rawbitrate The bitrate of an audio stream, *int* For video streams, this will be set to *None* .. attribute:: Stream.threed True if the stream is a 3D video (*boolean*) .. attribute:: Stream.title The title of the video, this will be the same as :attr:`Pafy.title` .. attribute:: Stream.notes Any additional notes regarding the stream (eg, 6-channel surround) *str* An example of accessing Stream attributes:: >>> import pafy >>> v = pafy.new("cyMHZVT91Dw") >>> v.audiostreams [audio:m4a@48k, audio:m4a@128k, audio:m4a@256k] >>> mystream = v.audiostreams[2] >>> mystream.rawbitrate 255940 >>> mystream.bitrate '256k' >>> mystream.url 'http://r20---sn-aigllnes.c.youtube.com/videoplayback?ipbits=8&clen=1130... Stream Methods -------------- .. function:: Stream.get_filesize() Returns the filesize of a stream .. function:: Stream.download([filepath=""][, quiet=False][, callback=None][, meta=False][, remux_audio=False]) Downloads the stream object, returns the path of the downloaded file. :param filepath: The filepath to use to save the stream, defaults to (sanitised) *title.extension* if ommitted :type filepath: string :param quiet: If True, supress output of the download progress :type quiet: boolean :param callback: Call back function to use for receiving download progress :type callback: function or None :param meta: If True, video id and itag are appended to filename :type meta: bool :param remux_audio: If True, remux audio file downloads (fixes some compatibility issues with file format, requires ffmpeg/avconv) :type remux_audio: bool :rtype: str If a callback function is provided, it will be called repeatedly for each chunk downloaded. It must be a function that takes the following five arguments; - total bytes in stream, *int* - total bytes downloaded, *int* - ratio downloaded (0-1), *float* - download rate (kbps), *float* - ETA in seconds, *float* :func:`Stream.download` example ------------------------------- Example of using stream.download():: import pafy v = pafy.new("cyMHZVT91Dw") s = v.getbest() print("Size is %s" % s.get_filesize()) filename = s.download() # starts download Will download to the current working directory and output the following progress statistics:: Size is 34775366 1,015,808 Bytes [2.92%] received. Rate: [ 640 kbps]. ETA: [51 secs] Download using *callback* example:: import pafy # callback function, this callback simply prints the bytes received, # ratio downloaded and eta. def mycb(total, recvd, ratio, rate, eta): print(recvd, ratio, eta) p = pafy.new("cyMHZVT91Dw") ba = p.getbestaudio() filename = ba.download(quiet=True, callback=mycb) The output of this will appear as follows, while the file is downloading:: (16384, 0.001449549245392125, 20.05230682669207) (32768, 0.00289909849078425, 16.88200659636641) (49152, 0.004348647736176375, 15.196503182407469) (65536, 0.0057981969815685, 14.946467230009146) (81920, 0.007247746226960625, 15.066431667096913) (98304, 0.00869729547235275, 14.978577915171627) (114688, 0.010146844717744874, 14.529802172976945) (131072, 0.011596393963137, 14.31917945870373) ... Playlist Retrieval ================== The :func:`pafy.get_playlist` function is initialised with similar arguments to :func:`pafy.new` and will return a dict containing metadata and :class:`Pafy` objects as listed in the YouTube playlist. .. function:: pafy.get_playlist(playlist_url[, basic=False][, gdata=False][, signature=False][, size=False][, callback=None]) :param playlist_url: The YouTube playlist url :type playlist_url: str :param basic: fetch basic metadata and streams :type basic: bool :param gdata: fetch gdata info (upload date, description, category, username, likes, dislikes) :type gdata: bool :param signature: fetch data required to decrypt urls, if encrypted :type signature: bool :param size: fetch the size of each stream (slow)(decrypts urls if needed) :type size: bool :param callback: a callback function to receive status strings :type callback: function :rtype: dict The returned dict contains the following keys: **playlist_id**: the id of the playlist **likes**: the number of likes for the playlist **dislikes**: the number of dislikes for the playlist **title**: the title of the playlist **author**: the author of the playlist **description**: the description of the playlist **items**: a list of dicts with each dict representing a video and containing the following keys: **pafy**: The :class:`Pafy` object for this video, initialised with the arguments given to :func:`pafy.get_playlist` **playlist_meta**: a dict of various video-specific metadata fetched from the playlist data, including: **added**, **likes**, **dislikes**, **thumbnail**, **is_cc**, **is_hd**, **user_id**, **cc_license**, **privacy**, **category_id** :func:`pafy.get_playlist` example --------------------------------- >>> import pafy >>> plurl = "https://www.youtube.com/playlist?list=PL634F2B56B8C346A2" >>> playlist = pafy.get_playlist(plurl) >>> >>> playlist['title'] u'Rick Astley playlist' >>> >>> playlist['author'] u'Deborah Back' >>> >>> len(playlist['items']) 43 >>> >>> playlist['items'][21]['pafy'] Title: Body and Soul - Rick astley Author: jadiafa ID: QtHnEJ8UArY Duration: 00:04:11 Rating: 5.0 Views: 18855 Thumbnail: http://i1.ytimg.com/vi/QtHnEJ8UArY/default.jpg Keywords: Rick, astely, body, and, soul, pop >>> >>> playlist['items'][21]['pafy'].audiostreams [audio:m4a@128k] >>> >>> playlist['items'][21]['pafy'].getbest() normal:webm@640x360 >>> >>> playlist['items'][21]['pafy'].getbest().url u'http://r4---sn-4g57knzr.googlevideo.com/videoplayback?ipbits=0&ratebypas...' The :func:`pafy.get_playlist2` serves the same purpose as the :func:`pafy.get_playlist`, but uses version 3 of youtube's api, making it able to retrieve playlists of over 200 items. It also provides a different interface, returning a :class:`pafy.Playlist` instead of a dictionary. .. function:: pafy.get_playlist2(playlist_url[, basic=False][, gdata=False][, signature=False][, size=False][, callback=None]) :param playlist_url: The YouTube playlist url :type playlist_url: str :param basic: fetch basic metadata and streams :type basic: bool :param gdata: fetch gdata info (upload date, description, category, username, likes, dislikes) :type gdata: bool :param signature: fetch data required to decrypt urls, if encrypted :type signature: bool :param size: fetch the size of each stream (slow)(decrypts urls if needed) :type size: bool :param callback: a callback function to receive status strings :type callback: function :rtype: :class:`pafy.Playlist` Playlist Attributes ------------------- Once you have retrieved a playlist with :func:`pafy.get_playlist2` you can iterate over it to get the Pafy objects for the items in it, or use `len(playlist)` to get its length. In addition, you can access the following attributes: .. attribute:: Pafy.plid The ID of the playlist (*str*) .. attribute:: Pafy.title The title of the playlist (*str*) .. attribute:: Pafy.author The author of the playlist (*str*) .. attribute:: Pafy.description The description of the playlist (*str*) pafy-0.5.2/pafy/000077500000000000000000000000001275540311500134175ustar00rootroot00000000000000pafy-0.5.2/pafy/__init__.py000066400000000000000000000006071275540311500155330ustar00rootroot00000000000000import sys __version__ = "0.5.2" __author__ = "np1" __license__ = "LGPLv3" # External api from .pafy import new from .pafy import set_api_key from .pafy import load_cache, dump_cache from .pafy import get_categoryname from .pafy import backend from .util import GdataError, call_gdata from .playlist import get_playlist, get_playlist2 if "test" not in sys.argv[0]: del pafy del sys pafy-0.5.2/pafy/backend_internal.py000066400000000000000000000363511275540311500172640ustar00rootroot00000000000000import os import hashlib import tempfile import json import re import sys import time import logging from xml.etree import ElementTree if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.parse import parse_qs, unquote_plus uni, pyver = str, 3 else: from urllib import unquote_plus from urlparse import parse_qs uni, pyver = unicode, 2 early_py_version = sys.version_info[:2] < (2, 7) from . import g from .pafy import fetch_decode, dbg, get_categoryname from .backend_shared import BasePafy, BaseStream from .jsinterp import JSInterpreter funcmap = {} class InternPafy(BasePafy): def __init__(self, *args, **kwargs): self.sm = [] self.asm = [] self.dash = [] self.js_url = None # if js_url is set then has new stream map self._dashurl = None self.age_ver = False self._formats = None self.ciphertag = None # used by Stream class in url property def super(InternPafy, self).__init__(*args, **kwargs) def _fetch_basic(self): """ Fetch basic data and streams. """ if self._have_basic: return allinfo = get_video_info(self.videoid, self.callback) self.callback("Fetched video info") def _get_lst(key, default="unknown", dic=allinfo): """ Dict get function, returns first index. """ retval = dic.get(key, default) return retval[0] if retval != default else default self._title = _get_lst('title') self._dashurl = _get_lst('dashmpd') self._author = _get_lst('author') self._rating = float(_get_lst('avg_rating', 0.0)) self._length = int(_get_lst('length_seconds', 0)) self._viewcount = int(_get_lst('view_count'), 0) self._thumb = unquote_plus(_get_lst('thumbnail_url', "")) self._formats = [x.split("/") for x in _get_lst('fmt_list').split(",")] self._keywords = _get_lst('keywords', "").split(',') self._bigthumb = _get_lst('iurlsd', "") self._bigthumbhd = _get_lst('iurlsdmaxres', "") self.ciphertag = _get_lst("use_cipher_signature") == "True" self.sm = _extract_smap(g.UEFSM, allinfo, True) self.asm = _extract_smap(g.AF, allinfo, True) dbg("extracted stream maps") sm_ciphertag = "s" in self.sm[0] if self.ciphertag != sm_ciphertag: dbg("ciphertag mismatch") self.ciphertag = not self.ciphertag watch_url = g.urls['watchv'] % self.videoid self.callback("Fetching watch page") watchinfo = fetch_decode(watch_url) # unicode dbg("Fetched watch page") self.callback("Fetched watch page") self.age_ver = re.search(r'player-age-gate-content">', watchinfo) is not None if self.ciphertag: dbg("Encrypted signature detected.") if not self.age_ver: smaps, js_url, mainfunc = get_js_sm(watchinfo, self.callback) funcmap[js_url] = mainfunc self.sm, self.asm = smaps self.js_url = js_url dashsig = re.search(r"/s/([\w\.]+)", self._dashurl).group(1) dbg("decrypting dash sig") goodsig = _decodesig(dashsig, js_url, self.callback) self._dashurl = re.sub(r"/s/[\w\.]+", "/signature/%s" % goodsig, self._dashurl) else: s = re.search(r"/s/([\w\.]+)", self._dashurl).group(1) s = s[2:63] + s[82] + s[64:82] + s[63] self._dashurl = re.sub(r"/s/[\w\.]+", "/signature/%s" % s, self._dashurl) if self._dashurl != 'unknown': self.dash = _extract_dash(self._dashurl) self._have_basic = 1 self._process_streams() self.expiry = time.time() + g.lifespan def _fetch_gdata(self): """ Extract gdata values, fetch gdata if necessary. """ if self._have_gdata: return item = self._get_video_gdata(self.videoid)['items'][0] snippet = item['snippet'] self._published = uni(snippet['publishedAt']) self._description = uni(snippet["description"]) self._category = get_categoryname(snippet['categoryId']) # TODO: Make sure actual usename is not available through the api self._username = uni(snippet['channelTitle']) statistics = item["statistics"] self._likes = int(statistics["likeCount"]) self._dislikes = int(statistics["dislikeCount"]) self._have_gdata = 1 def _process_streams(self): """ Create Stream object lists from internal stream maps. """ if not self._have_basic: self._fetch_basic() streams = [InternStream(z, self) for z in self.sm] streams = [x for x in streams if x.itag in g.itags] adpt_streams = [InternStream(z, self) for z in self.asm] adpt_streams = [x for x in adpt_streams if x.itag in g.itags] dash_streams = [InternStream(z, self) for z in self.dash] dash_streams = [x for x in dash_streams if x.itag in g.itags] audiostreams = [x for x in adpt_streams if x.bitrate] videostreams = [x for x in adpt_streams if not x.bitrate] dash_itags = [x.itag for x in dash_streams] audiostreams = [x for x in audiostreams if x.itag not in dash_itags] videostreams = [x for x in videostreams if x.itag not in dash_itags] audiostreams += [x for x in dash_streams if x.mediatype == "audio"] videostreams += [x for x in dash_streams if x.mediatype != "audio"] audiostreams = sorted(audiostreams, key=lambda x: x.rawbitrate, reverse=True) videostreams = sorted(videostreams, key=lambda x: x.dimensions, reverse=True) m4astreams = [x for x in audiostreams if x.extension == "m4a"] oggstreams = [x for x in audiostreams if x.extension == "ogg"] self._streams = streams self._audiostreams = audiostreams self._videostreams = videostreams self._m4astreams, self._oggstreams = m4astreams, oggstreams self._allstreams = streams + videostreams + audiostreams class InternStream(BaseStream): def __init__(self, sm, parent): super(InternStream, self).__init__(parent) self._itag = sm['itag'] # is_dash = "width" in sm and "height" in sm is_dash = "dash" in sm if self._itag not in g.itags: logging.warning("Unknown itag: %s", self._itag) return self._mediatype = g.itags[self.itag][2] self._threed = 'stereo3d' in sm and sm['stereo3d'] == '1' if is_dash: if sm['width'] != "None": # dash video self._resolution = "%sx%s" % (sm['width'], sm['height']) self._quality = self._resolution self._dimensions = (int(sm['width']), int(sm['height'])) else: # dash audio self._resolution = "0x0" self._dimensions = (0, 0) self._rawbitrate = int(sm['bitrate']) # self._bitrate = uni(int(sm['bitrate']) // 1024) + "k" self._bitrate = g.itags[self.itag][0] self._quality = self._bitrate self._fsize = int(sm['size'] or 0) # self._bitrate = sm['bitrate'] # self._rawbitrate = uni(int(self._bitrate) // 1024) + "k" else: # not dash self._resolution = g.itags[self.itag][0] self._dimensions = tuple(self.resolution.split("-")[0].split("x")) self._dimensions = tuple([int(x) if x.isdigit() else x for x in self._dimensions]) self._quality = self.resolution self._extension = g.itags[self.itag][1] self._title = parent.title self.encrypted = 's' in sm self._parent = parent self._filename = self.generate_filename() self._notes = g.itags[self.itag][3] self._rawurl = sm['url'] self._sig = sm['s'] if self.encrypted else sm.get("sig") self._active = False if self.mediatype == "audio" and not is_dash: self._dimensions = (0, 0) self._bitrate = self.resolution self._quality = self.bitrate self._resolution = "0x0" self._rawbitrate = int(sm["bitrate"]) @property def url(self): """ Return the url, decrypt if required. """ if not self._url: if self._parent.age_ver: if self._sig: s = self._sig self._sig = s[2:63] + s[82] + s[64:82] + s[63] elif self.encrypted: self._sig = _decodesig(self._sig, self._parent.js_url, self._parent.callback) self._url = _make_url(self._rawurl, self._sig) return self._url def parseqs(data): """ parse_qs, return unicode. """ if type(data) == uni: return parse_qs(data) elif pyver == 3: data = data.decode("utf8") data = parse_qs(data) else: data = parse_qs(data) out = {} for k, v in data.items(): k = k.decode("utf8") out[k] = [x.decode("utf8") for x in v] data = out return data def get_video_info(video_id, callback, newurl=None): """ Return info for video_id. Returns dict. """ # TODO: see if there is a way to avoid retrieving the embed page # just for this, or to use it for more. This was coppied from # youtube-dl. embed_webpage = fetch_decode(g.urls['embed']) sts = re.search(r'sts"\s*:\s*(\d+)', embed_webpage).group(1) url = g.urls['vidinfo'] % (video_id, video_id, sts) url = newurl if newurl else url info = fetch_decode(url) # bytes info = parseqs(info) # unicode dict dbg("Fetched video info%s", " (age ver)" if newurl else "") if info['status'][0] == "fail": reason = info['reason'][0] or "Bad video argument" raise IOError("Youtube says: %s [%s]" % (reason, video_id)) return info def _extract_smap(map_name, dic, zero_idx=True): """ Extract stream map, returns list of dicts. """ if map_name in dic: smap = dic.get(map_name) smap = smap[0] if zero_idx else smap smap = smap.split(",") smap = [parseqs(x) for x in smap] return [dict((k, v[0]) for k, v in x.items()) for x in smap] return [] def _extract_dash(dashurl): """ Download dash url and extract some data. """ # pylint: disable = R0914 dbg("Fetching dash page") dashdata = fetch_decode(dashurl) dbg("DASH list fetched") ns = "{urn:mpeg:DASH:schema:MPD:2011}" ytns = "{http://youtube.com/yt/2012/10/10}" tree = ElementTree.fromstring(dashdata) tlist = tree.findall(".//%sRepresentation" % ns) dashmap = [] for x in tlist: baseurl = x.find("%sBaseURL" % ns) url = baseurl.text size = baseurl.get("%scontentLength" % ytns) bitrate = x.get("bandwidth") itag = uni(x.get("id")) width = uni(x.get("width")) height = uni(x.get("height")) dashmap.append(dict(bitrate=bitrate, dash=True, itag=itag, width=width, height=height, url=url, size=size)) return dashmap def _get_mainfunc_from_js(js): """ Return main signature decryption function from javascript as dict. """ dbg("Scanning js for main function.") m = re.search(r'\.sig\|\|([a-zA-Z0-9$]+)\(', js) funcname = m.group(1) dbg("Found main function: %s", funcname) jsi = JSInterpreter(js) return jsi.extract_function(funcname) def _decodesig(sig, js_url, callback): """ Return decrypted sig given an encrypted sig and js_url key. """ # lookup main function in funcmap dict mainfunction = funcmap[js_url] # fill in function argument with signature callback("Decrypting signature") solved = mainfunction([sig]) dbg("Decrypted sig = %s...", solved[:30]) callback("Decrypted signature") return solved def fetch_cached(url, callback, encoding=None, dbg_ref="", file_prefix=""): """ Fetch url - from tmpdir if already retrieved. """ tmpdir = os.path.join(tempfile.gettempdir(), "pafy") if not os.path.exists(tmpdir): os.makedirs(tmpdir) url_md5 = hashlib.md5(url.encode("utf8")).hexdigest() cached_filename = os.path.join(tmpdir, file_prefix + url_md5) if os.path.exists(cached_filename): dbg("fetched %s from cache", dbg_ref) with open(cached_filename) as f: retval = f.read() return retval else: data = fetch_decode(url, "utf8") # unicode dbg("Fetched %s", dbg_ref) callback("Fetched %s" % dbg_ref) with open(cached_filename, "w") as f: f.write(data) # prune files after write prune_files(tmpdir, file_prefix) return data def prune_files(path, prefix="", age_max=3600 * 24 * 14, count_max=4): """ Remove oldest files from path that start with prefix. remove files older than age_max, leave maximum of count_max files. """ tempfiles = [] if not os.path.isdir(path): return for f in os.listdir(path): filepath = os.path.join(path, f) if os.path.isfile(filepath) and f.startswith(prefix): age = time.time() - os.path.getmtime(filepath) if age > age_max: os.unlink(filepath) else: tempfiles.append((filepath, age)) tempfiles = sorted(tempfiles, key=lambda x: x[1], reverse=True) for f in tempfiles[:-count_max]: os.unlink(f[0]) def get_js_sm(watchinfo, callback): """ Fetch watchinfo page and extract stream map and js funcs if not known. This function is needed by videos with encrypted signatures. If the js url referred to in the watchv page is not a key in funcmap, the javascript is fetched and functions extracted. Returns streammap (list of dicts), js url (str) and funcs (dict) """ m = re.search(g.jsplayer, watchinfo) myjson = json.loads(m.group(1)) stream_info = myjson['args'] sm = _extract_smap(g.UEFSM, stream_info, False) asm = _extract_smap(g.AF, stream_info, False) js_url = myjson['assets']['js'] js_url = "https:" + js_url if js_url.startswith("//") else js_url mainfunc = funcmap.get(js_url) if not mainfunc: dbg("Fetching javascript") callback("Fetching javascript") javascript = fetch_cached(js_url, callback, encoding="utf8", dbg_ref="javascript", file_prefix="js-") mainfunc = _get_mainfunc_from_js(javascript) elif mainfunc: dbg("Using functions in memory extracted from %s", js_url) dbg("Mem contains %s js func sets", len(funcmap)) return (sm, asm), js_url, mainfunc def _make_url(raw, sig, quick=True): """ Return usable url. Set quick=False to disable ratebypass override. """ if quick and "ratebypass=" not in raw: raw += "&ratebypass=yes" if "signature=" not in raw: if sig is None: raise IOError("Error retrieving url") raw += "&signature=" + sig return raw pafy-0.5.2/pafy/backend_shared.py000066400000000000000000000467241275540311500167230ustar00rootroot00000000000000import os import re import sys import time import logging import subprocess if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.request import build_opener from urllib.error import HTTPError, URLError from urllib.parse import parse_qs, urlparse uni, pyver = str, 3 else: from urllib2 import build_opener, HTTPError, URLError from urlparse import parse_qs, urlparse uni, pyver = unicode, 2 early_py_version = sys.version_info[:2] < (2, 7) from . import __version__, g from .pafy import call_gdata from .playlist import get_playlist2 dbg = logging.debug def extract_video_id(url): """ Extract the video id from a url, return video id as str. """ idregx = re.compile(r'[\w-]{11}$') url = str(url) if idregx.match(url): return url # ID of video if '://' not in url: url = '//' + url parsedurl = urlparse(url) if parsedurl.netloc in ('youtube.com', 'www.youtube.com'): query = parse_qs(parsedurl.query) if 'v' in query and idregx.match(query['v'][0]): return query['v'][0] elif parsedurl.netloc in ('youtu.be', 'www.youtu.be'): vidid = parsedurl.path.split('/')[-1] if parsedurl.path else '' if idregx.match(vidid): return vidid err = "Need 11 character video id or the URL of the video. Got %s" raise ValueError(err % url) class BasePafy(object): """ Class to represent a YouTube video. """ def __init__(self, video_url, basic=True, gdata=False, size=False, callback=None, ydl_opts=None): """ Set initial values. """ self.version = __version__ self.videoid = extract_video_id(video_url) self.watchv_url = g.urls['watchv'] % self.videoid self.callback = callback or (lambda x: None) self._have_basic = False self._have_gdata = False self._description = None self._likes = None self._dislikes = None self._category = None self._published = None self._username = None self._streams = [] self._oggstreams = [] self._m4astreams = [] self._allstreams = [] self._videostreams = [] self._audiostreams = [] self._title = None self._rating = None self._length = None self._author = None self._duration = None self._keywords = None self._bigthumb = None self._viewcount = None self._bigthumbhd = None self._mix_pl = None self.expiry = None if basic: self._fetch_basic() if gdata: self._fetch_gdata() if size: for s in self.allstreams: # pylint: disable=W0104 s.get_filesize() def _fetch_basic(self): """ Fetch basic data and streams. """ raise NotImplementedError def _fetch_gdata(self): """ Extract gdata values, fetch gdata if necessary. """ raise NotImplementedError def _get_video_gdata(self, video_id): """ Return json string containing video metadata from gdata api. """ self.callback("Fetching video gdata") query = {'part': 'id,snippet,statistics', 'maxResults': 1, 'id': video_id} gdata = call_gdata('videos', query) dbg("Fetched video gdata") self.callback("Fetched video gdata") return gdata def _process_streams(self): """ Create Stream object lists from internal stream maps. """ raise NotImplementedError def __repr__(self): """ Print video metadata. Return utf8 string. """ if self._have_basic: keys = "Title Author ID Duration Rating Views Thumbnail" keys = keys.split(" ") keywords = ", ".join(self.keywords) info = {"Title": self.title, "Author": self.author, "Views": self.viewcount, "Rating": self.rating, "Duration": self.duration, "ID": self.videoid, "Thumbnail": self.thumb} nfo = "\n".join(["%s: %s" % (k, info.get(k, "")) for k in keys]) else: nfo = "Pafy object: %s [%s]" % (self.videoid, self.title[:45] + "..") return nfo.encode("utf8", "replace") if pyver == 2 else nfo @property def streams(self): """ The streams for a video. Returns list.""" if not self._streams: self._process_streams() return self._streams @property def allstreams(self): """ All stream types for a video. Returns list. """ if not self._allstreams: self._process_streams() return self._allstreams @property def audiostreams(self): """ Return a list of audio Stream objects. """ if not self._audiostreams: self._process_streams() return self._audiostreams @property def videostreams(self): """ The video streams for a video. Returns list. """ if not self._videostreams: self._process_streams() return self._videostreams @property def oggstreams(self): """ Return a list of ogg encoded Stream objects. """ if not self._oggstreams: self._process_streams() return self._oggstreams @property def m4astreams(self): """ Return a list of m4a encoded Stream objects. """ if not self._m4astreams: self._process_streams() return self._m4astreams @property def title(self): """ Return YouTube video title as a string. """ if not self._title: self._fetch_basic() return self._title @property def author(self): """ The uploader of the video. Returns str. """ if not self._author: self._fetch_basic() return self._author @property def rating(self): """ Rating for a video. Returns float. """ if not self._rating: self._fetch_basic() return self._rating @property def length(self): """ Length of a video in seconds. Returns int. """ if not self._length: self._fetch_basic() return self._length @property def viewcount(self): """ Number of views for a video. Returns int. """ if not self._viewcount: self._fetch_basic() return self._viewcount @property def bigthumb(self): """ Large thumbnail image url. Returns str. """ self._fetch_basic() return self._bigthumb @property def bigthumbhd(self): """ Extra large thumbnail image url. Returns str. """ self._fetch_basic() return self._bigthumbhd @property def thumb(self): """ Thumbnail image url. Returns str. """ return g.urls['thumb'] % self.videoid @property def duration(self): """ Duration of a video (HH:MM:SS). Returns str. """ if not self._length: self._fetch_basic() self._duration = time.strftime('%H:%M:%S', time.gmtime(self._length)) self._duration = uni(self._duration) return self._duration @property def keywords(self): """ Return keywords as list of str. """ if not self._keywords: self._fetch_gdata() return self._keywords @property def category(self): """ YouTube category of the video. Returns string. """ if not self._category: self._fetch_gdata() return self._category @property def description(self): """ Description of the video. Returns string. """ if not self._description: self._fetch_gdata() return self._description @property def username(self): """ Return the username of the uploader. """ if not self._username: self._fetch_basic() return self._username @property def published(self): """ The upload date and time of the video. Returns string. """ if not self._published: self._fetch_gdata() return self._published.replace(".000Z", "").replace("T", " ") @property def likes(self): """ The number of likes for the video. Returns int. """ if not self._likes: self._fetch_basic() return self._likes @property def dislikes(self): """ The number of dislikes for the video. Returns int. """ if not self._dislikes: self._fetch_basic() return self._dislikes @property def mix(self): """ The playlist for the related YouTube mix. Returns a Playlist object. """ if self._mix_pl is None: try: self._mix_pl = get_playlist2("RD" + self.videoid) except IOError: return None return self._mix_pl def _getbest(self, preftype="any", ftypestrict=True, vidonly=False): """ Return the highest resolution video available. Select from video-only streams if vidonly is True """ streams = self.videostreams if vidonly else self.streams if not streams: return None def _sortkey(x, key3d=0, keyres=0, keyftype=0): """ sort function for max(). """ key3d = "3D" not in x.resolution keyres = int(x.resolution.split("x")[0]) keyftype = preftype == x.extension strict = (key3d, keyftype, keyres) nonstrict = (key3d, keyres, keyftype) return strict if ftypestrict else nonstrict r = max(streams, key=_sortkey) if ftypestrict and preftype != "any" and r.extension != preftype: return None else: return r def getbestvideo(self, preftype="any", ftypestrict=True): """ Return the best resolution video-only stream. set ftypestrict to False to return a non-preferred format if that has a higher resolution """ return self._getbest(preftype, ftypestrict, vidonly=True) def getbest(self, preftype="any", ftypestrict=True): """ Return the highest resolution video+audio stream. set ftypestrict to False to return a non-preferred format if that has a higher resolution """ return self._getbest(preftype, ftypestrict, vidonly=False) def getbestaudio(self, preftype="any", ftypestrict=True): """ Return the highest bitrate audio Stream object.""" if not self.audiostreams: return None def _sortkey(x, keybitrate=0, keyftype=0): """ Sort function for max(). """ keybitrate = int(x.rawbitrate) keyftype = preftype == x.extension strict, nonstrict = (keyftype, keybitrate), (keybitrate, keyftype) return strict if ftypestrict else nonstrict r = max(self.audiostreams, key=_sortkey) if ftypestrict and preftype != "any" and r.extension != preftype: return None else: return r def populate_from_playlist(self, pl_data): """ Populate Pafy object with items fetched from playlist data. """ self._title = pl_data.get("title") self._author = pl_data.get("author") self._length = int(pl_data.get("length_seconds", 0)) self._rating = pl_data.get("rating", 0.0) self._viewcount = "".join(re.findall(r"\d", pl_data.get("views", "0"))) self._viewcount = int(self._viewcount) self._description = pl_data.get("description") class BaseStream(object): """ YouTube video stream class. """ def __init__(self, parent): """ Set initial values. """ self._itag = None self._mediatype = None self._threed = None self._rawbitrate = None self._resolution = None self._quality = None self._dimensions = None self._bitrate = None self._extension = None self.encrypted = None self._notes = None self._url = None self._rawurl = None self._parent = parent self._filename = None self._fsize = None self._active = False def generate_filename(self, meta=False, max_length=None): """ Generate filename. """ ok = re.compile(r'[^/]') if os.name == "nt": ok = re.compile(r'[^\\/:*?"<>|]') filename = "".join(x if ok.match(x) else "_" for x in self.title) if meta: filename += " - %s - %s" % (self._parent.videoid, self.itag) if max_length: max_length = max_length + 1 + len(self.extension) if len(filename) > max_length: filename = filename[:max_length-3] + '...' filename += "." + self.extension return filename @property def rawbitrate(self): """ Return raw bitrate value. """ return self._rawbitrate @property def threed(self): """ Return bool, True if stream is 3D. """ return self._threed @property def itag(self): """ Return itag value of stream. """ return self._itag @property def resolution(self): """ Return resolution of stream as str. 0x0 if audio. """ return self._resolution @property def dimensions(self): """ Return dimensions of stream as tuple. (0, 0) if audio. """ return self._dimensions @property def quality(self): """ Return quality of stream (bitrate or resolution). eg, 128k or 640x480 (str) """ return self._quality @property def title(self): """ Return YouTube video title as a string. """ return self._parent.title @property def extension(self): """ Return appropriate file extension for stream (str). Possible values are: 3gp, m4a, m4v, mp4, webm, ogg """ return self._extension @property def bitrate(self): """ Return bitrate of an audio stream. """ return self._bitrate @property def mediatype(self): """ Return mediatype string (normal, audio or video). (normal means a stream containing both video and audio.) """ return self._mediatype @property def notes(self): """ Return additional notes regarding the stream format. """ return self._notes @property def filename(self): """ Return filename of stream; derived from title and extension. """ if not self._filename: self._filename = self.generate_filename() return self._filename @property def url(self): """ Return the url, decrypt if required. """ return self._url @property def url_https(self): """ Return https url. """ return self.url.replace("http://", "https://") def __repr__(self): """ Return string representation. """ out = "%s:%s@%s" % (self.mediatype, self.extension, self.quality) return out def get_filesize(self): """ Return filesize of the stream in bytes. Set member variable. """ if not self._fsize: try: dbg("Getting stream size") cl = "content-length" self._fsize = int(g.opener.open(self.url).headers[cl]) dbg("Got stream size") except (AttributeError, HTTPError, URLError): self._fsize = 0 return self._fsize def cancel(self): """ Cancel an active download. """ if self._active: self._active = False return True def download(self, filepath="", quiet=False, callback=lambda *x: None, meta=False, remux_audio=False): """ Download. Use quiet=True to supress output. Return filename. Use meta=True to append video id and itag to generated filename Use remax_audio=True to remux audio file downloads """ # pylint: disable=R0912,R0914 # Too many branches, too many local vars savedir = filename = "" if filepath and os.path.isdir(filepath): savedir, filename = filepath, self.generate_filename(max_length=256-len('.temp')) elif filepath: savedir, filename = os.path.split(filepath) else: filename = self.generate_filename(meta=meta, max_length=256-len('.temp')) filepath = os.path.join(savedir, filename) temp_filepath = filepath + ".temp" status_string = (' {:,} Bytes [{:.2%}] received. Rate: [{:4.0f} ' 'KB/s]. ETA: [{:.0f} secs]') if early_py_version: status_string = (' {0:} Bytes [{1:.2%}] received. Rate:' ' [{2:4.0f} KB/s]. ETA: [{3:.0f} secs]') response = g.opener.open(self.url) total = int(response.info()['Content-Length'].strip()) chunksize, bytesdone, t0 = 16384, 0, time.time() fmode, offset = "wb", 0 if os.path.exists(temp_filepath): if os.stat(temp_filepath).st_size < total: offset = os.stat(temp_filepath).st_size fmode = "ab" outfh = open(temp_filepath, fmode) if offset: # partial file exists, resume download resuming_opener = build_opener() resuming_opener.addheaders = [('User-Agent', g.user_agent), ("Range", "bytes=%s-" % offset)] response = resuming_opener.open(self.url) bytesdone = offset self._active = True while self._active: chunk = response.read(chunksize) outfh.write(chunk) elapsed = time.time() - t0 bytesdone += len(chunk) if elapsed: rate = ((float(bytesdone) - float(offset)) / 1024.0) / elapsed eta = (total - bytesdone) / (rate * 1024) else: # Avoid ZeroDivisionError rate = 0 eta = 0 progress_stats = (bytesdone, bytesdone * 1.0 / total, rate, eta) if not chunk: outfh.close() break if not quiet: status = status_string.format(*progress_stats) sys.stdout.write("\r" + status + ' ' * 4 + "\r") sys.stdout.flush() if callback: callback(total, *progress_stats) if self._active: if remux_audio and self.mediatype == "audio": remux(temp_filepath, filepath, quiet=quiet, muxer=remux_audio) else: os.rename(temp_filepath, filepath) return filepath else: # download incomplete, return temp filepath outfh.close() return temp_filepath def remux(infile, outfile, quiet=False, muxer="ffmpeg"): """ Remux audio. """ muxer = muxer if isinstance(muxer, str) else "ffmpeg" for tool in set([muxer, "ffmpeg", "avconv"]): cmd = [tool, "-y", "-i", infile, "-acodec", "copy", "-vn", outfile] try: with open(os.devnull, "w") as devnull: subprocess.call(cmd, stdout=devnull, stderr=subprocess.STDOUT) except OSError: dbg("Failed to remux audio using %s", tool) else: os.unlink(infile) dbg("remuxed audio file using %s" % tool) if not quiet: sys.stdout.write("\nAudio remuxed.\n") break else: logging.warning("audio remux failed") os.rename(infile, outfile) pafy-0.5.2/pafy/backend_youtube_dl.py000066400000000000000000000104671275540311500176230ustar00rootroot00000000000000import sys import time import logging if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 uni = str else: uni = unicode import youtube_dl from . import g from .backend_shared import BasePafy, BaseStream, remux dbg = logging.debug early_py_version = sys.version_info[:2] < (2, 7) class YtdlPafy(BasePafy): def __init__(self, *args, **kwargs): self._ydl_info = None self._ydl_opts = g.def_ydl_opts ydl_opts = kwargs.get("ydl_opts") if ydl_opts: self._ydl_opts.update(ydl_opts) super(YtdlPafy, self).__init__(*args, **kwargs) def _fetch_basic(self): """ Fetch basic data and streams. """ if self._have_basic: return with youtube_dl.YoutubeDL(self._ydl_opts) as ydl: try: self._ydl_info = ydl.extract_info(self.videoid, download=False) # Turn into an IOError since that is what pafy previously raised except youtube_dl.utils.DownloadError as e: raise IOError(str(e).replace('YouTube said', 'Youtube says')) self.callback("Fetched video info") self._title = self._ydl_info['title'] self._author = self._ydl_info['uploader'] self._rating = self._ydl_info['average_rating'] self._length = self._ydl_info['duration'] self._viewcount = self._ydl_info['view_count'] self._likes = self._ydl_info['like_count'] self._dislikes = self._ydl_info['dislike_count'] self._username = self._ydl_info['uploader_id'] self._category = self._ydl_info['categories'][0] self._bigthumb = g.urls['bigthumb'] % self.videoid self._bigthumbhd = g.urls['bigthumbhd'] % self.videoid self.expiry = time.time() + g.lifespan self._have_basic = True def _fetch_gdata(self): """ Extract gdata values, fetch gdata if necessary. """ if self._have_gdata: return item = self._get_video_gdata(self.videoid)['items'][0] snippet = item['snippet'] self._published = uni(snippet['publishedAt']) self._description = uni(snippet["description"]) # Note: using snippet.get since some videos have no tags object self._keywords = [uni(i) for i in snippet.get('tags', ())] self._have_gdata = True def _process_streams(self): """ Create Stream object lists from internal stream maps. """ if not self._have_basic: self._fetch_basic() allstreams = [YtdlStream(z, self) for z in self._ydl_info['formats']] self._streams = [i for i in allstreams if i.mediatype == 'normal'] self._audiostreams = [i for i in allstreams if i.mediatype == 'audio'] self._videostreams = [i for i in allstreams if i.mediatype == 'video'] self._m4astreams = [i for i in allstreams if i.extension == 'm4a'] self._oggstreams = [i for i in allstreams if i.extension == 'ogg'] self._allstreams = allstreams class YtdlStream(BaseStream): def __init__(self, info, parent): super(YtdlStream, self).__init__(parent) self._itag = info['format_id'] if (info.get('acodec') != 'none' and info.get('vcodec') == 'none'): self._mediatype = 'audio' elif (info.get('acodec') == 'none' and info.get('vcodec') != 'none'): self._mediatype = 'video' else: self._mediatype = 'normal' self._threed = info.get('format_note') == '3D' self._rawbitrate = info.get('abr', 0) * 1024 height = info.get('height') or 0 width = info.get('width') or 0 self._resolution = str(width) + 'x' + str(height) self._dimensions = width, height self._bitrate = str(info.get('abr', 0)) + 'k' self._quality = self._bitrate if self._mediatype == 'audio' else self._resolution self._extension = info['ext'] self._notes = info.get('format_note') or '' self._url = info.get('url') self._info = info def get_filesize(self): """ Return filesize of the stream in bytes. Set member variable. """ # Faster method if 'filesize' in self._info and self._info['filesize'] is not None: return self._info['filesize'] # Fallback return super(YtdlStream, self).get_filesize() pafy-0.5.2/pafy/g.py000066400000000000000000000075231275540311500142260ustar00rootroot00000000000000import sys if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.request import build_opener else: from urllib2 import build_opener from . import __version__ urls = { 'gdata': "https://www.googleapis.com/youtube/v3/", 'watchv': "http://www.youtube.com/watch?v=%s", 'playlist': ('http://www.youtube.com/list_ajax?' 'style=json&action_get_list=1&list=%s'), 'thumb': "http://i.ytimg.com/vi/%s/default.jpg", 'bigthumb': "http://i.ytimg.com/vi/%s/mqdefault.jpg", 'bigthumbhd': "http://i.ytimg.com/vi/%s/hqdefault.jpg", # For internal backend 'vidinfo': ('https://www.youtube.com/get_video_info?video_id=%s&' 'eurl=https://youtube.googleapis.com/v/%s&sts=%s'), 'embed': "https://youtube.com/embed/%s" } api_key = "AIzaSyCIM4EzNqi1in22f4Z3Ru3iYvLaY8tc3bo" user_agent = "pafy " + __version__ lifespan = 60 * 60 * 5 # 5 hours opener = build_opener() opener.addheaders = [('User-Agent', user_agent)] cache = {} def_ydl_opts = {'quiet': True, 'prefer_insecure': True, 'no_warnings': True} # The following are specific to the internal backend UEFSM = 'url_encoded_fmt_stream_map' AF = 'adaptive_fmts' jsplayer = r';ytplayer\.config\s*=\s*({.*?});' itags = { '5': ('320x240', 'flv', "normal", ''), '17': ('176x144', '3gp', "normal", ''), '18': ('640x360', 'mp4', "normal", ''), '22': ('1280x720', 'mp4', "normal", ''), '34': ('640x360', 'flv', "normal", ''), '35': ('854x480', 'flv', "normal", ''), '36': ('320x240', '3gp', "normal", ''), '37': ('1920x1080', 'mp4', "normal", ''), '38': ('4096x3072', 'mp4', "normal", '4:3 hi-res'), '43': ('640x360', 'webm', "normal", ''), '44': ('854x480', 'webm', "normal", ''), '45': ('1280x720', 'webm', "normal", ''), '46': ('1920x1080', 'webm', "normal", ''), '82': ('640x360-3D', 'mp4', "normal", ''), '83': ('640x480-3D', 'mp4', 'normal', ''), '84': ('1280x720-3D', 'mp4', "normal", ''), '100': ('640x360-3D', 'webm', "normal", ''), '102': ('1280x720-3D', 'webm', "normal", ''), '133': ('426x240', 'm4v', 'video', ''), '134': ('640x360', 'm4v', 'video', ''), '135': ('854x480', 'm4v', 'video', ''), '136': ('1280x720', 'm4v', 'video', ''), '137': ('1920x1080', 'm4v', 'video', ''), '138': ('4096x3072', 'm4v', 'video', ''), '139': ('48k', 'm4a', 'audio', ''), '140': ('128k', 'm4a', 'audio', ''), '141': ('256k', 'm4a', 'audio', ''), '160': ('256x144', 'm4v', 'video', ''), '167': ('640x480', 'webm', 'video', ''), '168': ('854x480', 'webm', 'video', ''), '169': ('1280x720', 'webm', 'video', ''), '170': ('1920x1080', 'webm', 'video', ''), '171': ('128k', 'ogg', 'audio', ''), '172': ('192k', 'ogg', 'audio', ''), '218': ('854x480', 'webm', 'video', 'VP8'), '219': ('854x480', 'webm', 'video', 'VP8'), '242': ('360x240', 'webm', 'video', 'VP9'), '243': ('480x360', 'webm', 'video', 'VP9'), '244': ('640x480', 'webm', 'video', 'VP9 low'), '245': ('640x480', 'webm', 'video', 'VP9 med'), '246': ('640x480', 'webm', 'video', 'VP9 high'), '247': ('720x480', 'webm', 'video', 'VP9'), '248': ('1920x1080', 'webm', 'video', 'VP9'), '249': ('48k', 'opus', 'audio', 'Opus'), '250': ('56k', 'opus', 'audio', 'Opus'), '251': ('128k', 'opus', 'audio', 'Opus'), '256': ('192k', 'm4a', 'audio', '6-channel'), '258': ('320k', 'm4a', 'audio', '6-channel'), '264': ('2560x1440', 'm4v', 'video', ''), '266': ('3840x2160', 'm4v', 'video', 'AVC'), '271': ('1920x1280', 'webm', 'video', 'VP9'), '272': ('3414x1080', 'webm', 'video', 'VP9'), '278': ('256x144', 'webm', 'video', 'VP9'), '298': ('1280x720', 'm4v', 'video', '60fps'), '299': ('1920x1080', 'm4v', 'video', '60fps'), '302': ('1280x720', 'webm', 'video', 'VP9'), '303': ('1920x1080', 'webm', 'video', 'VP9'), } pafy-0.5.2/pafy/jsinterp.py000066400000000000000000000230471275540311500156350ustar00rootroot00000000000000# Copied from youtube_dl from __future__ import unicode_literals import json import operator import re import sys import traceback class ExtractorError(Exception): """Error during info extraction.""" def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None): """ tb, if given, is the original traceback (so that it can be printed out). If expected is set, this is a normal error message and most likely not a bug in youtube-dl. """ if video_id is not None: msg = video_id + ': ' + msg if cause: msg += ' (caused by %r)' % cause super(ExtractorError, self).__init__(msg) self.traceback = tb self.exc_info = sys.exc_info() # preserve original exception self.cause = cause self.video_id = video_id def format_traceback(self): if self.traceback is None: return None return ''.join(traceback.format_tb(self.traceback)) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _ASSIGN_OPERATORS.append(('=', lambda cur, right: right)) _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def interpret_statement(self, stmt, local_vars, allow_recursion=100): if allow_recursion < 0: raise ExtractorError('Recursion limit reached') should_abort = False stmt = stmt.lstrip() stmt_m = re.match(r'var\s', stmt) if stmt_m: expr = stmt[len(stmt_m.group(0)):] else: return_m = re.match(r'return(?:\s+|$)', stmt) if return_m: expr = stmt[len(return_m.group(0)):] should_abort = True else: # Try interpreting it as an expression expr = stmt v = self.interpret_expression(expr, local_vars, allow_recursion) return v, should_abort def interpret_expression(self, expr, local_vars, allow_recursion): expr = expr.strip() if expr == '': # Empty expression return None if expr.startswith('('): parens_count = 0 for m in re.finditer(r'[()]', expr): if m.group(0) == '(': parens_count += 1 else: parens_count -= 1 if parens_count == 0: sub_expr = expr[1:m.start()] sub_result = self.interpret_expression( sub_expr, local_vars, allow_recursion) remaining_expr = expr[m.end():].strip() if not remaining_expr: return sub_result else: expr = json.dumps(sub_result) + remaining_expr break else: raise ExtractorError('Premature end of parens in %r' % expr) for op, opfunc in _ASSIGN_OPERATORS: m = re.match(r'''(?x) (?P%s)(?:\[(?P[^\]]+?)\])? \s*%s (?P.*)$''' % (_NAME_RE, re.escape(op)), expr) if not m: continue right_val = self.interpret_expression( m.group('expr'), local_vars, allow_recursion - 1) if m.groupdict().get('index'): lvar = local_vars[m.group('out')] idx = self.interpret_expression( m.group('index'), local_vars, allow_recursion) assert isinstance(idx, int) cur = lvar[idx] val = opfunc(cur, right_val) lvar[idx] = val return val else: cur = local_vars.get(m.group('out')) val = opfunc(cur, right_val) local_vars[m.group('out')] = val return val if expr.isdigit(): return int(expr) var_m = re.match( r'(?!if|return|true|false)(?P%s)$' % _NAME_RE, expr) if var_m: return local_vars[var_m.group('name')] try: return json.loads(expr) except ValueError: pass m = re.match( r'(?P%s)\.(?P[^(]+)(?:\(+(?P[^()]*)\))?$' % _NAME_RE, expr) if m: variable = m.group('var') member = m.group('member') arg_str = m.group('args') if variable in local_vars: obj = local_vars[variable] else: if variable not in self._objects: self._objects[variable] = self.extract_object(variable) obj = self._objects[variable] if arg_str is None: # Member access if member == 'length': return len(obj) return obj[member] assert expr.endswith(')') # Function call if arg_str == '': argvals = tuple() else: argvals = tuple([ self.interpret_expression(v, local_vars, allow_recursion) for v in arg_str.split(',')]) if member == 'split': assert argvals == ('',) return list(obj) if member == 'join': assert len(argvals) == 1 return argvals[0].join(obj) if member == 'reverse': assert len(argvals) == 0 obj.reverse() return obj if member == 'slice': assert len(argvals) == 1 return obj[argvals[0]:] if member == 'splice': assert isinstance(obj, list) index, howMany = argvals res = [] for i in range(index, min(index + howMany, len(obj))): res.append(obj.pop(index)) return res return obj[member](argvals) m = re.match( r'(?P%s)\[(?P.+)\]$' % _NAME_RE, expr) if m: val = local_vars[m.group('in')] idx = self.interpret_expression( m.group('idx'), local_vars, allow_recursion - 1) return val[idx] for op, opfunc in _OPERATORS: m = re.match(r'(?P.+?)%s(?P.+)' % re.escape(op), expr) if not m: continue x, abort = self.interpret_statement( m.group('x'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature left-side return of %s in %r' % (op, expr)) y, abort = self.interpret_statement( m.group('y'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature right-side return of %s in %r' % (op, expr)) return opfunc(x, y) m = re.match( r'^(?P%s)\((?P[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v in m.group('args').split(',')]) if fname not in self._functions: self._functions[fname] = self.extract_function(fname) return self._functions[fname](argvals) raise ExtractorError('Unsupported JS expression %r' % expr) def extract_object(self, objname): obj = {} obj_m = re.search( (r'(?:var\s+)?%s\s*=\s*\{' % re.escape(objname)) + r'\s*(?P([a-zA-Z$0-9]+\s*:\s*function\(.*?\)\s*\{.*?\}(?:,\s*)?)*)' + r'\}\s*;', self.code) fields = obj_m.group('fields') # Currently, it only supports function definitions fields_m = re.finditer( r'(?P[a-zA-Z$0-9]+)\s*:\s*function' r'\((?P[a-z,]+)\){(?P[^}]+)}', fields) for f in fields_m: argnames = f.group('args').split(',') obj[f.group('key')] = self.build_function(argnames, f.group('code')) return obj def extract_function(self, funcname): func_m = re.search( r'''(?x) (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* \((?P[^)]*)\)\s* \{(?P[^}]+)\}''' % ( re.escape(funcname), re.escape(funcname), re.escape(funcname)), self.code) if func_m is None: raise ExtractorError('Could not find JS function %r' % funcname) argnames = func_m.group('args').split(',') return self.build_function(argnames, func_m.group('code')) def call_function(self, funcname, *args): f = self.extract_function(funcname) return f(args) def build_function(self, argnames, code): def resf(args): local_vars = dict(zip(argnames, args)) for stmt in code.split(';'): res, abort = self.interpret_statement(stmt, local_vars) if abort: break return res return resf pafy-0.5.2/pafy/pafy.py000066400000000000000000000136761275540311500147450ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ pafy.py. Python library to download YouTube content and retrieve metadata https://github.com/np1/pafy Copyright (C) 2013-2014 np1 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . """ import sys import os import logging import time import re if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.error import HTTPError else: from urllib2 import HTTPError from . import g from .util import call_gdata Pafy = None # Select which backend to use backend = "internal" if os.environ.get("PAFY_BACKEND") != "internal": try: import youtube_dl backend = "youtube-dl" except ImportError: logging.warning("""pafy: youtube-dl not found; falling back to internal \ backend. This is not as well maintained as the youtube-dl backend. To hide this \ message, set the environmental variable PAFY_BACKEND to \"internal\".""") if os.environ.get("pafydebug") == "1": logging.basicConfig(level=logging.DEBUG) dbg = logging.debug def fetch_decode(url, encoding=None): """ Fetch url and decode. """ try: req = g.opener.open(url) except HTTPError as e: if e.getcode() == 503: time.sleep(.5) return fetch_decode(url, encoding) else: raise ct = req.headers['content-type'] if encoding: return req.read().decode(encoding) elif "charset=" in ct: dbg("charset: %s", ct) encoding = re.search(r"charset=([\w-]+)\s*(:?;|$)", ct).group(1) return req.read().decode(encoding) else: dbg("encoding unknown") return req.read() def new(url, basic=True, gdata=False, size=False, callback=None, ydl_opts=None): """ Return a new pafy instance given a url or video id. NOTE: The signature argument has been deprecated and now has no effect, it will be removed in a future version. Optional arguments: basic - fetch basic metadata and streams gdata - fetch gdata info (upload date, description, category) size - fetch the size of each stream (slow)(decrypts urls if needed) callback - a callback function to receive status strings If any of the first three above arguments are False, those data items will be fetched only when first called for. The defaults are recommended for most cases. If you wish to create many video objects at once, you may want to set basic to False, eg: video = pafy.new(basic=False) This will be quick because no http requests will be made on initialisation. Setting size to True will override the basic argument and force basic data to be fetched too (basic data is required to obtain Stream objects). """ global Pafy if Pafy is None: if backend == "internal": from .backend_internal import InternPafy as Pafy else: from .backend_youtube_dl import YtdlPafy as Pafy return Pafy(url, basic, gdata, size, callback, ydl_opts) def cache(name): """ Returns a sub-cache dictionary under which global key, value pairs can be stored. Regardless of whether a dictionary already exists for the given name, the sub-cache is returned by reference. """ if name not in g.cache: g.cache[name] = {} return g.cache[name] def get_categoryname(cat_id): """ Returns a list of video category names for one category ID. """ timestamp = time.time() cat_cache = cache('categories') cached = cat_cache.get(cat_id, {}) if cached.get('updated', 0) > timestamp - g.lifespan: return cached.get('title', 'unknown') # call videoCategories API endpoint to retrieve title query = {'id': cat_id, 'part': 'snippet'} catinfo = call_gdata('videoCategories', query) try: for item in catinfo.get('items', []): title = item.get('snippet', {}).get('title', 'unknown') cat_cache[cat_id] = {'title':title, 'updated':timestamp} return title cat_cache[cat_id] = {'updated':timestamp} return 'unknown' except Exception: raise IOError("Error fetching category name for ID %s" % cat_id) def set_categories(categories): """ Take a dictionary mapping video category IDs to name and retrieval time. All items are stored into cache node 'videoCategories', but for the ones with a retrieval time too long ago, the v3 API is queried before. """ timestamp = time.time() idlist = [cid for cid, item in categories.items() if item.get('updated', 0) < timestamp - g.lifespan] if len(idlist) > 0: query = {'id': ','.join(idlist), 'part': 'snippet'} catinfo = call_gdata('videoCategories', query) try: for item in catinfo.get('items', []): cid = item['id'] title = item.get('snippet', {}).get('title', 'unknown') categories[cid] = {'title':title, 'updated':timestamp} except Exception: raise IOError("Error fetching category name for IDs %s" % idlist) cache('categories').update(categories) def load_cache(newcache): """Loads a dict into pafy's internal cache.""" set_categories(newcache.get('categories', {})) def dump_cache(): """Returns pafy's cache for storing by program.""" return g.cache def set_api_key(key): """Sets the api key to be used with youtube.""" g.api_key = key pafy-0.5.2/pafy/playlist.py000066400000000000000000000167451275540311500156470ustar00rootroot00000000000000import sys import re import json if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.parse import parse_qs, urlparse else: from urlparse import parse_qs, urlparse from . import g from .pafy import new, get_categoryname, call_gdata, fetch_decode def extract_playlist_id(playlist_url): # Normal playlists start with PL, Mixes start with RD + first video ID idregx = re.compile(r'((?:RD|PL|LL)[-_0-9a-zA-Z]+)$') playlist_id = None if idregx.match(playlist_url): playlist_id = playlist_url # ID of video if '://' not in playlist_url: playlist_url = '//' + playlist_url parsedurl = urlparse(playlist_url) if parsedurl.netloc in ('youtube.com', 'www.youtube.com'): query = parse_qs(parsedurl.query) if 'list' in query and idregx.match(query['list'][0]): playlist_id = query['list'][0] return playlist_id def get_playlist(playlist_url, basic=False, gdata=False, size=False, callback=lambda x: None): """ Return a dict containing Pafy objects from a YouTube Playlist. The returned Pafy objects are initialised using the arguments to get_playlist() in the manner documented for pafy.new() """ playlist_id = extract_playlist_id(playlist_url) if not playlist_id: err = "Unrecognized playlist url: %s" raise ValueError(err % playlist_url) url = g.urls["playlist"] % playlist_id allinfo = fetch_decode(url) # unicode allinfo = json.loads(allinfo) # playlist specific metadata playlist = dict( playlist_id=playlist_id, likes=allinfo.get('likes'), title=allinfo.get('title'), author=allinfo.get('author'), dislikes=allinfo.get('dislikes'), description=allinfo.get('description'), items=[] ) # playlist items specific metadata for v in allinfo['video']: vid_data = dict( added=v.get('added'), is_cc=v.get('is_cc'), is_hd=v.get('is_hd'), likes=v.get('likes'), title=v.get('title'), views=v.get('views'), rating=v.get('rating'), author=v.get('author'), user_id=v.get('user_id'), privacy=v.get('privacy'), start=v.get('start', 0.0), dislikes=v.get('dislikes'), duration=v.get('duration'), comments=v.get('comments'), keywords=v.get('keywords'), thumbnail=v.get('thumbnail'), cc_license=v.get('cc_license'), category_id=v.get('category_id'), description=v.get('description'), encrypted_id=v.get('encrypted_id'), time_created=v.get('time_created'), time_updated=v.get('time_updated'), length_seconds=v.get('length_seconds'), end=v.get('end', v.get('length_seconds')) ) try: pafy_obj = new(vid_data['encrypted_id'], basic=basic, gdata=gdata, size=size, callback=callback) except IOError as e: callback("%s: %s" % (v['title'], e.message)) continue pafy_obj.populate_from_playlist(vid_data) playlist['items'].append(dict(pafy=pafy_obj, playlist_meta=vid_data)) callback("Added video: %s" % v['title']) return playlist def parseISO8591(duration): """ Parse ISO 8591 formated duration """ regex = re.compile(r'PT((\d{1,3})H)?((\d{1,3})M)?((\d{1,2})S)?') if duration: duration = regex.findall(duration) if len(duration) > 0: _, hours, _, minutes, _, seconds = duration[0] duration = [seconds, minutes, hours] duration = [int(v) if len(v) > 0 else 0 for v in duration] duration = sum([60**p*v for p, v in enumerate(duration)]) else: duration = 30 else: duration = 30 return duration class Playlist(object): _items = None def __init__(self, playlist_url, basic, gdata, size, callback): playlist_id = extract_playlist_id(playlist_url) if not playlist_id: err = "Unrecognized playlist url: %s" raise ValueError(err % playlist_url) query = {'part': 'snippet, contentDetails', 'id': playlist_id} allinfo = call_gdata('playlists', query) pl = allinfo['items'][0] self.plid = playlist_id self.title = pl['snippet']['title'] self.author = pl['snippet']['channelTitle'] self.description = pl['snippet']['description'] self ._len = pl['contentDetails']['itemCount'] self._basic = basic self._gdata = gdata self._size = size self._callback = callback def __len__(self): return self._len def __iter__(self): if self._items is not None: for i in self._items: yield i return items = [] # playlist items specific metadata query = {'part': 'snippet', 'maxResults': 50, 'playlistId': self.plid} while True: playlistitems = call_gdata('playlistItems', query) query2 = {'part':'contentDetails,snippet,statistics', 'maxResults': 50, 'id': ','.join(i['snippet']['resourceId']['videoId'] for i in playlistitems['items'])} wdata = call_gdata('videos', query2) for v, vextra in zip(playlistitems['items'], wdata['items']): vid_data = dict( title=v['snippet']['title'], author=v['snippet']['channelTitle'], thumbnail=v['snippet'].get('thumbnails', {} ).get('default', {}).get('url'), description=v['snippet']['description'], length_seconds=parseISO8591( vextra['contentDetails']['duration']), category=get_categoryname(vextra['snippet']['categoryId']), views=vextra['statistics'].get('viewCount',0), likes=vextra['statistics'].get('likeCount',0), dislikes=vextra['statistics'].get('dislikeCount',0), comments=vextra['statistics'].get('commentCount',0), ) try: pafy_obj = new(v['snippet']['resourceId']['videoId'], basic=self._basic, gdata=self._gdata, size=self._size, callback=self._callback) except IOError as e: self.callback("%s: %s" % (v['title'], e.message)) continue pafy_obj.populate_from_playlist(vid_data) items.append(pafy_obj) self._callback("Added video: %s" % vid_data['title']) yield pafy_obj if not playlistitems.get('nextPageToken'): break query['pageToken'] = playlistitems['nextPageToken'] self._items = items def get_playlist2(playlist_url, basic=False, gdata=False, size=False, callback=lambda x: None): """ Return a Playlist object from a YouTube Playlist. The returned Pafy objects are initialised using the arguments to get_playlist() in the manner documented for pafy.new() """ return Playlist(playlist_url, basic, gdata, size, callback) pafy-0.5.2/pafy/util.py000066400000000000000000000016021275540311500147450ustar00rootroot00000000000000import json import sys if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.error import HTTPError from urllib.parse import urlencode else: from urllib2 import HTTPError from urllib import urlencode from . import g class GdataError(Exception): """Gdata query failed.""" pass def call_gdata(api, qs): """Make a request to the youtube gdata api.""" qs = dict(qs) qs['key'] = g.api_key url = g.urls['gdata'] + api + '?' + urlencode(qs) try: data = g.opener.open(url).read().decode('utf-8') except HTTPError as e: try: errdata = e.file.read().decode() error = json.loads(errdata)['error']['message'] errmsg = 'Youtube Error %d: %s' % (e.getcode(), error) except: errmsg = str(e) raise GdataError(errmsg) return json.loads(data) pafy-0.5.2/scripts/000077500000000000000000000000001275540311500141475ustar00rootroot00000000000000pafy-0.5.2/scripts/ytdl000077500000000000000000000125001275540311500150470ustar00rootroot00000000000000#!/usr/bin/env python """ pafy - Command Line Downloader Tool - ytdl. Copyright (C) 2013-2014 np1 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . """ from __future__ import print_function, unicode_literals import pafy import sys import os early_py_version = sys.version_info[:2] < (2, 7) try: import argparse except ImportError: if early_py_version: msg = ("ytdl requires the argparse library to be installed separately " "for Python versions earlier than 2.7") sys.exit(msg) else: raise __version__ = "0.3.67" __author__ = "np1" __license__ = "LGPLv3" mswin = os.name == "nt" not_utf8_environment = mswin or "UTF-8" not in os.environ.get("LANG", "") def utf8_replace(txt): """ Replace unsupported characters in unicode string, returns unicode. """ sse = sys.stdout.encoding txt = txt.encode(sse, "replace").decode("utf8", "ignore") return txt def xenc(stuff): """ Replace unsupported characters. """ if sys.stdout.isatty(): return utf8_replace(stuff) if not_utf8_environment else stuff else: return stuff.encode("utf8", errors="replace") def xprint(stuff, end=None): """ Compatible print. """ print(xenc(stuff), end=end) def download(video, audio=False, stream=None): """ Download a video. """ if not stream and not audio: stream = video.getbest(preftype="mp4") if not stream and audio: stream = video.getbestaudio() size = stream.get_filesize() dl_str = "-Downloading '{0}' [{1:,} Bytes]" if early_py_version: dl_str = "-Downloading '{0}' [{1} Bytes]" xprint(dl_str.format(stream.filename, size)) xprint("-Quality: %s; Format: %s" % (stream.quality, stream.extension)) stream.download(quiet=False) xprint("\nDone") def printstreams(streams): """ Dump stream info. """ fstring = "{0:<7}{1:<8}{2:<7}{3:<15}{4:<10} " out = [] l = len(streams) text = " [Fetching stream info] >" for n, s in enumerate(streams): sys.stdout.write(text + "-" * n + ">" + " " * (l - n - 1) + "<\r") sys.stdout.flush() megs = "%3.f" % (s.get_filesize() / 1024 ** 2) + " MB" q = "[%s]" % s.quality out.append(fstring.format(n + 1, s.mediatype, s.extension, q, megs)) sys.stdout.write("\r") xprint(fstring.format("Stream", "Type", "Format", "Quality", " Size")) xprint(fstring.format("------", "----", "------", "-------", " ----")) for x in out: xprint(x) def main(): """ Parse args and show info or download. """ # pylint: disable=R0912 # too many branches description = "YouTube Download Tool" parser = argparse.ArgumentParser(description=description) paa = parser.add_argument paa('url', help="YouTube video URL to download") paa('-i', required=False, help="Display vid info", action="store_true") paa('-s', help="Display available streams", action="store_true") paa('-t', help="Stream types to display", type=str, nargs="+", choices="audio video normal all".split()) paa('-n', required=False, metavar="N", type=int, help='Specify stream to ' 'download by stream number (use -s to list available streams)') paa('-b', required=False, help='Download the best quality video (ignores ' '-n)', action="store_true") paa('-a', required=False, help='Download the best quality audio (ignores ' '-n)', action="store_true") args = parser.parse_args() vid = pafy.new(args.url) streams = [] if args.t: if "video" in args.t: streams += vid.videostreams if "audio" in args.t: streams += vid.audiostreams[::-1] if "normal" in args.t: streams += vid.streams if "all" in args.t: streams = vid.allstreams else: streams = vid.streams + vid.audiostreams[::-1] # if requested print vid info and list streams if args.i: xprint(vid) if args.s: printstreams(streams) if args.b or args.a: if args.a and args.b: xprint("-a and -b cannot be used together! Use only one.") else: download(vid, audio=args.a) sys.exit() elif args.n: streamnumber = int(args.n) - 1 try: download(vid, stream=streams[streamnumber]) except IndexError: em = "Sorry, %s is not a valid option, use 1-%s" em = em % (int(args.n), len(streams)) xprint(em) if not any([args.i, args.s, args.b, args.n, args.t, args.a]): streams = vid.streams + vid.audiostreams[::-1] printstreams(streams) elif args.t and not args.a and not args.b and not args.s: printstreams(streams) else: pass if __name__ == "__main__": main() pafy-0.5.2/setup.cfg000066400000000000000000000000341275540311500142760ustar00rootroot00000000000000[bdist_wheel] universal = 1 pafy-0.5.2/setup.py000077500000000000000000000037051275540311500142020ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- """ setup.py for pafy. https://np1.github.com/np1/pafy python setup.py sdist bdist_wheel """ from setuptools import setup from pafy import __version__ setup( name='pafy', packages=['pafy'], scripts=['scripts/ytdl'], version=__version__, description="Retrieve YouTube content and metadata", keywords=["pafy", "API", "YouTube", "youtube", "download", "video"], author="np1", author_email="np1nagev@gmail.com", url="http://np1.github.io/pafy/", download_url="https://github.com/np1/pafy/tarball/master", extras_require={ 'youtube-dl-backend': ["youtube-dl"], }, package_data={"": ["LICENSE", "README.rst", "CHANGELOG", "AUTHORS"]}, include_package_data=True, license='LGPLv3', classifiers=[ "License :: OSI Approved :: GNU Lesser General Public License v3 " "(LGPLv3)", "Operating System :: POSIX :: Linux", "Operating System :: MacOS", "Operating System :: MacOS :: MacOS 9", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft", "Operating System :: Microsoft :: Windows :: Windows 7", "Operating System :: Microsoft :: Windows :: Windows XP", "Operating System :: Microsoft :: Windows :: Windows Vista", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Intended Audience :: Developers", "Development Status :: 5 - Production/Stable", "Topic :: Multimedia :: Sound/Audio :: Capture/Recording", "Topic :: Utilities", "Topic :: Multimedia :: Video", "Topic :: Internet :: WWW/HTTP"], long_description=open("README.rst").read() ) pafy-0.5.2/tests/000077500000000000000000000000001275540311500136225ustar00rootroot00000000000000pafy-0.5.2/tests/test.py000066400000000000000000000247211275540311500151610ustar00rootroot00000000000000# encoding: utf8 """ Tests for pafy. """ from __future__ import unicode_literals from functools import wraps import hashlib import pafy import time import os import sys try: import unittest2 as unittest except ImportError: import unittest def stdout_to_null(fn): """ Supress stdout. """ @wraps(fn) def wrapper(*a, **b): """ wrapping function. """ with open(os.devnull, "w") as nul: stash = sys.stdout sys.stdout = nul retval = fn(*a, **b) sys.stdout = stash return retval return wrapper class Test(unittest.TestCase): """ Tests. """ def runOnce(self): """ Create pafy objects for tests. """ if hasattr(Test, "hasrun"): return Test.quick = os.environ.get("quick") Test.videos = VIDEOS if not Test.quick else [] Test.playlists = PLAYLISTS if not Test.quick else [] for video in Test.videos: time.sleep(0 if Test.quick else self.delay) video['pafy'] = pafy.new(video['identifier']) video['streams'] = video['pafy'].streams video['best'] = video['pafy'].getbest() video['bestaudio'] = video['pafy'].getbestaudio() video['bestvideo'] = video['pafy'].getbestvideo() # get urls for age restricted vids if video['pafy'].videoid == "07FYdnEawAQ": _ = video['pafy'].streams[0].url _ = video['pafy'].streams[1].url_https del _ for playlist in Test.playlists: playlist['fetched'] = pafy.get_playlist(playlist['identifier']) Test.hasrun = True def setUp(self): """ setup for tests. """ self.delay = 3 self.properties = ("videoid title length duration author " "username category thumb published").split() self.runOnce() def test_generate_filename_with_meta(self): """ Use meta argument to generate filename. """ if Test.quick: return p = pafy.new('jrNLsC_Y9Oo', size=True) a = p.getbestaudio() filename = a.generate_filename(meta=True) self.assertEqual(filename, 'Jessie J - WILD (Official) ft. Big Sean' ', Dizzee Rascal-jrNLsC_Y9Oo-251.webm') self.assertEqual(a.threed, False) self.assertEqual(a.title, 'Jessie J - WILD (Official) ft. Big Sean' ', Dizzee Rascal') self.assertEqual(a.notes, 'DASH audio') self.assertEqual(a.filename, 'Jessie J - WILD (Official) ft. Big Sean' ', Dizzee Rascal.webm') @stdout_to_null def test_pafy_download(self): """ Test downloading. """ callback = lambda a, b, c, d, e: 0 vid = pafy.new("DsAn_n6O5Ns", gdata=True) vstream = vid.audiostreams[-1] name = vstream.download(callback=callback) self.assertEqual(name[0:5], "WASTE") @stdout_to_null def test_pafy_download_resume(self): """ Test resuming a partial download. """ tempname = "WASTE 2 SECONDS OF YOUR LIFE-DsAn_n6O5Ns-171.m4a.temp" with open(tempname, "w") as ladeeda: ladeeda.write("abc") vid = pafy.new("DsAn_n6O5Ns", gdata=True, basic=False) vstream = vid.audiostreams[-1].download(meta=True, remux_audio=True) name = "WASTE 2 SECONDS OF YOUR LIFE.m4a" self.assertEqual(63639, os.stat(name).st_size) # test fetching attributes vid._title = None _ = vid.title vid._rating = None _ = vid.rating vid._author = None _ = vid.author vid._rating = None _ = vid.rating vid._length = None _ = vid.length vid._viewcount = None _ = vid.viewcount vid._thumb = None _ = vid.thumb vid._length = None _ = vid.duration def test_pafy_download_invalid_dirname(self): """ Test user specified invalid path. """ vid = pafy.new("DsAn_n6O5Ns", gdata=True) self.assertRaises(IOError, vid.audiostreams[-1].download, "/bad/h/") @stdout_to_null def test_pafy__invalid_win_filename(self): """ Test Windows and colon character in video name. """ os.name = "nt" vid = pafy.new("http://www.youtube.com/watch?v=K-TNJSBrFEk") audio = vid.getbestaudio() expected = ("Jon Meacham_ _Thomas Jefferson_ the Art of Power_ _ Talks" " at Google.m4a") self.assertEqual(expected, audio.generate_filename()) @stdout_to_null def test_pafy_download_to_dir(self): """ Test user specified path. """ vid = pafy.new("DsAn_n6O5Ns", gdata=True) vstream = vid.audiostreams[-1].download("/tmp", meta=True) name = "/tmp/WASTE 2 SECONDS OF YOUR LIFE.m4a" self.assertEqual(63639, os.stat(name).st_size) #def test_lazy_pafy(self): # """ Test create pafy object without fetching data. """ # vid = pafy.new("DsAn_n6O5Ns", basic=False, signature=False) # self.assertEqual(vid.bigthumb, '') # self.assertEqual(vid.bigthumbhd, '') # self.assertIsInstance(vid.likes, int) # self.assertIsInstance(vid.dislikes, int) def test_pafy_init(self): """ Test Pafy object creation. """ # test bad video id, 11 chars badid = "12345678901" too_short = "123" self.assertRaises(ValueError, pafy.new, too_short) self.assertRaises(ValueError, pafy.get_playlist, badid) self.assertRaises(IOError, pafy.new, badid) self.assertRaises(IOError, pafy.get_playlist, 'PL' + "a" * 16) def test_video_properties(self): """ Test video properties. """ for video in Test.videos: description = video['pafy'].description.encode("utf8") self.assertEqual(hashlib.sha1(description).hexdigest(), video['description']) for prop in self.properties: if prop != "thumb": paf_prop = getattr(video['pafy'], prop) exp_prop = video[prop] self.assertEqual(paf_prop, exp_prop) self.assertNotEqual(video.__repr__(), None) def test_streams_exist(self): """ Test for expected number of streams. """ for video in Test.videos: paf = video['pafy'] self.assertEqual(video['all streams'], len(paf.allstreams)) self.assertEqual(video['normal streams'], len(paf.streams)) self.assertEqual(video['audio streams'], len(paf.audiostreams)) self.assertEqual(video['video streams'], len(paf.videostreams)) self.assertEqual(video['ogg streams'], len(paf.oggstreams)) self.assertEqual(video['m4a streams'], len(paf.m4astreams)) def test_best_stream_size(self): """ Test stream filesize. """ for video in Test.videos: time.sleep(0 if Test.quick else self.delay) size = video['best'].get_filesize() self.assertEqual(video['bestsize'], size) def test_get_playlist(self): """ Test get_playlist function. """ for pl in Test.playlists: fetched = pl['fetched'] self.assertEqual(len(fetched['items']), pl['count']) for field in "playlist_id description author title".split(): self.assertEqual(fetched[field], pl[field]) PLAYLISTS = [ { 'identifier': "https://www.youtube.com/playlist?list=PL9-cZf_sidpkzR4W_LxvZjh4F7YFo4WoG", 'playlist_id': "PL9-cZf_sidpkzR4W_LxvZjh4F7YFo4WoG", 'description': "", 'author': "#TheBeatles", 'title': "All Tracks - The Beatles", 'count': 200, }, ] VIDEOS = [ { 'identifier': 'ukm64IUANwE', 'videoid': 'ukm64IUANwE', 'title': 'Getting started with automated testing', 'length': 1837, 'duration': '00:30:37', 'author': 'Next Day Video', 'username': 'NextDayVideo', 'published': '2013-03-19 23:43:42', 'thumb': 'http://i.ytimg.com/vi/ukm64IUANwE/default.jpg', 'category': 'Education', 'description': '1223db22b4a38d0a8ebfcafb549f40c39af26251', 'bestsize': 54284129, 'all streams': 19, 'normal streams': 5, 'video streams': 8, 'audio streams': 6, 'ogg streams': 0, 'm4a streams': 2, }, { 'identifier': 'www.youtube.com/watch?v=SeIJmciN8mo', 'videoid': 'SeIJmciN8mo', 'title': 'Nicki Minaj - Starships (Explicit)', 'length': 261, 'duration': '00:04:21', 'author': 'NickiMinajAtVEVO', 'username': 'NickiMinajAtVEVO', 'published': '2012-04-27 04:22:39', 'thumb': 'http://i.ytimg.com/vi/SeIJmciN8mo/default.jpg', 'category': 'Music', 'description': 'fa34f2704be9c1b21949af515e813f644f14b89a', 'bestsize': 102152520, 'all streams': 17, 'normal streams': 6, 'video streams': 6, 'audio streams': 5, 'ogg streams': 0, 'm4a streams': 1, }, { 'identifier': 'EnHp24CVORc', 'videoid': 'EnHp24CVORc', 'title': 'Chinese Knock Off Sky Loop Roller Coaster POV Chuanlord Holiday Manor China 魔环垂直过山车', 'length': 312, 'duration': '00:05:12', 'author': 'Theme Park Review', 'username': 'themeparkreviewTPR', 'published': '2014-05-05 19:58:07', 'thumb': 'http://i.ytimg.com/vi/EnHp24CVORc/default.jpg', 'category': 'People & Blogs', 'description': '3c884d9791be15646ddf351edffcb2dd22ec70f8', 'bestsize': 101082749, 'all streams': 21, 'normal streams': 6, 'video streams': 12, 'audio streams': 3, 'ogg streams': 0, 'm4a streams': 2, }, { 'identifier': 'http://youtube.com/watch?v=rYEDA3JcQqw', 'videoid': 'rYEDA3JcQqw', 'title': 'Adele - Rolling in the Deep', 'length': 234, 'duration': '00:03:54', 'author': 'AdeleVEVO', 'username': 'AdeleVEVO', 'published': '2010-11-30 23:16:19', 'thumb': 'http://i.ytimg.com/vi/rYEDA3JcQqw/default.jpg', 'category': 'Music', 'description': '72bfd9472e59a8f48b83af36197ebcf5d2227609', 'bestsize': 41333693, 'all streams': 23, 'normal streams': 6, 'video streams': 12, 'audio streams': 5, 'ogg streams': 0, 'm4a streams': 1, } ] if __name__ == "__main__": unittest.main(verbosity=2) pafy-0.5.2/tox.ini000066400000000000000000000002631275540311500137740ustar00rootroot00000000000000[tox] envlist = py34, py26, py27 [testenv] deps = nose commands = nosetests -v tests/test.py [testenv:py26] deps = nose unittest2 commands = nosetests -v tests/test.py