pax_global_header00006660000000000000000000000064134361640620014517gustar00rootroot0000000000000052 comment=561849b8ce4ba85b01a8de0c5c87034ed074556c ytcc-1.8.1/000077500000000000000000000000001343616406200124705ustar00rootroot00000000000000ytcc-1.8.1/.editorconfig000066400000000000000000000003641343616406200151500ustar00rootroot00000000000000# http://editorconfig.org root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true indent_style = space indent_size = 4 trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.py] max_line_length = 99 ytcc-1.8.1/.gitignore000066400000000000000000000022231343616406200144570ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv .venv/ venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject # Pycharm project settings .idea/ # Pydev project settings .pydevproject .project # mypy cache .mypy_cache/ ytcc-1.8.1/.pydocstylerc000066400000000000000000000002011343616406200152060ustar00rootroot00000000000000[pydocstyle] inherit = false # Ignore missing docstrings for now, but existing docstrings must be correct. ignore = D1,D203,D213 ytcc-1.8.1/.pylintrc000066400000000000000000000333371343616406200143460ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist=lxml # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. jobs=4 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,missing-docstring # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable= [REPORTS] # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio).You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module max-module-lines=1000 # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. no-space-check=trailing-comma,dict-separator # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins=_ # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,future.builtins [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming hint for argument names argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Regular expression matching correct argument names argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Naming hint for attribute names attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Regular expression matching correct attribute names attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{1,30}|(__.*__))$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming hint for function names function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Regular expression matching correct function names function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_ # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for method names method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Regular expression matching correct method names method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. property-classes=abc.abstractproperty # Naming hint for variable names variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ # Regular expression matching correct variable names variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis. It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [DESIGN] # Maximum number of arguments for function / method max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=10 # Maximum number of boolean expressions in a if statement max-bool-expr=5 # Maximum number of branch for function / method body max-branches=12 # Maximum number of locals for function / method body max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of statements in function / method body max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=0 [IMPORTS] # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception ytcc-1.8.1/COPYING000066400000000000000000001045131343616406200135270ustar00rootroot00000000000000 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 How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ytcc-1.8.1/README.md000066400000000000000000000127521343616406200137560ustar00rootroot00000000000000# ytcc - The YouTube channel checker Command Line tool to keep track of your favourite YouTube channels without signing up for a Google account. ## Installation ### Arch Linux Install [ytcc](https://aur.archlinux.org/packages/ytcc/) from the AUR. ### Void Linux Install package `ytcc`. ### Other distros Ytcc requires python 3.6 or later. Install dependencies: `python3-sqlalchemy`, `python3-lxml`, `python3-feedparser`, `python3-setuptools`, `mpv`, `youtube-dl`, `gettext`. ```bash git clone https://github.com/woefe/ytcc.git cd ytcc sudo python3 setup.py install sudo install -Dm644 zsh/_ytcc /usr/share/zsh/site-functions/_ytcc ``` ### Without installation You can start ytcc directly from the cloned repo, if all the requirements are installed. ```bash ./ytcc.py --help ``` ## Usage Check for new videos and play them. ```shell ytcc ``` Check for new videos and play them without asking you anything. ```shell ytcc -y ``` "Subscribe" to a channel. ```shell ytcc -a "Jupiter Broadcasting" https://www.youtube.com/user/jupiterbroadcasting ``` Import subscriptions from YouTube's subscription manager export. ```shell ytcc --import-from ~/Downloads/subscription_manager ``` Download all videos from a channel that were published in July. ```shell ytcc -f "Jupiter Broadcasting" --download --since 07-01 --to 07-31 --include-watched ``` Mark all videos of a channel as watched. ```shell ytcc -f "Jupiter Broadcasting" -m ``` Listen to some music without limitations. ```shell ytcc --add "NCS" https://www.youtube.com/user/NoCopyrightSounds --update ytcc --disable-interactive --list --watch --no-video --include-watched --channel-filter NCS ``` ## Configuration Ytcc searches for a configuration file at following locations: 1. `$XDG_CONFIG_HOME/ytcc/ytcc.conf` 2. `~/.config/ytcc/ytcc.conf` 3. `~/.ytcc.conf` If no config file is found in these three locations, a default config file is created at `~/.config/ytcc/ytcc.conf`. ### Example config ```conf # General options [YTCC] # Path to file where database is stored. Can be used to sync the database between multiple machines ;) dbpath = ~/.local/share/ytcc/ytcc.db # Directory where downloads are saved, when --path is not given downloaddir = ~/Downloads # Parameters passed to mpv. Adjusting these might break ytcc! mpvflags = --really-quiet --ytdl --ytdl-format=bestvideo[height<=?1080]+bestaudio/best # The characters to use for selecting videos in interactive mode. alphabet = sdfervghnuiojkl # Defines the order of video listings. # Possible options: channel, date, title, url, id, watched orderby = channel, date # Prompt and table colors. Supports 256 colors. Hence, values between 0-255 are allowed. # See https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit for the color codes. [color] promptdownloadaudio = 2 promptdownloadvideo = 4 promptplayaudio = 2 promptplayvideo = 4 promptmarkwatched = 1 tablealternatebackground = 245 # Options for downloads [youtube-dl] # Format (see FORMAT SELECTION in youtube-dl manpage). Make sure to use a video format here, if you # want to be able to download videos. format = bestvideo[height<=?1080]+bestaudio/best # Output template (see OUTPUT TEMPLATE in youtube-dl manpage) outputtemplate = %(title)s.%(ext)s # Loglevel options: quiet, normal, verbose loglevel = normal # Limit download speed to the given bytes/second. Set 0 for no limit. # E.g. limit to one megabyte per second #ratelimit = 1000000 ratelimit = 0 # Set number of retries before giving up on a download. Use `inf` for indefinitely many retries. retries = 0 # Subtitles for videos. If enabled and available, automatic and manual subtitles for selected # languages are embedded in the video. #subtitles = en,de subtitles = off # Embed the youtube thumbnail in audio downloads. Transforms the resulting file to m4a, if # enabled. thumbnail = on # Skips livestreams in download mode skiplivestream = yes # Columns printed by --list option, if --columns is not given as well. [TableFormat] id = on date = off channel = on title = on url = off watched = off ``` ## Reporting issues Create a new issue on the [github issue tracker](https://github.com/woefe/ytcc/issues/new). Describe the issue as detailed as possible. **Important**: do not forget to include the output of `ytcc --bug-report-info` in bug reports. ## Development We recommend developing inside a virtualenv. 1. Set up a [virtualenv](https://virtualenv.pypa.io/en/latest/) 2. Install development dependencies: `pip install -r devrequirements.txt` Run the following commands before every pull request and fix the warnings or errors they produce. ```bash mypy ytcc nosetests pylint ytcc pydocstyle ytcc ``` ## Translations Ytcc uses the GNU gettext utilities to manage localization. ### Managing locales Create a new locale with `msginit`. The example below creates a new locale for Polish. ```bash cd po msginit --locale pl ``` Every time the PO template is changed, the locales have to be updated with `msgmerge`. ```bash cd po msgmerge --update de.po ytcc.pot ``` Every time a PO file is created or updated, new strings have to be translated. There are multiple tools available, see the [GNU gettext manual](https://www.gnu.org/software/gettext/manual/gettext.html#Editing). I prefer GTranslator, e.g: ```bash cd po gtranslator de.po ``` ### Updating the PO tempate ```bash xgettext --output=po/ytcc.pot \ --language=Python \ --from-code=utf-8 \ --copyright-holder="Wolfgang Popp" \ --package-name="ytcc" \ --package-version=$(python -c "import ytcc; print(ytcc.__version__)") \ ytcc/{cli,arguments}.py ``` ytcc-1.8.1/completions/000077500000000000000000000000001343616406200150245ustar00rootroot00000000000000ytcc-1.8.1/completions/fish/000077500000000000000000000000001343616406200157555ustar00rootroot00000000000000ytcc-1.8.1/completions/fish/ytcc.fish000066400000000000000000000054641343616406200176030ustar00rootroot00000000000000set -l cmd "ytcc" set -l channel '__fish_contains_opt -s r -s f channel-filter delete-channel' set -l video '__fish_contains_opt -s w -s d -s m watch download mark-watched' function __ytcc_last_flag set -l tokens (commandline -poc) for token in $tokens if test (echo $token | head -c 1) = "-" set last_flag $token end end for arg in $argv if test "x$last_flag" = "x$arg" return 0 end end return 1 end complete -c $cmd -x -l help -s h -d "show help message and exit" complete -c $cmd -f -r -l add-channel -s a -d "add a new channel" complete -c $cmd -f -l list-channels -s c -d "print all subscribed channels" complete -c $cmd -f -l delete-channel -s r -d "unsubscribe from channels" complete -c $cmd -f -l rename -d "rename a channel" complete -c $cmd -f -l update -s u -d "update the videolist" complete -c $cmd -f -l list-unwatched -s l -d "print all of unwatched videos" complete -c $cmd -f -l watch -s w -d "play videos" complete -c $cmd -f -l download -s d -d "download the videos" complete -c $cmd -f -l mark-watched -s m -d "mark videos as watched" complete -c $cmd -f -l channel-filter -s f -d "apply a channel filter" complete -c $cmd -f -l include-watched -s n -d "apply include-watched filter" complete -c $cmd -f -r -l since -s s -d "apply date begin filter" complete -c $cmd -f -r -l to -s t -d "apply date end filter" complete -c $cmd -r -l path -s p -d "set the download path" complete -c $cmd -f -l no-description -s g -d "do not print the video description" complete -c $cmd -f -r -l columns -s o -d "column" -a 'ID Date Channel Title URL Watched all' complete -c $cmd -f -l no-header -d "don't print table header" complete -c $cmd -f -l no-video -s x -d "audio only" complete -c $cmd -f -l disable-interactive -s y -d "automatically play videos without asking" complete -c $cmd -r -l import-from -d "import subscriptions from youtube" complete -c $cmd -r -l export-to -d "export subscriptions as OPML file" complete -c $cmd -x -l cleanup -d "cleanup and shrink database file" complete -c $cmd -x -l version -s v -d "output version information and exit" complete -c $cmd -x -l bug-report-info -d "print versions and exit" complete -c $cmd -f -n '__ytcc_last_flag -r --delete-channel -f --channel-filter' -a "(ytcc --list-channels)" complete -c $cmd -f -n '__ytcc_last_flag -w --watch -d --download -m --mark' -a "(ytcc -lo ID --no-header | tr -d ' ')" complete -c $cmd -f -n '__ytcc_last_flag -o --columns' -a 'ID Date Channel Title URL' ytcc-1.8.1/completions/zsh/000077500000000000000000000000001343616406200156305ustar00rootroot00000000000000ytcc-1.8.1/completions/zsh/_ytcc000066400000000000000000000057411343616406200166630ustar00rootroot00000000000000#compdef ytcc _ytcc_channels() { local _channel_list _channel_list=( "${(@f)$(ytcc -c)}" ) _describe -t values 'channel' _channel_list || compadd "$@" } _ytcc_videos() { local _video_list _video_list=( "${(@f)$(ytcc -lo ID Channel Title --no-header | sed -r "s/ *([0-9]+) *│/\1:/")}" ) _describe -t values 'videos' _video_list || compadd "$@" } _ytcc_mark() { local _video_list _video_list=( "${(@f)$(ytcc -lo ID Channel Title --no-header | sed -r "s/ *([0-9]+) *│/\1:/")}" ) if [[ ${_video_list[1]} == "No videos to list. No videos match the given criteria." ]]; then _video_list=( ) fi _describe -t values 'unwatched videos' _video_list || compadd "$@" } _ytcc() { local context state line local -A opt_args _arguments \ '(-h --help)'{-h,--help}'[show help message and exit]' \ '(-a --add-channel)'{-a,--add-channel}'[add a new channel]:2::' \ '(-c --list-channels)'{-c,--list-channels}'[print a list of all subscribed channels]' \ '(-r --delete-channel)'{-r,--delete-channel}'[unsubscribe from channels]:*: :->channels' \ '(--rename)--rename[rename a channel]:*: :->channels' \ '(-u --update)'{-u,--update}'[update the videolist]' \ '(-l --list)'{-l,--list}'[print a list of videos]' \ '(-w --watch)'{-w,--watch}'[play videos]:*: :->videos' \ '(-d --download)'{-d,--download}'[download the videos]:*: :->videos' \ '(-m --mark-watched)'{-m,--mark-watched}'[mark videos as watched]:*: :->mark' \ '(-f --channel-filter)'{-f,--channel-filter}'[apply a filter]:*: :->channels' \ '(-n --include-watched)'{-n,--list-recent}'[include watched videos to filter]' \ '(-s --since)'{-s,--since}'[set lower limit of date filter]:1::' \ '(-t --to)'{-t,--to}'[set upper limit of date filter]:1::' \ '(-p --path)'{-p,--path}'[set the download path]::download path:_path_files -/' \ '(-g --no-description)'{-g,--no-description}'[do not print the video description]' \ '(-o --columns)'{-o,--columns}'[set which columns will be displayed]:*:columns:(ID Date Channel Title URL Watched all)' \ '(--no-header)--no-header[do not print table header]' \ '(-x --no-video)'{-x,--no-video}'[audio only]' \ '(-y --disable-interactive)'{-y,--yes}'[automatically play videos without asking]' \ '(--import-from)--import-from[import subscriptions from youtube]::subscription file:_path_files -f' \ '(--export-to)--export-to[export subscriptions to OPML]::opml file:_path_files -f' \ '(--cleanup)--cleanup[cleanup and shrink database file]' \ '(-v --version)'{-v,--version}'[output version information and exit]' \ '(--bug-report-info)--bug-report-info[print versions and details]' \ case $state in (channels) _ytcc_channels ;; (videos) _ytcc_videos ;; (mark) _ytcc_mark ;; esac } _ytcc "$@" ytcc-1.8.1/devrequirements.txt000066400000000000000000000002011343616406200164440ustar00rootroot00000000000000# Devtools sqlalchemy-stubs mypy nose pylint pydocstyle # Application dependencies lxml feedparser>=5.2.0 youtube_dl SQLAlchemy ytcc-1.8.1/make-release.sh000077500000000000000000000007061343616406200153650ustar00rootroot00000000000000#!/usr/bin/env bash tagname=$1 if ! echo "$tagname" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+'; then echo "Usage: $0 major.minor.patch" exit 1 fi sed -i -e "s/^__version__ = .*$/__version__ = \"$tagname\"/" ytcc/__init__.py git commit ytcc/__init__.py -m "Release version $tagname" git tag -a "v$tagname" -m "Version $tagname" git show HEAD read -rp "Push changes? Ctrl+c to cancel, Enter to push" git push origin master git push origin "v$tagname" ytcc-1.8.1/mypy.ini000066400000000000000000000000671343616406200141720ustar00rootroot00000000000000[mypy] plugins = sqlmypy ignore_missing_imports = True ytcc-1.8.1/po/000077500000000000000000000000001343616406200131065ustar00rootroot00000000000000ytcc-1.8.1/po/de.po000066400000000000000000000317371343616406200140510ustar00rootroot00000000000000# German translations for YTCC package. # Copyright (C) 2019 Wolfgang Popp # This file is distributed under the same license as the YTCC package. # , 2019. # Wolfgang Popp , 2017-2019. # msgid "" msgstr "" "Project-Id-Version: ytcc 1.7.4\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-03-01 08:57+0100\n" "PO-Revision-Date: 2019-03-01 09:01+0100\n" "Last-Translator: Wolfgang Popp \n" "Language-Team: German \n" "Language: de\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" "X-Generator: Gtranslator 3.30.1\n" #: ytcc/cli.py:52 msgid "The configuration file has errors!" msgstr "Die Konfigurationsdatei enthält Fehler!" #: ytcc/cli.py:60 msgid "ID" msgstr "ID" #: ytcc/cli.py:60 msgid "Date" msgstr "Datum" #: ytcc/cli.py:60 msgid "Channel" msgstr "Kanal" #: ytcc/cli.py:60 msgid "Title" msgstr "Titel" #: ytcc/cli.py:60 msgid "URL" msgstr "URL" #: ytcc/cli.py:60 msgid "Watched" msgstr "Gesehen" #: ytcc/cli.py:88 msgid "Play video" msgstr "Video apspielen" #: ytcc/cli.py:89 msgid "Play audio" msgstr "Tonspur abspielen" #: ytcc/cli.py:90 msgid "Mark as watched" msgstr "Als gesehen markieren" #: ytcc/cli.py:92 msgid "Download audio" msgstr "Tonspur herunterladen" #: ytcc/cli.py:93 msgid "Download video" msgstr "Video herunterladen" #: ytcc/cli.py:151 msgid "Type a valid TAG. for help." msgstr "Gib einen TAG ein. für Hilfe." #: ytcc/cli.py:225 msgid "" " Display this help text.\n" " Set action: Play video.\n" " Set action: Play audio.\n" " Set action: Mark as watched.\n" " Refresh video list.\n" " Set action: Download video.\n" " Set action: Download audio.\n" " Accept first video.\n" " Exit.\n" msgstr "" " Zeigt diese Hilfe an.\n" " Modus wechseln: Video abspielen.\n" " Modus wechseln: Audio abspielen.\n" " Modus wechseln: Als gelesen markieren.\n" " Videoliste aktualisieren.\n" " Modus wechseln: Video herunterladen.\n" " Modus wechseln: Audio herunterladen.\n" " Wählt das oberste Video.\n" " Beenden.\n" #: ytcc/cli.py:235 msgid "Press Enter to continue" msgstr "Enter drücken zum Fortfahren" #: ytcc/cli.py:252 msgid "Video description:" msgstr "Videobeschreibung:" #: ytcc/cli.py:262 #, python-brace-format msgid "Playing \"{video.title}\" by \"{video.channel.displayname}\"..." msgstr "Spiele \"{video.title}\" von \"{video.channel.displayname}\" ab..." #: ytcc/cli.py:266 msgid "" "WARNING: The video player terminated with an error.\n" " The last video is not marked as watched!" msgstr "" "WARNUNG: Der Videoplayer wurde fehlerhaft beendet.\n" " Das Video wurde nicht als gesehen markiert!" #: ytcc/cli.py:299 msgid "Yes" msgstr "Ja" #: ytcc/cli.py:299 msgid "No" msgstr "Nein" #: ytcc/cli.py:318 #, python-brace-format msgid "Downloading \"{video.title}\" by \"{video.channel.displayname}\"..." msgstr "Lade \"{video.title}\" von \"{video.channel.displayname}\" herunter..." #: ytcc/cli.py:321 msgid "An Error occured while downloading the video" msgstr "Während des Herunterladens ist ein Fehler aufgetreten" #: ytcc/cli.py:329 msgid "No videos were marked as watched" msgstr "Keine Videos wurden als gesehen markiert" #: ytcc/cli.py:335 msgid "Following videos were marked as watched:" msgstr "Die Folgenden Videos wurden als gesehen markiert:" #: ytcc/cli.py:346 msgid "No videos to watch. No videos match the given criteria." msgstr "" "Keine Videos zum abspielen gefunden. Die gegeben Suchkriterien treffen auf " "kein Video zu." #: ytcc/cli.py:363 msgid "Updating channels..." msgstr "Aktualisiere Kanäle..." #: ytcc/cli.py:371 msgid "No videos to list. No videos match the given criteria." msgstr "" "Keine Videos zum auflisten gefunden. Die gegeben Suchkriterien treffen auf " "kein Video zu." #: ytcc/cli.py:380 msgid "No channels added, yet." msgstr "Bisher wurden noch keine Kanäle abboniert" #: ytcc/cli.py:391 msgid "{!r} is not a valid YouTube URL" msgstr "{!r} ist keine gültige YouTube URL" #: ytcc/cli.py:393 msgid "You are already subscribed to {!r}" msgstr "Der Kanal {!r} ist bereits abonniert" #: ytcc/cli.py:395 msgid "The channel {!r} does not exist" msgstr "Der Kanal {!r} existiert nicht" #: ytcc/cli.py:408 msgid "Error: The given channel does not exist." msgstr "Fehler: Der angegebene Kanal existiert nicht." #: ytcc/cli.py:410 msgid "Error: The new name already exists." msgstr "Fehler: Der neue Name existiert bereits." #: ytcc/cli.py:415 msgid "Cleaning up database..." msgstr "Bereinige die Datenbank..." #: ytcc/cli.py:421 msgid "Importing..." msgstr "Importieren..." #: ytcc/cli.py:424 msgid "Subscriptions" msgstr "Abonnements" #: ytcc/cli.py:430 msgid "The given file is not valid YouTube export file" msgstr "Die gegebene Datei ist keine gültige YouTube Export Datei" #: ytcc/cli.py:584 msgid "Bye..." msgstr "Tschüss..." #: ytcc/arguments.py:29 msgid "{!r} is not a directory" msgstr "{!r} ist kein Verzeichnis" #: ytcc/arguments.py:39 msgid "{!r} is not a valid date" msgstr "{!r} ist kein gültiges Datum" #: ytcc/arguments.py:45 msgid "" "ytcc is a commandline YouTube client that keeps track of your favorite " "channels. The --list, --watch, --download, --mark-watched options can be " "combined with filter options --channel-filter, --include-watched, --since, --" "to" msgstr "" "ytcc ist ein YouTube Client für die Kommandozeile, der deine Lieblingskanäle " "verwalten kann. Die --list, --watch, --download, --mark-watched Optionen " "können mit den Filteroptionen --channel-filter, --include-watched, --since, " "--to kombiniert werden" #: ytcc/arguments.py:51 msgid "" "add a new channel. NAME is the name displayed by ytcc. URL is the url of the " "channel's front page or the URL of any video published by the channel" msgstr "" "abonniert einen neuen Kanal. NAME ist der von ytcc angezeigte Name des " "Kanals. URL ist die URL zur Hauptseite des Kanals oder die URL zu " "irgendeinem Video des Kanals" #: ytcc/arguments.py:58 msgid "print a list of all subscribed channels" msgstr "zeigt eine Liste aller abonnierten Kanäle" #: ytcc/arguments.py:62 msgid "unsubscribe from the channel identified by 'NAME'" msgstr "deabonniert den gegebenen Kanal" #: ytcc/arguments.py:68 msgid "rename channel 'OLDNAME' to 'NEWNAME'" msgstr "benennt den Kanal 'OLDNAME' in 'NEWNAME' um" #: ytcc/arguments.py:74 msgid "update the video list" msgstr "aktualisiert die Videoliste" #: ytcc/arguments.py:78 msgid "" "print a list of videos that match the criteria given by the filter options" msgstr "" "zeigt eine Liste von Videos an, die den gegebenen Kriterien entsprechen" #: ytcc/arguments.py:83 msgid "" "play the videos identified by 'ID'. Omitting the ID will play all videos " "specified by the filter options" msgstr "" "spielt das Video mit der gegebenen 'ID' ab. Wird keine ID angegeben, werden " "alle Videos abgespielt, die auf die Filteroptionen zutreffen" #: ytcc/arguments.py:90 msgid "" "download the videos identified by 'ID'. The videos are saved in $HOME/" "Downloads by default. Omitting the ID will download all videos that match " "the criteria given by the filter options" msgstr "" "lädt das Video mit der gegebenen 'ID' herunter. Die Videos werden " "standardmäßig im $HOME/Downloads Verzeichnis gespeichert. Wird keine ID " "angegeben, werden alle Videos heruntergeladen, die auf die Filteroptionen " "zutreffen" #: ytcc/arguments.py:98 msgid "" "mark videos identified by ID as watched. Omitting the ID will mark all " "videos that match the criteria given by the filter options as watched" msgstr "" "markiert das Video mit der gegebenen 'ID' als gesehen. Wird keine ID " "angegeben, werden alle Videos als gesehen markiert, die auf die " "Filteroptionen zutreffen" #: ytcc/arguments.py:106 msgid "" "plays, lists, marks, downloads only videos from channels defined in the " "filter" msgstr "" "filtert nach den gegebenen Kanälen. Es werden also nur Videos von den " "gegebenen Kanälen abgespielt / heruntergeladen / aufgelistet / als gesehen " "markiert" #: ytcc/arguments.py:113 msgid "include already watched videos to filter rules" msgstr "" "standardmäßig werden bei Suchen und den Filteroptionen bereits gesehene " "Videos ignoriert. Diese Option ermöglicht, dass auch bereits gesehene Videos " "berücksichtigt werden." #: ytcc/arguments.py:117 msgid "includes only videos published after the given date" msgstr "" "filtert nach Videos, die nach dem gegebenen Datum veröffentlicht wurden" #: ytcc/arguments.py:122 msgid "includes only videos published before the given date" msgstr "filtert nach Videos, die vor dem gegebenen Datum veröffentlicht wurden" #: ytcc/arguments.py:127 msgid "set the download path to PATH" msgstr "setzt den Download Pfad" #: ytcc/arguments.py:132 msgid "do not print the video description before playing the video" msgstr "" "deaktiviert die Videobeschreibung, die vor dem Abspielen des Videos " "angezeigt wird" #: ytcc/arguments.py:136 #, python-brace-format msgid "" "specifies which columns will be printed when listing videos. COL can be any " "of {columns}. All columns can be enabled with 'all'" msgstr "" "legt fest welche Spalten in der Tabelle der Videoauflistung angezeigt " "werden. Mögliche Spalten sind: {columns}. Alle Spalten können mit 'all' " "aktiviert werden" #: ytcc/arguments.py:144 msgid "do not print the header of the table when listing videos" msgstr "deaktiviert die Kopfzeile der Tabelle der Videoauflistung" #: ytcc/arguments.py:148 msgid "plays or downloads only the audio part of a video" msgstr "" "spielt nur die Tonspur der Videos ab bzw. lädt nur die Tonspur herunter" #: ytcc/arguments.py:152 msgid "disables the interactive mode" msgstr "deaktiviert den interaktiven Modus" #: ytcc/arguments.py:156 msgid "" "import YouTube channels from YouTube's subscription export (available at " "https://www.youtube.com/subscription_manager)" msgstr "" "importiert die YouTube Kanäle aus YouTubes Abo Export (verfügbar hier: " "https://www.youtube.com/subscription_manager)" #: ytcc/arguments.py:162 msgid "export YouTube channels in opml format" msgstr "exportiert abonnierte Kanäle als OPML Datei" #: ytcc/arguments.py:167 msgid "" "removes old videos from the database and shrinks the size of the database " "file" msgstr "" "löscht alte Videos aus der Datenbank und reduziert die Größe der " "Datenbankdatei" #: ytcc/arguments.py:172 msgid "output version information and exit" msgstr "Versionsinformationen anzeigen und beenden" #: ytcc/arguments.py:176 msgid "print info to include in a bug report" msgstr "zeigt Informationen für einen Bugreport" #~ msgid "Available commands:" #~ msgstr "Verfügbare Befehle" #~ msgid "print this help" #~ msgstr "zeigt diese Hilfe an" #~ msgid "do not play the video" #~ msgstr "spielt das Video nicht ab" #~ msgid "mark the video watched without playing it" #~ msgstr "markiert das Video als gesehen ohne es abzuspielen" #~ msgid "play only the audio track of the video" #~ msgstr "spielt nur die Tonspur des Videos ab" #~ msgid "download the audio track of the video" #~ msgstr "lädt die Tonspur des Videos herunter" #~ msgid "exit ytcc" #~ msgstr "beendet ytcc" #~ msgid "Play video \"{video.title}\" by \"{video.channelname}\"?" #~ msgstr "" #~ "Soll das Video \"{video.title}\" von \"{video.channelname}\" abgespielt " #~ "werden?" #~ msgid "'{cmd}' is an invalid command. Type 'help' for more info.\n" #~ msgstr "" #~ "'{cmd} ist kein gültiger Befehl. Tippe 'help' für mehr Informationen\n" #~ msgid "Type a valid TAG. to exit. accepts first video." #~ msgstr "Tippe einen TAG! beendet. wählt das erste Video." #~ msgid "" #~ "searches for the given PATTERN. The pattern can specify one of the three " #~ "columns 'channel', 'title', 'description'. If no column is specified, all " #~ "columns are searched. The pattern can also specify '*' wildcards. " #~ "Example: --search 'title:box*' will find all video that have a word that " #~ "starts with 'box' in their title. If this flag is enabled, the -f, -n, -" #~ "s, -t flags will be ignored." #~ msgstr "" #~ "sucht nach dem gegebenen PATTERN in der lokalen Datenbank. In dem " #~ "Suchbegriff kann eine der drei Spalten 'channel', 'title' oder " #~ "'description' angegeben werden. Falls keine Spalte angegeben wurde, " #~ "werden alle Spalten durchsucht. Der Suchbegriff kann auch das '*' " #~ "Platzhaltersymbol enthalten. Beispiel: --search 'title:box*' sucht nach " #~ "Videos, die in ihrem Titel ein Wort enthalten, das mit 'box' beginnt. " #~ "Wenn diese Option aktiviert ist, werden die -f, -n, -s und -t Optionen " #~ "ignoriert." #~ msgid "automatically answer all questions with yes" #~ msgstr "beantwortet alle Fragen automatisch mit 'yes'" #~ msgid "an alias for 'play-video'" #~ msgstr "ein Alias für 'play-video'" #~ msgid "The video has not been downloaded due to the following error:" #~ msgstr "" #~ "Das Video konnte aufgrund des folgenden Fehlers nicht heruntergeladen " #~ "werden:" ytcc-1.8.1/po/ytcc.pot000066400000000000000000000147241343616406200146040ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR Wolfgang Popp # This file is distributed under the same license as the ytcc package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: ytcc 1.8.0\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-03-01 08:57+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: ytcc/cli.py:52 msgid "The configuration file has errors!" msgstr "" #: ytcc/cli.py:60 msgid "ID" msgstr "" #: ytcc/cli.py:60 msgid "Date" msgstr "" #: ytcc/cli.py:60 msgid "Channel" msgstr "" #: ytcc/cli.py:60 msgid "Title" msgstr "" #: ytcc/cli.py:60 msgid "URL" msgstr "" #: ytcc/cli.py:60 msgid "Watched" msgstr "" #: ytcc/cli.py:88 msgid "Play video" msgstr "" #: ytcc/cli.py:89 msgid "Play audio" msgstr "" #: ytcc/cli.py:90 msgid "Mark as watched" msgstr "" #: ytcc/cli.py:92 msgid "Download audio" msgstr "" #: ytcc/cli.py:93 msgid "Download video" msgstr "" #: ytcc/cli.py:151 msgid "Type a valid TAG. for help." msgstr "" #: ytcc/cli.py:225 msgid "" " Display this help text.\n" " Set action: Play video.\n" " Set action: Play audio.\n" " Set action: Mark as watched.\n" " Refresh video list.\n" " Set action: Download video.\n" " Set action: Download audio.\n" " Accept first video.\n" " Exit.\n" msgstr "" #: ytcc/cli.py:235 msgid "Press Enter to continue" msgstr "" #: ytcc/cli.py:252 msgid "Video description:" msgstr "" #: ytcc/cli.py:262 #, python-brace-format msgid "Playing \"{video.title}\" by \"{video.channel.displayname}\"..." msgstr "" #: ytcc/cli.py:266 msgid "" "WARNING: The video player terminated with an error.\n" " The last video is not marked as watched!" msgstr "" #: ytcc/cli.py:299 msgid "Yes" msgstr "" #: ytcc/cli.py:299 msgid "No" msgstr "" #: ytcc/cli.py:318 #, python-brace-format msgid "Downloading \"{video.title}\" by \"{video.channel.displayname}\"..." msgstr "" #: ytcc/cli.py:321 msgid "An Error occured while downloading the video" msgstr "" #: ytcc/cli.py:329 msgid "No videos were marked as watched" msgstr "" #: ytcc/cli.py:335 msgid "Following videos were marked as watched:" msgstr "" #: ytcc/cli.py:346 msgid "No videos to watch. No videos match the given criteria." msgstr "" #: ytcc/cli.py:363 msgid "Updating channels..." msgstr "" #: ytcc/cli.py:371 msgid "No videos to list. No videos match the given criteria." msgstr "" #: ytcc/cli.py:380 msgid "No channels added, yet." msgstr "" #: ytcc/cli.py:391 msgid "{!r} is not a valid YouTube URL" msgstr "" #: ytcc/cli.py:393 msgid "You are already subscribed to {!r}" msgstr "" #: ytcc/cli.py:395 msgid "The channel {!r} does not exist" msgstr "" #: ytcc/cli.py:408 msgid "Error: The given channel does not exist." msgstr "" #: ytcc/cli.py:410 msgid "Error: The new name already exists." msgstr "" #: ytcc/cli.py:415 msgid "Cleaning up database..." msgstr "" #: ytcc/cli.py:421 msgid "Importing..." msgstr "" #: ytcc/cli.py:424 msgid "Subscriptions" msgstr "" #: ytcc/cli.py:430 msgid "The given file is not valid YouTube export file" msgstr "" #: ytcc/cli.py:584 msgid "Bye..." msgstr "" #: ytcc/arguments.py:29 msgid "{!r} is not a directory" msgstr "" #: ytcc/arguments.py:39 msgid "{!r} is not a valid date" msgstr "" #: ytcc/arguments.py:45 msgid "" "ytcc is a commandline YouTube client that keeps track of your favorite " "channels. The --list, --watch, --download, --mark-watched options can be " "combined with filter options --channel-filter, --include-watched, --since, --" "to" msgstr "" #: ytcc/arguments.py:51 msgid "" "add a new channel. NAME is the name displayed by ytcc. URL is the url of the " "channel's front page or the URL of any video published by the channel" msgstr "" #: ytcc/arguments.py:58 msgid "print a list of all subscribed channels" msgstr "" #: ytcc/arguments.py:62 msgid "unsubscribe from the channel identified by 'NAME'" msgstr "" #: ytcc/arguments.py:68 msgid "rename channel 'OLDNAME' to 'NEWNAME'" msgstr "" #: ytcc/arguments.py:74 msgid "update the video list" msgstr "" #: ytcc/arguments.py:78 msgid "" "print a list of videos that match the criteria given by the filter options" msgstr "" #: ytcc/arguments.py:83 msgid "" "play the videos identified by 'ID'. Omitting the ID will play all videos " "specified by the filter options" msgstr "" #: ytcc/arguments.py:90 msgid "" "download the videos identified by 'ID'. The videos are saved in $HOME/" "Downloads by default. Omitting the ID will download all videos that match " "the criteria given by the filter options" msgstr "" #: ytcc/arguments.py:98 msgid "" "mark videos identified by ID as watched. Omitting the ID will mark all " "videos that match the criteria given by the filter options as watched" msgstr "" #: ytcc/arguments.py:106 msgid "" "plays, lists, marks, downloads only videos from channels defined in the " "filter" msgstr "" #: ytcc/arguments.py:113 msgid "include already watched videos to filter rules" msgstr "" #: ytcc/arguments.py:117 msgid "includes only videos published after the given date" msgstr "" #: ytcc/arguments.py:122 msgid "includes only videos published before the given date" msgstr "" #: ytcc/arguments.py:127 msgid "set the download path to PATH" msgstr "" #: ytcc/arguments.py:132 msgid "do not print the video description before playing the video" msgstr "" #: ytcc/arguments.py:136 #, python-brace-format msgid "" "specifies which columns will be printed when listing videos. COL can be any " "of {columns}. All columns can be enabled with 'all'" msgstr "" #: ytcc/arguments.py:144 msgid "do not print the header of the table when listing videos" msgstr "" #: ytcc/arguments.py:148 msgid "plays or downloads only the audio part of a video" msgstr "" #: ytcc/arguments.py:152 msgid "disables the interactive mode" msgstr "" #: ytcc/arguments.py:156 msgid "" "import YouTube channels from YouTube's subscription export (available at " "https://www.youtube.com/subscription_manager)" msgstr "" #: ytcc/arguments.py:162 msgid "export YouTube channels in opml format" msgstr "" #: ytcc/arguments.py:167 msgid "" "removes old videos from the database and shrinks the size of the database " "file" msgstr "" #: ytcc/arguments.py:172 msgid "output version information and exit" msgstr "" #: ytcc/arguments.py:176 msgid "print info to include in a bug report" msgstr "" ytcc-1.8.1/scripts/000077500000000000000000000000001343616406200141575ustar00rootroot00000000000000ytcc-1.8.1/scripts/ytcc000077700000000000000000000000001343616406200165662../ytcc.pyustar00rootroot00000000000000ytcc-1.8.1/setup.py000077500000000000000000000021061343616406200142040ustar00rootroot00000000000000#!/usr/bin/env python3 from glob import glob from pathlib import Path from subprocess import run from setuptools import setup import ytcc def compile_translations(): po_files = glob("po/*.po") package_data = [] for file in po_files: lang = file[3:][:-3] package_data_file = "resources/locale/" + lang + "/LC_MESSAGES/ytcc.mo" out_file = Path("ytcc").joinpath(package_data_file) out_file.parent.mkdir(parents=True, exist_ok=True) if run(["msgfmt", "-o", str(out_file), file]).returncode == 0: package_data.append(package_data_file) return package_data setup( name='ytcc', description='A YouTube subscription tool', long_description=ytcc.__doc__, version=ytcc.__version__, url='https://github.com/woefe/ytcc', author=ytcc.__author__, author_email=ytcc.__email__, license=ytcc.__license__, scripts=['scripts/ytcc'], packages=['ytcc'], install_requires=['lxml', 'feedparser>=5.2.0', 'youtube_dl', 'SQLAlchemy'], package_data={ 'ytcc': compile_translations() }, ) ytcc-1.8.1/snapcraft.yaml000066400000000000000000000005621343616406200153400ustar00rootroot00000000000000name: ytcc version: git summary: ytcc - The YouTube channel checker description: | Command Line tool to keep track of your favourite YouTube channels without signing up for a Google account. grade: devel confinement: devmode parts: ytcc: source: . plugin: python python-version: python3 stage-packages: [mpv] apps: ytcc: command: bin/ytcc ytcc-1.8.1/test/000077500000000000000000000000001343616406200134475ustar00rootroot00000000000000ytcc-1.8.1/test/__init__.py000066400000000000000000000000001343616406200155460ustar00rootroot00000000000000ytcc-1.8.1/test/data/000077500000000000000000000000001343616406200143605ustar00rootroot00000000000000ytcc-1.8.1/test/data/subscriptions000066400000000000000000000240351343616406200172160ustar00rootroot00000000000000 ytcc-1.8.1/test/data/ytcc_test.conf000066400000000000000000000004211343616406200172250ustar00rootroot00000000000000[YTCC] DBPath = /tmp/ytcc_test/db.sqlite DownloadDir = /tmp/ytcc_test/download MpvFlags = --really-quiet --ytdl --ytdl-format=bestvideo[height<=?1080]+bestaudio/best YtdlOutputTemplate = %(title)s.%(ext)s [TableFormat] title = on channel = on id = on date = off url = off ytcc-1.8.1/test/test_database.py000066400000000000000000000101021343616406200166160ustar00rootroot00000000000000from unittest import TestCase import sqlalchemy from nose.tools import raises from ytcc.database import Database, Video, Channel def init_db(): insert_list = [ Video(yt_videoid="0", title="title1", description="description1", publisher="id_publisher1", publish_date=1488286166, watched=False), Video(yt_videoid="0", title="title1", description="description1", publisher="id_publisher1", publish_date=1488286167, watched=False), Video(yt_videoid="1", title="title2", description="description1", publisher="id_publisher1", publish_date=1488286168, watched=False), Video(yt_videoid="1", title="title2", description="description2", publisher="id_publisher2", publish_date=1488286170, watched=False), Video(yt_videoid="2", title="title3", description="description3", publisher="id_publisher2", publish_date=1488286171, watched=False) ] db = Database(":memory:") db.add_channel(Channel(displayname="publisher1", yt_channelid="id_publisher1")) db.add_channel(Channel(displayname="publisher2", yt_channelid="id_publisher2")) db.add_channel(Channel(displayname="publisher3", yt_channelid="id_publisher3")) db.add_videos(insert_list) return db class DatabaseTest(TestCase): @raises(sqlalchemy.exc.IntegrityError) def test_add_channel_duplicate(self): db = Database(":memory:") db.add_channel(Channel(displayname="Webdriver Torso", yt_channelid="UCsLiV4WJfkTEHH0b9PmRklw")) db.add_channel(Channel(displayname="Webdriver Torso2", yt_channelid="UCsLiV4WJfkTEHH0b9PmRklw")) def test_add_and_get_channels(self): db = Database(":memory:") db.add_channel(Channel(displayname="Webdriver Torso", yt_channelid="UCsLiV4WJfkTEHH0b9PmRklw")) db.add_channel(Channel(displayname="Webdriver YPP", yt_channelid="UCxexYYtOetqikZqriLuTS-g")) channels = db.get_channels() self.assertEqual(len(channels), 2) self.assertEqual(channels[0].displayname, "Webdriver Torso") self.assertEqual(channels[0].yt_channelid, "UCsLiV4WJfkTEHH0b9PmRklw") self.assertEqual(channels[1].displayname, "Webdriver YPP") self.assertEqual(channels[1].yt_channelid, "UCxexYYtOetqikZqriLuTS-g") def test_add_and_get_videos(self): db = init_db() videos = db.session.query(Video).all() self.assertEqual(len(videos), 3) self.assertEqual(videos[0].yt_videoid, "0") self.assertEqual(videos[1].yt_videoid, "1") self.assertEqual(videos[2].yt_videoid, "2") def test_delete_channels(self): db = init_db() db.delete_channels(["publisher1", "publisher2"]) channels = db.get_channels() self.assertEqual(len(channels), 1) self.assertEqual(channels[0].displayname, "publisher3") def test_resolve_video_id(self): db = init_db() video = db.resolve_video_id(1) expected = Video(id=1, yt_videoid="0", title="title1", description="description1", publisher="id_publisher1", publish_date=1488286166.0, watched=False) self.eq_video(video, expected) def test_mark_watched(self): db = init_db() for video in db.resolve_video_ids([2, 3]): video.watched = True videos = db.session.query(Video).filter(Video.watched == False).all() expected = Video(id=1, yt_videoid="0", title="title1", description="description1", publisher="id_publisher1", publish_date=1488286166.0, watched=False) self.assertEqual(len(videos), 1) self.eq_video(videos[0], expected) def eq_video(self, video: Video, expected: Video) -> None: self.assertEqual(video.id, expected.id) self.assertEqual(video.yt_videoid, expected.yt_videoid) self.assertEqual(video.title, expected.title) self.assertEqual(video.description, expected.description) self.assertEqual(video.publish_date, expected.publish_date) self.assertEqual(video.publisher, expected.publisher) self.assertEqual(video.watched, expected.watched) ytcc-1.8.1/test/test_ytcc.py000066400000000000000000000211701343616406200160230ustar00rootroot00000000000000from unittest import TestCase import os from datetime import datetime from ytcc.core import BadURLException from ytcc.core import DuplicateChannelException from ytcc.core import Ytcc from ytcc.database import Channel, Video class TestYtcc(TestCase): def setUp(self): self.current_dir = os.path.dirname(__file__) self.ytcc = Ytcc(os.path.join(self.current_dir, "data/ytcc_test.conf")) self.db_conn = self.ytcc.database def tearDown(self): self.db_conn.session.flush() self.db_conn.engine.execute("delete from video") self.db_conn.engine.execute("delete from channel") def test_add_channel_duplicate(self): ytcc = self.ytcc ytcc.add_channel("Webdriver Torso", "https://www.youtube.com/channel/UCsLiV4WJfkTEHH0b9PmRklw") self.assertRaises(DuplicateChannelException, ytcc.add_channel, "Fail", "https://www.youtube.com/channel/UCsLiV4WJfkTEHH0b9PmRklw") def test_add_channel_bad_url(self): ytcc = self.ytcc self.assertRaises(BadURLException, ytcc.add_channel, "Fail", "yotube.com/channel/UCsLiV4WJfkTEHH0b9PmRklw") def test_add_and_get_channels(self): ytcc = self.ytcc ytcc.add_channel("Webdriver Torso", "https://www.youtube.com/channel/UCsLiV4WJfkTEHH0b9PmRklw") ytcc.add_channel("Webdriver YPP", "youtube.com/channel/UCxexYYtOetqikZqriLuTS-g") channels = ytcc.get_channels() self.assertEqual(len(channels), 2) self.assertEqual(channels[0].displayname, "Webdriver Torso") self.assertEqual(channels[1].displayname, "Webdriver YPP") def test_import_channels(self): ytcc = self.ytcc with open(os.path.join(self.current_dir, "data/subscriptions")) as f: ytcc.import_channels(f) self.assertEqual(len(ytcc.get_channels()), 58) class TestYtccPreparedChannels(TestCase): def setUp(self): self.current_dir = os.path.dirname(__file__) self.ytcc = Ytcc(os.path.join(self.current_dir, "data/ytcc_test.conf")) self.db_conn = self.ytcc.database self.db_conn.engine.execute("delete from video") self.db_conn.engine.execute("delete from channel") self.db_conn.add_channel(Channel(displayname="Webdriver Torso", yt_channelid="UCsLiV4WJfkTEHH0b9PmRklw")) self.db_conn.add_channel(Channel(displayname="Webdriver YPP", yt_channelid="UCxexYYtOetqikZqriLuTS-g")) def tearDown(self): self.db_conn.session.commit() self.db_conn.engine.execute("delete from video") self.db_conn.engine.execute("delete from channel") def test_update_all(self): ytcc = self.ytcc ytcc.update_all() self.assertTrue(len(ytcc.list_videos()) > 10) def test_delete_channels(self): ytcc = self.ytcc ytcc.delete_channels(["Webdriver Torso"]) channels = ytcc.get_channels() self.assertEqual(len(channels), 1) self.assertEqual(channels[0].displayname, "Webdriver YPP") class TestYtccPreparedVideos(TestCase): def setUp(self): self.current_dir = os.path.dirname(__file__) self.ytcc = Ytcc(os.path.join(self.current_dir, "data/ytcc_test.conf")) self.db_conn = self.ytcc.database insert_list = [ Video(yt_videoid="V-ozGFl3Jks", title="tmptYnCut", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488348731.0, watched=True), Video(yt_videoid="a1gOeiyIqPs", title="tmp99Yc1l", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488348519.0, watched=True), Video(yt_videoid="0ounUgOrcqo", title="tmppfXKp6", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488345630.0, watched=True), Video(yt_videoid="7mckB-NdKWY", title="tmpiM62pN", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488345565.0, watched=False), Video(yt_videoid="RmRPt93uAsQ", title="tmpIXBgjd", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488344217.0, watched=False), Video(yt_videoid="nDPy3RyKdrg", title="tmpwA0TjG", description="", publisher="UCsLiV4WJfkTEHH0b9PmRklw", publish_date=1488343000.0, watched=False), Video(yt_videoid="L0_F805qUIM", title="tmpKDOkro", description="", publisher="UCxexYYtOetqikZqriLuTS-g", publish_date=1488344253.0, watched=True), Video(yt_videoid="lXWrdlDEzQs", title="tmpEvCR4s", description="", publisher="UCxexYYtOetqikZqriLuTS-g", publish_date=1488343152.0, watched=True), Video(yt_videoid="cCnXsCQNkr8", title="tmp1rpsWK", description="", publisher="UCxexYYtOetqikZqriLuTS-g", publish_date=1488343046.0, watched=True), Video(yt_videoid="rSxVs0XeQa4", title="tmpc5Y2pd", description="", publisher="UCxexYYtOetqikZqriLuTS-g", publish_date=1488342015.0, watched=False), Video(yt_videoid="gQAsWrGfsrw", title="tmpn1M1Oa", description="", publisher="UCxexYYtOetqikZqriLuTS-g", publish_date=1488341324.0, watched=False), ] self.db_conn.session.execute("delete from video") self.db_conn.session.execute("delete from channel") self.db_conn.add_channel(Channel(displayname="Webdriver Torso", yt_channelid="UCsLiV4WJfkTEHH0b9PmRklw")) self.db_conn.add_channel(Channel(displayname="Webdriver YPP", yt_channelid="UCxexYYtOetqikZqriLuTS-g")) self.db_conn.add_videos(insert_list) self.video = self.db_conn.session.query(Video).filter(Video.title == "tmpIXBgjd").one() self.video_id = self.video.id def tearDown(self): self.db_conn.session.commit() self.db_conn.session.execute("delete from video") self.db_conn.session.execute("delete from channel") self.db_conn.session.commit() def test_list_videos_no_filter(self): ytcc = self.ytcc videos = ytcc.list_videos() self.assertEqual(len(videos), 5) titles = set([v.title for v in videos]) expected = {"tmpiM62pN", "tmpIXBgjd", "tmpwA0TjG", "tmpc5Y2pd", "tmpn1M1Oa"} self.assertSetEqual(set(titles), expected) def test_list_videos_channel_filter(self): ytcc = self.ytcc ytcc.set_channel_filter(["Webdriver Torso"]) videos = ytcc.list_videos() self.assertEqual(len(videos), 3) self.assertEqual(videos[0].channel.displayname, "Webdriver Torso") self.assertEqual(videos[1].channel.displayname, "Webdriver Torso") self.assertEqual(videos[2].channel.displayname, "Webdriver Torso") def test_list_videos_watched_filter(self): ytcc = self.ytcc ytcc.set_include_watched_filter() videos = ytcc.list_videos() self.assertEqual(len(videos), 11) def test_list_videos_date_filter(self): ytcc = self.ytcc ytcc.set_date_begin_filter(datetime.fromtimestamp(1488343000.0)) ytcc.set_date_end_filter(datetime.fromtimestamp(1488345000.0)) videos = ytcc.list_videos() self.assertEqual(len(videos), 1) self.assertEqual(videos[0].title, "tmpIXBgjd") def test_list_videos_combined_filters(self): ytcc = self.ytcc ytcc.set_date_begin_filter(datetime.fromtimestamp(1488343000.0)) ytcc.set_date_end_filter(datetime.fromtimestamp(1488346000.0)) ytcc.set_include_watched_filter() ytcc.set_channel_filter(["Webdriver Torso"]) videos = ytcc.list_videos() expected = {"tmppfXKp6", "tmpiM62pN", "tmpIXBgjd"} titles = set([v.title for v in videos]) self.assertEqual(len(videos), 3) self.assertSetEqual(titles, expected) def test_resolve_video_ids(self): ytcc = self.ytcc ytcc.set_video_id_filter([self.video_id]) videos = ytcc.list_videos() self.assertEqual(len(videos), 1) self.assertEqual(videos[0].title, "tmpIXBgjd") def test_play_video(self): ytcc = self.ytcc ytcc.set_video_id_filter([self.video_id]) videos = ytcc.list_videos() ytcc.play_video(videos[0]) self.assertTrue(videos[0].watched) def test_download_videos(self): ytcc = self.ytcc self.assertTrue(ytcc.download_video(self.video)) self.assertTrue(self.video.watched) self.assertTrue(os.path.isfile(os.path.join(ytcc.config.download_dir, "tmpIXBgjd.webm"))) def test_mark_all_watched(self): ytcc = self.ytcc videos = ytcc.list_videos() for v in videos: v.watched = True videos = ytcc.list_videos() self.assertEqual(len(videos), 0) ytcc-1.8.1/ytcc.py000077500000000000000000000000711343616406200140050ustar00rootroot00000000000000#!/usr/bin/env python3 from ytcc.cli import main main() ytcc-1.8.1/ytcc/000077500000000000000000000000001343616406200134325ustar00rootroot00000000000000ytcc-1.8.1/ytcc/__init__.py000066400000000000000000000025131343616406200155440ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . """The YouTube channel checker. Command Line tool to keep track of your favourite YouTube channels without signing up for a Google account. """ __license__ = "GPLv3" __version__ = "1.8.1" __author__ = __maintainer__ = "Wolfgang Popp" __email__ = "mail@wolfgang-popp.de" from pathlib import Path import gettext import sys def _get_translations_path() -> str: path = Path(__file__) path = path.parent.joinpath("resources", "locale") if path.is_dir(): return str(path) return sys.prefix + "/share/locale" gettext.bindtextdomain("ytcc", _get_translations_path()) gettext.textdomain("ytcc") _ = gettext.gettext ytcc-1.8.1/ytcc/arguments.py000066400000000000000000000166401343616406200160200ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . import argparse import os from datetime import datetime import ytcc.cli from ytcc import _ def is_directory(string: str) -> str: if not os.path.isdir(string): msg = _("{!r} is not a directory").format(string) raise argparse.ArgumentTypeError(msg) return string def is_date(string: str) -> datetime: try: return datetime.strptime(string, "%Y-%m-%d") except ValueError: msg = _("{!r} is not a valid date").format(string) raise argparse.ArgumentTypeError(msg) def get_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description=_("ytcc is a commandline YouTube client that keeps track of your favorite " "channels. The --list, --watch, --download, --mark-watched options can be " "combined with filter options --channel-filter, --include-watched, --since," " --to")) parser.add_argument("-a", "--add-channel", help=_("add a new channel. NAME is the name displayed by ytcc. URL is the " "url of the channel's front page or the URL of any video published " "by the channel"), nargs=2, metavar=("NAME", "URL")) parser.add_argument("-c", "--list-channels", help=_("print a list of all subscribed channels"), action="store_true") parser.add_argument("-r", "--delete-channel", help=_("unsubscribe from the channel identified by 'NAME'"), metavar="NAME", nargs='+', type=str) parser.add_argument("--rename", help=_("rename channel 'OLDNAME' to 'NEWNAME'"), metavar=("OLDNAME", "NEWNAME"), nargs=2, type=str) parser.add_argument("-u", "--update", help=_("update the video list"), action="store_true") parser.add_argument("-l", "--list", help=_("print a list of videos that match the criteria given by the " "filter options"), action="store_true") parser.add_argument("-w", "--watch", help=_("play the videos identified by 'ID'. Omitting the ID will play all " "videos specified by the filter options"), nargs='*', type=int, metavar="ID") parser.add_argument("-d", "--download", help=_("download the videos identified by 'ID'. The videos are saved " "in $HOME/Downloads by default. Omitting the ID will download " "all videos that match the criteria given by the filter options"), nargs="*", type=int, metavar="ID") parser.add_argument("-m", "--mark-watched", help=_("mark videos identified by ID as watched. Omitting the ID will mark" " all videos that match the criteria given by the filter options as " "watched"), nargs='*', type=int, metavar="ID") parser.add_argument("-f", "--channel-filter", help=_("plays, lists, marks, downloads only videos from channels defined " "in the filter"), nargs='+', type=str, metavar="NAME") parser.add_argument("-n", "--include-watched", help=_("include already watched videos to filter rules"), action="store_true") parser.add_argument("-s", "--since", help=_("includes only videos published after the given date"), metavar="YYYY-MM-DD", type=is_date) parser.add_argument("-t", "--to", help=_("includes only videos published before the given date"), metavar="YYYY-MM-DD", type=is_date) parser.add_argument("-p", "--path", help=_("set the download path to PATH"), metavar="PATH", type=is_directory) parser.add_argument("-g", "--no-description", help=_("do not print the video description before playing the video"), action="store_true") parser.add_argument("-o", "--columns", help=_("specifies which columns will be printed when listing videos. COL " "can be any of {columns}. All columns can be enabled with " "'all'").format(columns=ytcc.cli.TABLE_HEADER), nargs='+', metavar="COL", choices=["all", *ytcc.cli.TABLE_HEADER]) parser.add_argument("--no-header", help=_("do not print the header of the table when listing videos"), action="store_true") parser.add_argument("-x", "--no-video", help=_("plays or downloads only the audio part of a video"), action="store_true") parser.add_argument("-y", "--disable-interactive", help=_("disables the interactive mode"), action="store_true") parser.add_argument("--import-from", help=_("import YouTube channels from YouTube's subscription export " "(available at https://www.youtube.com/subscription_manager)"), metavar="PATH", type=argparse.FileType("r")) parser.add_argument("--export-to", help=_("export YouTube channels in opml format"), metavar="PATH", type=argparse.FileType("wb")) parser.add_argument("--cleanup", help=_("removes old videos from the database and shrinks the size of the " "database file"), action="store_true") parser.add_argument("-v", "--version", help=_("output version information and exit"), action="store_true") parser.add_argument("--bug-report-info", help=_("print info to include in a bug report"), action="store_true") return parser.parse_args() ytcc-1.8.1/ytcc/cli.py000066400000000000000000000447061343616406200145660ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . # Allow global statement # pylint: disable=W0603 import itertools import sys from collections import OrderedDict import inspect import shutil import signal import textwrap as wrap from datetime import datetime from enum import Enum from typing import List, Iterable, Optional, TextIO, Any, Set, Tuple, Callable, NamedTuple, Dict, \ BinaryIO from ytcc import core, arguments, terminal, _ from ytcc.database import Video from ytcc.exceptions import BadConfigException, ChannelDoesNotExistException, \ DuplicateChannelException, BadURLException from ytcc.terminal import printt, printtln from ytcc.utils import unpack_optional try: ytcc_core = core.Ytcc() # pylint: disable=C0103 COLUMN_FILTER = [ytcc_core.config.table_format.getboolean("ID"), ytcc_core.config.table_format.getboolean("Date"), ytcc_core.config.table_format.getboolean("Channel"), ytcc_core.config.table_format.getboolean("Title"), ytcc_core.config.table_format.getboolean("URL"), ytcc_core.config.table_format.getboolean("Watched")] COLORS = ytcc_core.config.color except BadConfigException: print(_("The configuration file has errors!")) exit(1) INTERACTIVE_ENABLED = True DESCRIPTION_ENABLED = True NO_VIDEO = False DOWNLOAD_PATH = "" HEADER_ENABLED = True TABLE_HEADER = [_("ID"), _("Date"), _("Channel"), _("Title"), _("URL"), _("Watched")] _REGISTERED_OPTIONS: Dict[str, "Option"] = dict() def register_option(option_name, exit=False, is_action=True): # pylint: disable=redefined-builtin def decorator(func): nargs = len(inspect.signature(func).parameters) _REGISTERED_OPTIONS[option_name] = Option( run=func, exit=exit, nargs=nargs, is_action=is_action) return func return decorator class Option(NamedTuple): run: Callable exit: bool nargs: int is_action: bool class Action(Enum): def __init__(self, text: str, hotkey: str, color: int): self.text = text self.hotkey = hotkey self.color = color SHOW_HELP = (None, terminal.Keys.F1, None) PLAY_VIDEO = (_("Play video"), terminal.Keys.F2, COLORS.prompt_play_video) PLAY_AUDIO = (_("Play audio"), terminal.Keys.F3, COLORS.prompt_play_audio) MARK_WATCHED = (_("Mark as watched"), terminal.Keys.F4, COLORS.prompt_mark_watched) REFRESH = (None, terminal.Keys.F5, None) DOWNLOAD_AUDIO = (_("Download audio"), terminal.Keys.F7, COLORS.prompt_download_audio) DOWNLOAD_VIDEO = (_("Download video"), terminal.Keys.F6, COLORS.prompt_download_video) class Interactive: def __init__(self, videos: List[Video]): self.videos = videos self.previous_action = Action.PLAY_VIDEO self.action = Action.PLAY_VIDEO def makef(arg): return lambda: self.set_action(arg) self.hooks = {action.hotkey: makef(action) for action in list(Action)} def set_action(self, action: Action) -> bool: self.previous_action = self.action self.action = action return action in (Action.SHOW_HELP, Action.REFRESH) @staticmethod def _prefix_codes(alphabet: Set[str], count: int) -> List[str]: codes = list(alphabet) if len(codes) < 2: raise ValueError("alphabet must have at least two characters") if count <= 0: raise ValueError("count must not be negative") if len(codes) >= count: return codes[:count] first = codes.pop(0) iterator = iter(alphabet) while len(codes) < count: try: char = next(iterator) codes.append(first + char) except StopIteration: iterator = iter(alphabet) first = codes.pop(0) return codes def get_prompt_text(self) -> str: return self.action.text def get_prompt_color(self) -> Optional[int]: return self.action.color def command_line(self, tags: List[str], alphabet: Set[str]) -> Tuple[str, bool]: def print_prompt(): prompt_format = "{prompt_text} > " prompt = prompt_format.format(prompt_text=self.get_prompt_text()) printt(prompt, foreground=self.get_prompt_color(), bold=True, replace=True) print() print(_("Type a valid TAG. for help.")) print_prompt() tag = "" hook_triggered = False while tag not in tags: char = terminal.getkey() if char in self.hooks: hook_triggered = True if self.hooks[char](): break if char in {"\x04", "\x03"}: # Ctrl+d, Ctrl+d break if char in {"\r", ""}: tag = tags[0] break if char == "\x7f": # DEL tag = tag[:-1] elif char in alphabet: tag += char print_prompt() printt(tag) print() return tag, hook_triggered def run(self) -> None: alphabet = ytcc_core.config.quickselect_alphabet tags = self._prefix_codes(alphabet, len(self.videos)) index = OrderedDict(zip(tags, self.videos)) while index: remaining_tags = list(index.keys()) remaining_videos = index.values() # Clear display and set cursor to (1,1). Allows scrolling back in some terminals terminal.clear_screen() print_videos(remaining_videos, quickselect_column=remaining_tags) tag, hook_triggered = self.command_line(remaining_tags, alphabet) video = index.get(tag) if video is None and not hook_triggered: break if video is not None: if self.action is Action.MARK_WATCHED: video.watched = True del index[tag] elif self.action is Action.DOWNLOAD_AUDIO: print() download_video(video, True) del index[tag] elif self.action is Action.DOWNLOAD_VIDEO: print() download_video(video, False) del index[tag] elif self.action is Action.PLAY_AUDIO: print() play(video, True) del index[tag] elif self.action is Action.PLAY_VIDEO: print() play(video, False) del index[tag] elif self.action is Action.SHOW_HELP: self.action = self.previous_action terminal.clear_screen() print(_( " Display this help text.\n" " Set action: Play video.\n" " Set action: Play audio.\n" " Set action: Mark as watched.\n" " Refresh video list.\n" " Set action: Download video.\n" " Set action: Download audio.\n" " Accept first video.\n" " Exit.\n" )) input(_("Press Enter to continue")) elif self.action is Action.REFRESH: self.action = self.previous_action terminal.clear_screen() update_all() self.videos = ytcc_core.list_videos() self.run() break def maybe_print_description(description: Optional[str]) -> None: if DESCRIPTION_ENABLED and description is not None: columns = shutil.get_terminal_size().columns delimiter = "=" * columns lines = description.splitlines() print() print(_("Video description:")) print(delimiter) for line in lines: print(wrap.fill(line, width=columns)) print(delimiter, end="\n\n") def play(video: Video, audio_only: bool) -> None: print(_('Playing "{video.title}" by "{video.channel.displayname}"...').format(video=video)) maybe_print_description(video.description) if not ytcc_core.play_video(video, audio_only): print() print(_("WARNING: The video player terminated with an error.\n" " The last video is not marked as watched!")) print() def table_print(header: List[str], table: List[List[str]]) -> None: transposed = zip(header, *table) col_widths = [max(map(len, column)) for column in transposed] table_format = "│".join(itertools.repeat(" {{:<{}}} ", len(header))).format(*col_widths) if HEADER_ENABLED: header_line = "┼".join("─" * (width + 2) for width in col_widths) printtln(table_format.format(*header), bold=True) print(header_line) for i, row in enumerate(table): background = None if i % 2 == 0 else COLORS.table_alternate_background printtln(table_format.format(*row), background=background) def print_videos(videos: Iterable[Video], quickselect_column: Optional[Iterable[str]] = None) -> None: def row_filter(row: Iterable[str]) -> List[str]: return list(itertools.compress(row, COLUMN_FILTER)) def video_to_list(video: Video) -> List[str]: timestamp = unpack_optional(video.publish_date, lambda: 0) return [ str(video.id), datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M"), str(video.channel.displayname), str(video.title), ytcc_core.get_youtube_video_url(video.yt_videoid), _("Yes") if video.watched else _("No") ] def concat_row(tag: str, video: Video) -> List[str]: row = row_filter(video_to_list(video)) row.insert(0, tag) return row if quickselect_column is None: table = [row_filter(video_to_list(v)) for v in videos] table_print(row_filter(TABLE_HEADER), table) else: table = [concat_row(k, v) for k, v in zip(quickselect_column, videos)] header = row_filter(TABLE_HEADER) header.insert(0, "TAG") table_print(header, table) def download_video(video: Video, audio_only: bool = False) -> None: print(_('Downloading "{video.title}" by "{video.channel.displayname}"...').format(video=video)) success = ytcc_core.download_video(video=video, path=DOWNLOAD_PATH, audio_only=audio_only) if not success: print(_("An Error occured while downloading the video")) @register_option("mark_watched") def mark_watched(video_ids: List[int]) -> None: ytcc_core.set_video_id_filter(video_ids) videos = ytcc_core.list_videos() if not videos: print(_("No videos were marked as watched")) return for video in videos: video.watched = True print(_("Following videos were marked as watched:")) print() print_videos(videos) @register_option("watch") def watch(video_ids: Iterable[int]) -> None: ytcc_core.set_video_id_filter(video_ids) videos = ytcc_core.list_videos() if not videos: print(_("No videos to watch. No videos match the given criteria.")) elif not INTERACTIVE_ENABLED: for video in videos: play(video, NO_VIDEO) else: Interactive(videos).run() @register_option("download") def download(video_ids: List[int]) -> None: ytcc_core.set_video_id_filter(video_ids) for video in ytcc_core.list_videos(): download_video(video, NO_VIDEO) @register_option("update") def update_all() -> None: print(_("Updating channels...")) ytcc_core.update_all() @register_option("list") def list_videos() -> None: videos = ytcc_core.list_videos() if not videos: print(_("No videos to list. No videos match the given criteria.")) else: print_videos(videos) @register_option("list_channels") def print_channels() -> None: channels = ytcc_core.get_channels() if not channels: print(_("No channels added, yet.")) else: for channel in channels: print(channel.displayname) @register_option("add_channel", exit=True) def add_channel(name: str, channel_url: str) -> None: try: ytcc_core.add_channel(name, channel_url) except BadURLException: print(_("{!r} is not a valid YouTube URL").format(channel_url)) except DuplicateChannelException: print(_("You are already subscribed to {!r}").format(name)) except ChannelDoesNotExistException: print(_("The channel {!r} does not exist").format(channel_url)) @register_option("delete_channel", exit=True) def delete_channel(channels: List[str]) -> None: ytcc_core.delete_channels(channels) @register_option("rename", exit=True) def rename_channel(oldname: str, newname: str) -> None: try: ytcc_core.rename_channel(oldname, newname) except ChannelDoesNotExistException: print(_("Error: The given channel does not exist.")) except DuplicateChannelException: print(_("Error: The new name already exists.")) @register_option("cleanup", exit=True) def cleanup() -> None: print(_("Cleaning up database...")) ytcc_core.cleanup() @register_option("import_from", exit=True) def import_channels(file: TextIO) -> None: print(_("Importing...")) try: ytcc_core.import_channels(file) subscriptions = _("Subscriptions") print() print(subscriptions) print("=" * len(subscriptions)) print_channels() except core.InvalidSubscriptionFileError: print(_("The given file is not valid YouTube export file")) @register_option("export_to", exit=True) def export_channels(file: BinaryIO) -> None: ytcc_core.export_channels(file) @register_option("version", exit=True) def version() -> None: import ytcc print("ytcc version " + ytcc.__version__) print() print("Copyright (C) 2015-2019 " + ytcc.__author__) print("This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you") print("are welcome to redistribute it under certain conditions. See the GNU General ") print("Public Licence for details.") @register_option("bug_report_info", exit=True) def bug_report_info() -> None: import ytcc import youtube_dl.version import subprocess import feedparser import lxml.etree import sqlalchemy print("---ytcc version---") print(ytcc.__version__) print() print("---youtube-dl version---") print(youtube_dl.version.__version__) print() print("---SQLAlchemy version---") print(sqlalchemy.__version__) # type: ignore print() print("---feedparser version---") print(feedparser.__version__) print() print("---lxml version---") print(lxml.etree.__version__) print() print("---python version---") print(sys.version) print() print("---mpv version---") subprocess.run(["mpv", "--version"]) print() print("---config dump---") print(ytcc_core.config) @register_option("disable_interactive", is_action=False) def disable_interactive() -> None: global INTERACTIVE_ENABLED INTERACTIVE_ENABLED = False @register_option("no_description", is_action=False) def disable_description() -> None: global DESCRIPTION_ENABLED DESCRIPTION_ENABLED = False @register_option("no_header", is_action=False) def disable_header() -> None: global HEADER_ENABLED HEADER_ENABLED = False @register_option("no_video", is_action=False) def disable_video() -> None: global NO_VIDEO NO_VIDEO = True @register_option("path", is_action=False) def set_download_path(path: str) -> None: global DOWNLOAD_PATH DOWNLOAD_PATH = path @register_option("columns", is_action=False) def set_columns(cols: List["str"]) -> None: global COLUMN_FILTER if cols == ["all"]: COLUMN_FILTER = [True] * len(TABLE_HEADER) else: COLUMN_FILTER = [f in cols for f in TABLE_HEADER] @register_option("include_watched", is_action=False) def set_include_watched_filter() -> None: ytcc_core.set_include_watched_filter() COLUMN_FILTER[5] = True @register_option("channel_filter", is_action=False) def set_channel_filter(channels: List[str]) -> None: ytcc_core.set_channel_filter(channels) @register_option("since", is_action=False) def set_date_begin_filter(begin: datetime) -> None: ytcc_core.set_date_begin_filter(begin) @register_option("to", is_action=False) def set_date_end_filter(end: datetime) -> None: ytcc_core.set_date_end_filter(end) def run() -> None: args = vars(arguments.get_args()) option_names = [ "version", "bug_report_info", "add_channel", "delete_channel", "cleanup", "import_from", "export_to", "rename", "disable_interactive", "no_description", "no_header", "no_video", "path", "include_watched", "columns", "channel_filter", "since", "to", "list_channels", "update", "list", "download", "watch", "mark_watched" ] action_executed = False for option_name in option_names: option = _REGISTERED_OPTIONS.get(option_name) arg = args.get(option_name) if option is not None and (arg or arg == []): if option.nargs == 0: option.run() elif option.nargs == 1: option.run(arg) else: option.run(*arg) action_executed = action_executed or option.is_action if option.exit: return if not action_executed: update_all() print() if not INTERACTIVE_ENABLED: list_videos() print() watch([]) def register_signal_handlers() -> None: # pylint: disable=unused-argument def handler(signum: Any, frame: Any) -> None: ytcc_core.close() print() print(_("Bye...")) exit(1) signal.signal(signal.SIGINT, handler) def main() -> None: register_signal_handlers() run() ytcc_core.close() ytcc-1.8.1/ytcc/config.py000066400000000000000000000133641343616406200152600ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . import configparser import io import os import re from pathlib import Path from typing import Any, Dict, Optional, Iterable from ytcc.database import Video, Channel from ytcc.exceptions import BadConfigException DEFAULTS: Dict[str, Dict[str, Any]] = { "YTCC": { "DBPath": "~/.local/share/ytcc/ytcc.db", "DownloadDir": "~/Downloads", "mpvFlags": "--really-quiet --ytdl --ytdl-format=bestvideo[height<=?1080]+bestaudio/best", "alphabet": "sdfervghnuiojkl", "orderBy": "channel, date" }, "color": { "promptDownloadAudio": 2, "promptDownloadVideo": 4, "promptPlayAudio": 2, "promptPlayVideo": 4, "promptMarkWatched": 1, "tableAlternateBackground": 245, }, "youtube-dl": { "format": "bestvideo[height<=?1080]+bestaudio/best", "outputTemplate": "%(title)s.%(ext)s", "loglevel": "normal", "ratelimit": 0, "retries": 0, "subtitles": "off", "thumbnail": "on", "skipLiveStream": "yes" }, "TableFormat": { "ID": "on", "Date": "off", "Channel": "on", "Title": "on", "URL": "off", "Watched": "off" } } def _get_config(override_cfg_file: Optional[str] = None) -> configparser.ConfigParser: """Read config file from several locations. Searches at following locations: 1. ``override_cfg_file`` 2. ``$XDG_CONFIG_HOME/ytcc/ytcc.conf`` 3. ``~/.config/ytcc/ytcc.conf`` 4. ``~/.ytcc.conf`` If no config file is found in these three locations, a default config file is created in ``~/.config/ytcc/ytcc.conf`` :param override_cfg_file: Read the config from this file. :return: The dict-like config object """ config_dir = os.getenv("XDG_CONFIG_HOME") if not config_dir: config_dir = "~/.config" global_cfg_file = "/etc/ytcc/ytcc.conf" default_cfg_file = os.path.expanduser(config_dir + "/ytcc/ytcc.conf") fallback_cfg_file = os.path.expanduser("~/.ytcc.conf") config = configparser.ConfigParser(interpolation=None) config.read_dict(DEFAULTS) cfg_file_locations = [global_cfg_file, default_cfg_file, fallback_cfg_file] if override_cfg_file: cfg_file_locations.append(override_cfg_file) if not config.read(cfg_file_locations): path = Path(default_cfg_file) path.parent.mkdir(parents=True, exist_ok=True) path.touch() with path.open("w") as conf_file: config.write(conf_file) return config class Config: """Handles the ini-based configuration file.""" def __init__(self, override_cfg_file: Optional[str] = None) -> None: super(Config, self).__init__() config = _get_config(override_cfg_file) self._config = config self.download_dir = os.path.expanduser(config["YTCC"]["DownloadDir"]) self.db_path = os.path.expanduser(config["YTCC"]["DBPath"]) self.mpv_flags = re.compile("\\s+").split(config["YTCC"]["mpvFlags"]) self.quickselect_alphabet = set(config["YTCC"]["alphabet"]) self.table_format = config["TableFormat"] self.youtube_dl = _YTDLConf(config["youtube-dl"]) self.order_by = list(self.init_order()) self.color = _ColorConf(config["color"]) def init_order(self) -> Iterable[Any]: col_mapping = { "id": Video.id, "date": Video.publish_date, "channel": Channel.displayname, "title": Video.title, "url": Video.yt_videoid, "watched": Video.watched } for key in self._config["YTCC"]["orderBy"].split(","): column = col_mapping.get(key.strip().lower()) if column is not None: yield column else: raise BadConfigException(f"Cannot order by {key.strip()}") def __str__(self) -> str: strio = io.StringIO() self._config.write(strio) return strio.getvalue() class _ColorConf: def __init__(self, subconf: Any) -> None: super(_ColorConf, self).__init__() self.prompt_download_audio = int(subconf["promptDownloadAudio"]) self.prompt_download_video = int(subconf["promptDownloadVideo"]) self.prompt_play_audio = int(subconf["promptPlayAudio"]) self.prompt_play_video = int(subconf["promptPlayVideo"]) self.prompt_mark_watched = int(subconf["promptMarkWatched"]) self.table_alternate_background = int(subconf["tableAlternateBackground"]) class _YTDLConf: def __init__(self, subconf: Any) -> None: super(_YTDLConf, self).__init__() self.format = subconf["format"] self.output_template = subconf["outputTemplate"] self.loglevel = subconf["loglevel"] self.retries = float(subconf["retries"]) # float to set indefinetly many retires self.subtitles = subconf["subtitles"] self.thumbnail = subconf.getboolean("thumbnail") self.skip_live_stream = subconf.getboolean("skipLiveStream") limit = int(subconf["ratelimit"]) self.ratelimit = limit if limit > 0 else None ytcc-1.8.1/ytcc/core.py000066400000000000000000000356621343616406200147500ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . import time import datetime import os import subprocess from itertools import chain from concurrent.futures import ThreadPoolExecutor as Pool from io import StringIO from typing import Iterable, List, TextIO, Optional, Any, Dict, BinaryIO from urllib.error import URLError from urllib.parse import urlparse, urlunparse, parse_qs from urllib.request import urlopen import sqlalchemy import youtube_dl from lxml import etree import feedparser from ytcc.config import Config from ytcc.database import Channel, Database, Video from ytcc.exceptions import YtccException, BadURLException, ChannelDoesNotExistException, \ DuplicateChannelException, InvalidSubscriptionFileError from ytcc.utils import unpack_optional def _get_youtube_rss_url(yt_channel_id: str) -> str: return f"https://www.youtube.com/feeds/videos.xml?channel_id={yt_channel_id}" class Ytcc: """The Ytcc class handles updating the RSS feeds and playing and listing/filtering videos. Filters can be set with with following methods: * ``set_channel_filter`` * ``set_date_begin_filter`` * ``set_date_end_filter`` * ``set_include_watched_filter`` """ def __init__(self, override_cfg_file: Optional[str] = None) -> None: self.config = Config(override_cfg_file) self.database = Database(self.config.db_path) self.video_id_filter: List[int] = [] self.channel_filter: List[str] = [] self.date_begin_filter = 0.0 self.date_end_filter = (0.0, False) self.include_watched_filter = False def __enter__(self) -> "Ytcc": return self def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: self.database.__exit__(exc_type, exc_val, exc_tb) def close(self) -> None: """Close open resources like the database connection.""" self.database.close() @staticmethod def get_youtube_video_url(yt_videoid: Optional[str]) -> str: """Return the YouTube URL for the given youtube video ID. :param yt_videoid: The YouTube video ID. :return: The YouTube URL for the given youtube video ID. """ if yt_videoid is None: raise YtccException("Video id is none!") return f"https://www.youtube.com/watch?v={yt_videoid}" def set_channel_filter(self, channel_filter: List[str]) -> None: """Set the channel filter. The results when listing videos will only include videos by channels specified in the filter. :param channel_filter: The list of channel names. """ self.channel_filter.clear() self.channel_filter.extend(channel_filter) def set_date_begin_filter(self, begin: datetime.datetime) -> None: """Set the time filter. The results when listing videos will only include videos newer than the given time. :param begin: The lower bound of the time filter. """ self.date_begin_filter = begin.timestamp() def set_date_end_filter(self, end: datetime.datetime) -> None: """Set the time filter. The results when listing videos will only include videos older than the given time. :param end: The upper bound of the time filter. """ self.date_end_filter = (end.timestamp(), True) def set_include_watched_filter(self) -> None: """Set the "watched video" filter. The results when listing videos will include both watched and unwatched videos. """ self.include_watched_filter = True def set_video_id_filter(self, ids: Optional[Iterable[int]] = None) -> None: """Set the id filter. This filter overrides all other filters. :param ids: IDs to filter for. """ self.video_id_filter.clear() if ids is not None: self.video_id_filter.extend(ids) @staticmethod def _update_channel(channel: Channel) -> List[Video]: yt_channel_id = channel.yt_channelid url = _get_youtube_rss_url(yt_channel_id) feed = feedparser.parse(url) return [ Video( yt_videoid=str(entry.yt_videoid), title=str(entry.title), description=str(entry.description), publisher=yt_channel_id, publish_date=time.mktime(entry.published_parsed), watched=False ) for entry in feed.entries ] def update_all(self) -> None: """Check every channel for new videos.""" channels = self.database.get_channels() num_workers = unpack_optional(os.cpu_count(), lambda: 1) * 2 with Pool(num_workers) as pool: videos = chain.from_iterable(pool.map(self._update_channel, channels)) self.database.add_videos(videos) def play_video(self, video: Video, audio_only: bool = False) -> bool: """Play the given video with the mpv video player and mark the the video as watched. The video will not be marked as watched, if the player exits unexpectedly (i.e. exits with non-zero exit code) or another error occurs. :param video: The video to play. :param audio_only: If True, only the audio track of the video is played :return: False if the given video_id does not exist or the player closed with a non-zero exit code. True if the video was played successfully. """ no_video_flag = [] if audio_only: no_video_flag.append("--no-video") if video: try: mpv_result = subprocess.run(["mpv", *no_video_flag, *self.config.mpv_flags, self.get_youtube_video_url(video.yt_videoid)]) except FileNotFoundError: raise YtccException("Could not locate the mpv video player!") if mpv_result.returncode == 0: video.watched = True return True return False def download_video(self, video: Video, path: str = "", audio_only: bool = False) -> bool: """Download the given video with youtube-dl and mark it as watched. If the path is not given, the path is read from the config file. :param video: The video to download. :param path: The directory where the download is saved. :param audio_only: If True, only the audio track is downloaded. :return: True, if the video was downloaded successfully. False otherwise. """ if path: download_dir = path elif self.config.download_dir: download_dir = self.config.download_dir else: download_dir = "" conf = self.config.youtube_dl ydl_opts: Dict[str, Any] = { "outtmpl": os.path.join(download_dir, conf.output_template), "ratelimit": conf.ratelimit, "retries": conf.retries, "quiet": conf.loglevel == "quiet", "verbose": conf.loglevel == "verbose", "ignoreerrors": False } if audio_only: ydl_opts["format"] = "bestaudio/best" if conf.thumbnail: ydl_opts["writethumbnail"] = True ydl_opts["postprocessors"] = [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': "m4a" }, {"key": "EmbedThumbnail"} ] else: ydl_opts["format"] = conf.format if conf.subtitles != "off": ydl_opts["subtitleslangs"] = list(map(str.strip, conf.subtitles.split(","))) ydl_opts["writesubtitles"] = True ydl_opts["writeautomaticsub"] = True ydl_opts["postprocessors"] = [{"key": "FFmpegEmbedSubtitle"}] with youtube_dl.YoutubeDL(ydl_opts) as ydl: url = self.get_youtube_video_url(video.yt_videoid) try: info = ydl.extract_info(url, download=False, process=False) if info.get("is_live", False) and conf.skip_live_stream: return False ydl.process_ie_result(info, download=True) video.watched = True return True except youtube_dl.utils.YoutubeDLError: return False def add_channel(self, displayname: str, channel_url: str) -> None: """Subscribe to a channel. :param displayname: A human readable name of the channel. :param channel_url: The url to a page that can identify the channel. :raises ChannelDoesNotExistException: If the given URL does not exist. :raises DuplicateChannelException: If the channel already exists in the database. :raises BadURLException: If the given URL does not refer to a YouTube channel. """ known_yt_domains = ["youtu.be", "youtube.com", "youtubeeducation.com", "youtubekids.com", "youtube-nocookie.com", "yt.be", "ytimg.com"] url_parts = urlparse(channel_url, scheme="https") if not url_parts.netloc: url_parts = urlparse("https://" + channel_url) domain = url_parts.netloc.split(":")[0] domain = ".".join(domain.split(".")[-2:]) if domain not in known_yt_domains: raise BadURLException(f"{channel_url} is not a valid URL") url = urlunparse(("https", url_parts.netloc, url_parts.path, url_parts.params, url_parts.query, url_parts.fragment)) try: response = urlopen(url).read().decode('utf-8') except URLError: raise BadURLException(f"{channel_url} is not a valid URL") parser = etree.HTMLParser() root = etree.parse(StringIO(response), parser).getroot() site_name_node = root.xpath('/html/head/meta[@property="og:site_name"]') channel_id_node = root.xpath('//meta[@itemprop="channelId"]') if not site_name_node or site_name_node[0].attrib.get("content", "") != "YouTube": raise BadURLException(f"{channel_url} does not seem to be a YouTube URL") if not channel_id_node: raise ChannelDoesNotExistException(f"{channel_url} does not seem to be a YouTube URL") yt_channelid = channel_id_node[0].attrib.get("content") try: self.database.add_channel(Channel(displayname=displayname, yt_channelid=yt_channelid)) except sqlalchemy.exc.IntegrityError: raise DuplicateChannelException(f"Channel already subscribed: {displayname}") def import_channels(self, file: TextIO) -> None: """Import all channels from YouTube's subscription export file. :param file: The file to read from. """ def _create_channel(elem: etree.Element) -> Channel: rss_url = urlparse(elem.attrib["xmlUrl"]) query_dict = parse_qs(rss_url.query, keep_blank_values=False) channel_id = query_dict.get("channel_id", []) if len(channel_id) != 1: message = f"'{file.name}' is not a valid YouTube export file" raise InvalidSubscriptionFileError(message) return Channel(displayname=elem.attrib["title"], yt_channelid=channel_id[0]) try: root = etree.parse(file) except Exception: raise InvalidSubscriptionFileError(f"'{file.name}' is not a valid YouTube export file") elements = root.xpath('//outline[@type="rss"]') self.database.add_channels((_create_channel(e) for e in elements)) def export_channels(self, outstream: BinaryIO) -> None: """Export all channels as OPML file. :param outstream: The file/stream the OPML file will be written to. """ opml = etree.Element("opml", version="1.1") body = etree.SubElement(opml, "body") outline = etree.SubElement(body, "outline", text="ytcc subscriptions", title="ytcc subscriptions") for channel in self.get_channels(): outline.append(etree.Element("outline", text=channel.displayname, title=channel.displayname, type="rss", xmlUrl=_get_youtube_rss_url(channel.yt_channelid))) outstream.write(etree.tostring(opml, pretty_print=True)) def list_videos(self) -> List[Video]: """Return a list of videos that match the filters set by the set_*_filter methods. :return: A list of videos. """ if self.video_id_filter: return self.database.session.query(Video) \ .join(Channel, Channel.yt_channelid == Video.publisher) \ .filter(Video.id.in_(self.video_id_filter)) \ .order_by(*self.config.order_by).all() if not self.date_end_filter[1]: date_end_filter = time.mktime(time.gmtime()) + 20 else: date_end_filter = self.date_end_filter[0] query = self.database.session.query(Video) \ .join(Channel, Channel.yt_channelid == Video.publisher) \ .filter(Video.publish_date > self.date_begin_filter) \ .filter(Video.publish_date < date_end_filter) if self.channel_filter: query = query.filter(Channel.displayname.in_(self.channel_filter)) if not self.include_watched_filter: query = query.filter(~Video.watched) query = query.order_by(*self.config.order_by) return query.all() def delete_channels(self, displaynames: List[str]) -> None: """Delete (or unsubscribe) channels. :param displaynames: The names of channels to delete. """ self.database.delete_channels(displaynames) def rename_channel(self, oldname: str, newname: str) -> None: """Rename the given channel. :param oldname: The name of the channel. :param newname: The new name of the channel. :raises ChannelDoesNotExistException: If the given channel does not exist. :raises DuplicateChannelException: If new name already exists. """ self.database.rename_channel(oldname, newname) def get_channels(self) -> List[Channel]: """Get the list of all subscribed channels. :return: A list of channel names. """ return self.database.get_channels() def cleanup(self) -> None: """Delete old videos from the database.""" self.database.cleanup() ytcc-1.8.1/ytcc/database.py000066400000000000000000000134621343616406200155560ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . from pathlib import Path from typing import List, Iterable, Any from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String, Boolean, ForeignKey, Float from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.orm.exc import NoResultFound from ytcc.exceptions import ChannelDoesNotExistException, DuplicateChannelException Base = declarative_base() class Channel(Base): __tablename__ = "channel" id = Column(Integer, primary_key=True) displayname = Column(String, unique=True, nullable=False) yt_channelid = Column(String, unique=True, nullable=False) videos = relationship("Video", back_populates="channel", cascade="all, delete, delete-orphan") class Video(Base): __tablename__ = "video" id = Column(Integer, primary_key=True) yt_videoid = Column(String, unique=True, nullable=False) title = Column(String) description = Column(String) publisher = Column(String, ForeignKey("channel.yt_channelid"), nullable=False) publish_date = Column(Float) watched = Column(Boolean) channel = relationship("Channel", back_populates="videos") class Database: def __init__(self, path: str = ":memory:"): if path != ":memory:": expanded_path = Path(path).expanduser() expanded_path.parent.mkdir(parents=True, exist_ok=True) path = str(expanded_path) self.engine = create_engine(f"sqlite:///{path}", echo=False) session = sessionmaker(bind=self.engine) self.session = session() Base.metadata.create_all(self.engine) def __enter__(self) -> "Database": return self def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: self.close() def close(self) -> None: self.session.commit() self.session.close() def add_channels(self, channels: Iterable[Channel]) -> None: self.session.add_all(channels) self.session.commit() def add_channel(self, channel: Channel) -> None: self.session.add(channel) self.session.commit() def get_channels(self) -> List[Channel]: return self.session.query(Channel).order_by(Channel.displayname).all() def delete_channels(self, display_names: Iterable[str]): channels = self.session.query(Channel).filter(Channel.displayname.in_(display_names)) for channel in channels: self.session.delete(channel) self.session.commit() def rename_channel(self, oldname: str, newname: str) -> None: """Rename the given channel. :param oldname: The name of the channel. :param newname: The new name of the channel. :raises ChannelDoesNotExistException: If the given channel does not exist. :raises DuplicateChannelException: If new name already exists. """ query = self.session.query(Channel).filter(Channel.displayname == newname) if query.one_or_none() is not None: raise DuplicateChannelException() try: channel = self.session.query(Channel).filter(Channel.displayname == oldname).one() channel.displayname = newname except NoResultFound: raise ChannelDoesNotExistException() def add_videos(self, videos: Iterable[Video]) -> None: for video in videos: query = self.session.query(Video.id).filter(Video.yt_videoid == video.yt_videoid) if not self.session.query(query.exists()).scalar(): self.session.add(video) self.session.flush() def resolve_video_ids(self, video_ids: Iterable[int]): return self.session.query(Video).filter(Video.id.in_(video_ids)) def resolve_video_id(self, video_id: int) -> Video: return self.session.query(Video).get(video_id) def cleanup(self) -> None: """Delete all videos from all channels, but keeps the 30 latest videos of every channel.""" sql = """ delete from video as v where (select count(*) from video w where v.publish_date < w.publish_date and v.publisher = w.publisher) >= 30; """ self.session.commit() self.engine.execute(sql) # Delete videos without channels. # This happend in older versions, because foreign keys were not enabled. # Also happens if foreign keys cannot be enabled due to missing compile flags. delete_dangling_sql = """ delete from video where id in ( select v.id from video v left join channel c on v.publisher = c.yt_channelid where c.yt_channelid is null ); """ self.engine.execute(delete_dangling_sql) # Delete old full text search tables and triggers self.engine.execute("drop table if exists user_search;") self.engine.execute("drop trigger if exists populate_search;") self.engine.execute("drop trigger if exists delete_from_search;") self.engine.execute("vacuum;") self.session.commit() ytcc-1.8.1/ytcc/exceptions.py000066400000000000000000000026721343616406200161740ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . """Exceptions in their own module to avoid circular imports.""" class YtccException(Exception): """A general parent class of all Exceptions that are used in Ytcc.""" class BadURLException(YtccException): """Raised when a given URL does not refer to a YouTube channel.""" class DuplicateChannelException(YtccException): """Raised when trying to subscribe to a channel the second (or more) time.""" class ChannelDoesNotExistException(YtccException): """Raised when the url of a given channel does not exist.""" class InvalidSubscriptionFileError(YtccException): """Raised when the given file is not a valid XML file.""" class BadConfigException(YtccException): """Raised when error in config file is encountered.""" ytcc-1.8.1/ytcc/terminal.py000066400000000000000000000104671343616406200156270ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . import sys import tty import termios from typing import Optional class Keys: """Indetifiers for special key sequences like the F-keys.""" F1 = "" F2 = "" F3 = "" F4 = "" F5 = "" F6 = "" F7 = "" # https://invisible-island.net/xterm/xterm-function-keys.html _KNOWN_KEYS = { # vt100 "\x1bOP": Keys.F1, "\x1bOQ": Keys.F2, "\x1bOR": Keys.F3, "\x1bOS": Keys.F4, "\x1bOt": Keys.F5, "\x1bOu": Keys.F6, "\x1bOv": Keys.F7, # rxvt "\x1b[11~": Keys.F1, "\x1b[12~": Keys.F2, "\x1b[13~": Keys.F3, "\x1b[14~": Keys.F4, "\x1b[15~": Keys.F5, "\x1b[17~": Keys.F6, "\x1b[18~": Keys.F7, # linux "\x1b[[A": Keys.F1, "\x1b[[B": Keys.F2, "\x1b[[C": Keys.F3, "\x1b[[D": Keys.F4, "\x1b[[E": Keys.F5, } _PREFIXES = { escape_sequence[:i] for escape_sequence in _KNOWN_KEYS for i in range(1, len(escape_sequence) + 1) } def _read_sequence(stream) -> str: seq = stream.read(1) if seq == "\x1b": while seq not in _KNOWN_KEYS and seq in _PREFIXES: seq += stream.read(1) return _KNOWN_KEYS.get(seq, "Unknown Sequence") return seq def getkey() -> str: """Read a single character from stdin without the need to press enter. If the key press caused an escape sequence, return the sequence (see Keys). If the sequence could not be understood, return "Unknown Sequence". :return: Character read from stdin. """ if not sys.stdin.isatty(): return "" file_descriptor = sys.stdin.fileno() old_settings = termios.tcgetattr(file_descriptor) try: tty.setraw(sys.stdin.fileno()) char = _read_sequence(sys.stdin) finally: termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings) return char def clear_screen() -> None: print("\033[2J\033[1;1H", end="") def printtln(*text, foreground: Optional[int] = None, background: Optional[int] = None, bold: bool = False, replace: bool = False) -> None: """Like printt, but print newline at the end. :param text: The text to print, elements are concatenated without a separator. :param foreground: Foreground color. :param background: Background color. :param bold: Make text bold. :param replace: Replace the current line. """ printt(*text, foreground=foreground, background=background, bold=bold, replace=replace) print() def printt(*text, foreground: Optional[int] = None, background: Optional[int] = None, bold: bool = False, replace: bool = False) -> None: """Print text on terminal styled with ANSI escape sequences. If stdout is not a TTY, no escape sequences will be printed. Supports 8-bit colors. :param text: The text to print, elements are concatenated without a separator. :param foreground: Foreground color. :param background: Background color. :param bold: Make text bold. :param replace: Replace the current line. """ if not sys.stdout.isatty(): print(*text, sep="", end="") return esc_color_background = "\033[48;5;{}m" esc_color_foreground = "\033[38;5;{}m" esc_clear_attrs = "\033[0m" esc_bold = "\033[1m" if foreground is not None and 0 <= foreground <= 255: print(esc_color_foreground.format(foreground), end="") if background is not None and 0 <= background <= 255: print(esc_color_background.format(background), end="") if bold: print(esc_bold, end="") if replace: print(f"\033[2K\r", end="") print(*text, sep="", end="") print(esc_clear_attrs, flush=True, end="") ytcc-1.8.1/ytcc/utils.py000066400000000000000000000016641343616406200151530ustar00rootroot00000000000000# ytcc - The YouTube channel checker # Copyright (C) 2019 Wolfgang Popp # # This file is part of ytcc. # # ytcc is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ytcc is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ytcc. If not, see . from typing import TypeVar, Optional, Callable # pylint: disable=invalid-name T = TypeVar("T") def unpack_optional(elem: Optional[T], default: Callable[[], T]) -> T: if elem is None: return default() return elem