minimal viable product

This commit is contained in:
simon 2021-09-06 00:10:14 +07:00
commit dc9fd72cde
65 changed files with 6499 additions and 0 deletions

18
.dockerignore Normal file
View File

@ -0,0 +1,18 @@
# Git
.git
.gitignore
# Docker
.docker
# Python
tubearchivist/__pycache__/
tubearchivist/*/__pycache__/
tubearchivist/*/*/__pycache__/
tubearchivist/*/*/*/__pycache__/
.env/
.venv/
venv/
# Unneeded graphics
assets/*

11
.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
# python testing cache
__pycache__
# django testing db
db.sqlite3
# frontend fonts
*ttf.woff
# for local testing only
testing.sh

5
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"python.linting.pylintEnabled": true,
"python.linting.pycodestyleEnabled": false,
"python.linting.enabled": true
}

41
Dockerfile Normal file
View File

@ -0,0 +1,41 @@
# build the tube archivist image from default python slim image
FROM python:3.9.7-slim-bullseye
ENV PYTHONUNBUFFERED 1
# install distro packages needed
RUN apt-get clean && apt-get -y update && apt-get -y install --no-install-recommends \
build-essential \
ffmpeg \
nginx \
curl && rm -rf /var/lib/apt/lists/*
# copy config files
COPY nginx.conf /etc/nginx/conf.d/
# make folders
RUN mkdir /cache
RUN mkdir /youtube
RUN mkdir /app
# install python dependencies
COPY ./tubearchivist/requirements.txt /requirements.txt
RUN pip install --no-cache-dir -r requirements.txt --src /usr/local/src
# copy application into container
COPY ./tubearchivist /app
COPY ./run.sh /app
COPY ./uwsgi.ini /app
# volumes
VOLUME /cache
VOLUME /youtube
# start
WORKDIR /app
EXPOSE 80
RUN chmod +x ./run.sh
CMD ["./run.sh"]

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

76
README.md Normal file
View File

@ -0,0 +1,76 @@
![banner-tube-archivist-light.png](assets/tube-archivist-banner.jpg?raw=true "Tube Archivist Banner")
<center><h1>The Tube Archivist<br>Your self hosted Youtube media server</h1></center>
## Core functionality
* Subscribe to your favourite Youtube channels
* Download Videos using **yt-dlp**
* Index and make videos searchable
* Play videos
* Keep track of viewed and unviewed videos
## Problem Tube Archivist tries to solve
Once your Youtube video collection grows, it becomes hard to search and find a specific video. That's where Tube Archivist comes in: By indexing your video collection with metadata from Youtube, you can organize, search and enjoy your archived Youtube videos without hassle offline through a convenient web interface.
## Installation
Take a look at the example `docker-compose.yml` file provided. Tube Archivist depends on three main components split up into seperate docker containers:
### Tube Archivist
The main Python application that displays and serves your video collection, built with Django.
- Serves the interface on port `8000`
- Needs a mandatory volume for the video archive at **/youtube**
- And another recommended volume to save the cache for thumbnails and artwork at **/cache**.
- The environment variables `ES_URL` and `REDIS_HOST` are needed to tell Tube Archivist where Elasticsearch and Redis respectively are located.
- The environment variables `HOST_UID` and `HOST_GID` allowes Tube Archivist to `chown` the video files to the main host system user instead of the container user.
### Elasticsearch
Stores video meta data and makes everything searchable. Also keeps track of the download queue.
- Needs to be accessable over the default port `9200`
- Needs a volume at **/usr/share/elasticsearch/data** to store data
Follow the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html) for additional installation details.
### Redis JSON
Functions as a cache and temporary link between the application and the filesystem. Used to store and display messages and configuration variables.
- Needs to be accessable over the default port `6379`
- Takes an optional volume at **/data** to make your configuration changes permanent.
## Getting Started
1. Go through the **settings** page and look at the available options. Particularly set *Download Format* to you desired video quality before downloading.
2. Subscribe to some of your favourite Youtube channels on the **channels** page.
3. On the **downloads** page, click on *Rescan subscriptions* to add videos from the subscribed channels to your Download queue or click on *Add to download queue* to manually add Video IDs or links.
4. Click on *Download queue* and let Tube Archivist to it's thing.
5. Enjoy your archived collection!
## Potential pitfalls
**Elastic Search** in Docker requires the kernel setting of the host machine `vm.max_map_count` to be set to least 262144.
To temporary set the value run:
```
sudo sysctl -w vm.max_map_count=262144
```
To apply the change permanently depends on your host operating system:
- For example on Ubuntu Server add `vm.max_map_count = 262144` to the file */etc/sysctl.conf*.
- On Arch based systems create a file */etc/sysctl.d/max_map_count.conf* with the content `vm.max_map_count = 262144`.
- On any other platform look up in the documentation on how to pass kernel parameters.
## Roadmap
This should be considered as a **minimal viable product**, there is an exstensive list of future functions and improvements planned:
- [ ] Scan your filesystem to manually add videos
- [ ] Access controll
- [ ] User roles
- [ ] Delete videos and channel
- [ ] Create playlists
- [ ] Show similar videos on video page
- [ ] Import existing downloaded archive
- [ ] Multi language support
- [ ] Backup and restore
## Known limitations
- Video files created by Tube Archivist need to be **mp4** video files for best browser compatibility.
- Every limitation **yt-dlp** will also be present in Tube Archivist. If yt-dlp can't download or extract a video for any reason, Tube Archivist won't be able to either.
- For now this is meant to be run in a trusted network environment.

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

73
deploy.sh Executable file
View File

@ -0,0 +1,73 @@
#!/bin/bash
# deploy all needed project files to different servers:
# test for local vm for testing
# blackhole for local production
# docker to publish
set -e
function sync_blackhole {
# docker commands need sudo
host="blackhole.local"
read -sp 'Password: ' remote_pw
export PASS=$remote_pw
rsync -a --progress --delete-after \
--exclude "**/cache" \
--exclude "**/__pycache__/" \
--exclude "db.sqlite3" \
. -e ssh "$host":tubearchivist
echo "$PASS" | ssh "$host" 'sudo -S docker build -t bbilly1/tubearchivist:latest tubearchivist 2>/dev/null'
echo "$PASS" | ssh "$host" 'sudo -S docker-compose up -d 2>/dev/null'
}
function sync_test {
# docker commands don't need sudo in testing vm
host="tubearchivist.local"
rsync -a --progress --delete-after \
--exclude "**/cache" \
--exclude "**/__pycache__/" \
--exclude "db.sqlite3" \
. -e ssh "$host":tubearchivist
rsync -r --progress --delete docker-compose.yml -e ssh "$host":docker
ssh "$host" 'docker build -t bbilly1/tubearchivist:latest tubearchivist'
ssh "$host" 'docker-compose -f docker/docker-compose.yml up -d'
}
function sync_docker {
if [[ $(systemctl is-active docker) != 'active' ]]; then
echo "starting docker"
sudo systemctl start docker
fi
sudo docker build -t bbilly1/tubearchivist:latest .
sudo docker push bbilly1/tubearchivist:latest
}
if [[ $1 == "blackhole" ]]; then
sync_blackhole
elif [[ $1 == "test" ]]; then
sync_test
elif [[ $1 == "docker" ]]; then
sync_docker
else
echo "valid options are: blackhole | test | docker"
fi
##
exit 0

45
docker-compose.yml Normal file
View File

@ -0,0 +1,45 @@
version: '3.3'
services:
tubearchivist:
container_name: tubearchivist
restart: always
image: bbilly1/tubearchivist:latest
ports:
- 8000:8000
volumes:
- ./volumes/tubearchivist/media:/youtube
- ./volumes/tubearchivist/cache:/cache
environment:
- ES_URL=http://archivist-es:9200
- REDIS_HOST=archivist-redis
- HOST_UID=1000
- HOST_GID=1000
depends_on:
- archivist-es
- archivist-redis
archivist-redis:
image: redislabs/rejson:latest
container_name: archivist-redis
restart: always
ports:
- 6379:6379
volumes:
- ./volumes/tubearchivist/redis:/data
depends_on:
- archivist-es
archivist-es:
image: docker.elastic.co/elasticsearch/elasticsearch:7.14.1
container_name: archivist-es
restart: always
environment:
- "discovery.type=single-node"
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
memlock:
soft: -1
hard: -1
volumes:
- ./volumes/tubearchivist/es:/usr/share/elasticsearch/data
ports:
- 9200:9200

18
nginx.conf Normal file
View File

@ -0,0 +1,18 @@
server {
listen 8000;
location /cache/ {
alias /cache/;
}
location /media/ {
alias /youtube/;
}
location / {
include uwsgi_params;
uwsgi_pass localhost:8080;
}
}

20
run.sh Normal file
View File

@ -0,0 +1,20 @@
#!/bin/bash
# startup script inside the container for tubearchivist
counter=0
until curl "$ES_URL" -fs; do
echo "waiting for elastic search to start"
counter=$((counter+1))
if [[ $counter -eq 12 ]]; then
# fail after 1 min
echo "failed to connect to elastic search, exiting..."
exit 1
fi
sleep 5
done
python manage.py migrate
python manage.py collectstatic
nginx &
celery -A home.tasks worker --loglevel=INFO --detach
uwsgi --ini uwsgi.ini

View File

View File

@ -0,0 +1,16 @@
"""
ASGI config for config project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()

View File

@ -0,0 +1,144 @@
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
from os import environ
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'Fvid^aUL6LohRZz*kZFvq85B&JW&kB9o*#jdzWsdWE8*XkCLR8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(environ.get('DJANGO_DEBUG'))
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'home.apps.HomeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'django.contrib.humanize'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# STATICFILES_DIRS = [
# str(BASE_DIR.joinpath('static')),
# '/cache/'
# ]
# STATIC_URL = '/static/'
STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),)
# MEDIA_ROOT = str(BASE_DIR.joinpath('media'))
# MEDIA_URL = '/media/'
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@ -0,0 +1,22 @@
"""config URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('home.urls')),
path('admin/', admin.site.urls),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for config project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_wsgi_application()

View File

@ -0,0 +1,40 @@
""" handle startup """
import os
from home.src.config import AppConfig
from home.src.helper import set_message
from home.src.index_management import index_check
from .tasks import app as celery_app
def sync_redis_state():
""" make sure redis gets the config.json values """
print('sync redis')
config = AppConfig().config
sort_order = config['archive']['sort']
set_message('sort_order', sort_order, expire=False)
hide_watched = bool(int(config['archive']['hide_watched']))
set_message('hide_watched', hide_watched, expire=False)
show_subed_only = bool(int(config['archive']['show_subed_only']))
set_message('show_subed_only', show_subed_only, expire=False)
def make_folders():
""" make needed folders here to avoid letting docker messing it up """
folders = ['download', 'channels', 'videos']
config = AppConfig().config
cache_dir = config['application']['cache_dir']
for folder in folders:
folder_path = os.path.join(cache_dir, folder)
try:
os.makedirs(folder_path)
except FileExistsError:
continue
__all__ = ('celery_app',)
make_folders()
sync_redis_state()
index_check()

View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class HomeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'home'

View File

@ -0,0 +1,25 @@
{
"archive": {
"sort": "published",
"hide_watched": false,
"show_subed_only": false,
"page_size": 12
},
"subscriptions": {
"auto_search": false,
"auto_download": false,
"channel_size": 50
},
"downloads": {
"limit_count": 5,
"limit_speed": false,
"sleep_interval": 3,
"format": "bestvideo[height<=720]+bestaudio/best[height<=720]"
},
"application": {
"cache_dir": "/cache",
"videos": "/youtube",
"file_template": "%(id)s_%(title)s.mp4",
"colors": "dark"
}
}

View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

View File

View File

View File

@ -0,0 +1,60 @@
"""
Functionality:
- read and write config
- load config variables into redis
- needs to be a separate module to avoid circular import
"""
import json
import os
from home.src.helper import get_message, set_message
class AppConfig:
""" handle user settings and application variables """
def __init__(self):
self.config = self.get_config()
def get_config(self):
""" get config from default file or redis if changed """
config = self.get_config_redis()
if not config:
with open('home/config.json', 'r', encoding="utf-8") as f:
config_str = f.read()
config = json.loads(config_str)
config['application']['REDIS_HOST'] = os.environ.get('REDIS_HOST')
config['application']['es_url'] = os.environ.get('ES_URL')
config['application']['HOST_UID'] = int(os.environ.get('HOST_UID'))
config['application']['HOST_GID'] = int(os.environ.get('HOST_GID'))
return config
@staticmethod
def get_config_redis():
""" read config json set from redis to overwrite defaults """
config = get_message('config')
if not list(config.values())[0]:
return False
return config
def update_config(self, form_post):
""" update config values from settings form """
config = self.config
for key, value in form_post.items():
to_write = value[0]
if len(to_write):
if to_write == '0':
to_write = False
elif to_write.isdigit():
to_write = int(to_write)
config_dict, config_value = key.split('.')
config[config_dict][config_value] = to_write
with open('home/config.json', 'w', encoding="utf-8") as f:
f.write(json.dumps(config))
set_message('config', config, expire=False)

View File

@ -0,0 +1,477 @@
"""
Functionality:
- handele the download queue
- manage subscriptions to channels
- downloading videos
"""
import json
import shutil
import os
from datetime import datetime
from time import sleep
import requests
import yt_dlp as youtube_dl
from home.src.index import YoutubeChannel, index_new_video
from home.src.config import AppConfig
from home.src.helper import clean_string, DurationConverter, set_message
class PendingList:
""" manage the pending videos list """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
VIDEOS = CONFIG['application']['videos']
@staticmethod
def parse_url_list(youtube_ids):
""" extract youtube ids from list """
missing_videos = []
for entry in youtube_ids:
url = entry['url']
url_type = entry['type']
if url_type == 'video':
missing_videos.append(url)
elif url_type == 'channel':
youtube_ids = ChannelSubscription().get_last_youtube_videos(
url, limit=False
)
missing_videos = missing_videos + youtube_ids
return missing_videos
def add_to_pending(self, missing_videos):
""" build the bulk json data from pending """
# check if channel is indexed
channel_handler = ChannelSubscription()
all_indexed = channel_handler.get_channels(subscribed_only=False)
all_channel_ids = [i['channel_id'] for i in all_indexed]
# check if already there
all_downloaded = self.get_all_downloaded()
# loop
bulk_list = []
for video in missing_videos:
if isinstance(video, str):
youtube_id = video
elif isinstance(video, tuple):
youtube_id = video[0]
if youtube_id in all_downloaded:
# skip already downlaoded
continue
video = self.get_youtube_details(youtube_id)
# skip on download error
if not video:
continue
if video['channel_id'] in all_channel_ids:
video['channel_indexed'] = True
else:
video['channel_indexed'] = False
video['status'] = "pending"
action = {"create": {"_id": youtube_id, "_index": "ta_download"}}
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(video))
# add last newline
bulk_list.append('\n')
query_str = '\n'.join(bulk_list)
headers = {'Content-type': 'application/x-ndjson'}
url = self.ES_URL + '/_bulk'
request = requests.post(url, data=query_str, headers=headers)
# notify
mess_dict = {
"status": "pending",
"level": "info",
"title": "Adding to download queue.",
"message": 'Processing IDs...'
}
set_message('progress:download', mess_dict)
if not request.ok:
print(request)
@staticmethod
def get_youtube_details(youtube_id):
""" get details from youtubedl for single pending video """
obs = {
'default_search': 'ytsearch',
'quiet': True,
'skip_download': True,
}
try:
vid = youtube_dl.YoutubeDL(obs).extract_info(youtube_id)
except youtube_dl.utils.DownloadError:
print('failed to extract info for: ' + youtube_id)
return False
# parse response
seconds = vid['duration']
duration_str = DurationConverter.get_str(seconds)
upload_date = vid['upload_date']
upload_dt = datetime.strptime(upload_date, "%Y%m%d")
published = upload_dt.strftime("%Y-%m-%d")
# build dict
youtube_details = {
"youtube_id": youtube_id,
"channel_name": vid['channel'],
"vid_thumb_url": vid['thumbnail'],
"title": vid['title'],
"channel_id": vid['channel_id'],
"duration": duration_str,
"published": published,
"timestamp": int(datetime.now().strftime("%s"))
}
return youtube_details
def get_all_pending(self):
""" get a list of all pending videos in ta_download """
headers = {'Content-type': 'application/json'}
# get PIT ID
url = self.ES_URL + '/ta_download/_pit?keep_alive=1m'
response = requests.post(url)
json_data = json.loads(response.text)
pit_id = json_data['id']
# query
data = {
"size": 50, "query": {"match_all": {}},
"pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [{"timestamp": {"order": "desc"}}]
}
query_str = json.dumps(data)
url = self.ES_URL + '/_search'
all_pending = []
all_ignore = []
while True:
response = requests.get(url, data=query_str, headers=headers)
json_data = json.loads(response.text)
all_hits = json_data['hits']['hits']
if all_hits:
for hit in all_hits:
youtube_id = hit['_source']['youtube_id']
status = hit['_source']['status']
if status == 'pending':
all_pending.append(hit['_source'])
elif status == 'ignore':
all_ignore.append(youtube_id)
search_after = hit['sort']
# update search_after with last hit data
data['search_after'] = search_after
query_str = json.dumps(data)
else:
break
# clean up PIT
query_str = json.dumps({"id": pit_id})
requests.delete(self.ES_URL + '/_pit', data=query_str, headers=headers)
return all_pending, all_ignore
def get_all_indexed(self):
""" get a list of all videos indexed """
headers = {'Content-type': 'application/json'}
# get PIT ID
url = self.ES_URL + '/ta_video/_pit?keep_alive=1m'
response = requests.post(url)
json_data = json.loads(response.text)
pit_id = json_data['id']
# query
data = {
"size": 500, "query": {"match_all": {}},
"pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [{"published": {"order": "desc"}}]
}
query_str = json.dumps(data)
url = self.ES_URL + '/_search'
all_indexed = []
while True:
response = requests.get(url, data=query_str, headers=headers)
json_data = json.loads(response.text)
all_hits = json_data['hits']['hits']
if all_hits:
for hit in all_hits:
all_indexed.append(hit)
search_after = hit['sort']
# update search_after with last hit data
data['search_after'] = search_after
query_str = json.dumps(data)
else:
break
# clean up PIT
query_str = json.dumps({"id": pit_id})
requests.delete(self.ES_URL + '/_pit', data=query_str, headers=headers)
return all_indexed
def get_all_downloaded(self):
""" get a list of all videos in archive """
all_channel_folders = os.listdir(self.VIDEOS)
all_downloaded = []
for channel_folder in all_channel_folders:
channel_path = os.path.join(self.VIDEOS, channel_folder)
all_videos = os.listdir(channel_path)
youtube_vids = [i[9:20] for i in all_videos]
for youtube_id in youtube_vids:
all_downloaded.append(youtube_id)
return all_downloaded
def delete_from_pending(self, youtube_id):
""" delete the youtube_id from ta_download """
url = f'{self.ES_URL}/ta_download/_doc/{youtube_id}'
response = requests.delete(url)
if not response.ok:
print(response.text)
def ignore_from_pending(self, ignore_list):
""" build the bulk query string """
stamp = int(datetime.now().strftime("%s"))
bulk_list = []
for youtube_id in ignore_list:
action = {"update": {"_id": youtube_id, "_index": "ta_download"}}
source = {"doc": {"status": 'ignore', "timestamp": stamp}}
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(source))
# add last newline
bulk_list.append('\n')
query_str = '\n'.join(bulk_list)
headers = {'Content-type': 'application/x-ndjson'}
url = self.ES_URL + '/_bulk'
request = requests.post(url, data=query_str, headers=headers)
mess_dict = {
"status": "ignore",
"level": "info",
"title": "Added to ignore list",
"message": ''
}
set_message('progress:download', mess_dict)
if not request.ok:
print(request)
class ChannelSubscription:
""" manage the list of channels subscribed """
def __init__(self):
config = AppConfig().config
self.es_url = config['application']['es_url']
self.channel_size = config['subscriptions']['channel_size']
def get_channels(self, subscribed_only=True):
""" get a list of all channels subscribed to """
headers = {'Content-type': 'application/json'}
# get PIT ID
url = self.es_url + '/ta_channel/_pit?keep_alive=1m'
response = requests.post(url)
json_data = json.loads(response.text)
pit_id = json_data['id']
# query
if subscribed_only:
data = {
"query": {"term": {"channel_subscribed": {"value": True}}},
"size": 50, "pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [{"channel_name.keyword": {"order": "asc"}}]
}
else:
data = {
"query": {"match_all": {}},
"size": 50, "pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [{"channel_name.keyword": {"order": "asc"}}]
}
query_str = json.dumps(data)
url = self.es_url + '/_search'
all_channels = []
while True:
response = requests.get(url, data=query_str, headers=headers)
json_data = json.loads(response.text)
all_hits = json_data['hits']['hits']
if all_hits:
for hit in all_hits:
source = hit['_source']
search_after = hit['sort']
all_channels.append(source)
# update search_after with last hit data
data['search_after'] = search_after
query_str = json.dumps(data)
else:
break
# clean up PIT
query_str = json.dumps({"id": pit_id})
requests.delete(self.es_url + '/_pit', data=query_str, headers=headers)
return all_channels
def get_last_youtube_videos(self, channel_id, limit=True):
""" get a list of last videos from channel """
url = f'https://www.youtube.com/channel/{channel_id}/videos'
obs = {
'default_search': 'ytsearch', 'quiet': True,
'skip_download': True, 'extract_flat': True
}
if limit:
obs['playlistend'] = self.channel_size
chan = youtube_dl.YoutubeDL(obs).extract_info(url, download=False)
last_videos = [(i['id'], i['title']) for i in chan['entries']]
return last_videos
def find_missing(self):
""" add missing videos from subscribed channels to pending """
all_channels = self.get_channels()
pending_handler = PendingList()
all_pending, all_ignore = pending_handler.get_all_pending()
all_pending_ids = [i['youtube_id'] for i in all_pending]
all_downloaded = pending_handler.get_all_downloaded()
to_ignore = all_pending_ids + all_ignore + all_downloaded
missing_videos = []
counter = 1
for channel in all_channels:
channel_id = channel['channel_id']
last_videos = self.get_last_youtube_videos(channel_id)
set_message('progress:download', {
"status": "rescan",
"level": "info",
"title": "Rescanning: Looking for new videos.",
"message": f'Progress: {counter}/{len(all_channels)}'
}
)
for video in last_videos:
youtube_id = video[0]
if youtube_id not in to_ignore:
missing_videos.append(youtube_id)
counter = counter + 1
return missing_videos
def change_subscribe(self, channel_id, channel_subscribed):
""" subscribe or unsubscribe from channel and update """
if not isinstance(channel_subscribed, bool):
print('invalid status, should be bool')
return
headers = {'Content-type': 'application/json'}
channel_handler = YoutubeChannel(channel_id)
channel_dict = channel_handler.channel_dict
channel_dict['channel_subscribed'] = channel_subscribed
if channel_subscribed:
# handle subscribe
url = self.es_url + '/ta_channel/_doc/' + channel_id
payload = json.dumps(channel_dict)
print(channel_dict)
else:
url = self.es_url + '/ta_channel/_update/' + channel_id
payload = json.dumps({'doc': channel_dict})
# update channel
request = requests.post(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
# sync to videos
channel_handler.sync_to_videos()
class VideoDownloader:
""" handle the video download functionality """
def __init__(self, youtube_id_list):
self.youtube_id_list = youtube_id_list
self.config = AppConfig().config
def download_list(self):
""" download the list of youtube_ids """
for youtube_id in self.youtube_id_list:
try:
self.dl_single_vid(youtube_id)
except youtube_dl.utils.DownloadError:
print('failed to download ' + youtube_id)
continue
vid_dict = index_new_video(youtube_id)
self.move_to_archive(vid_dict)
self.delete_from_pending(youtube_id)
if self.config['downloads']['sleep_interval']:
sleep(self.config['downloads']['sleep_interval'])
@staticmethod
def progress_hook(response):
""" process the progress_hooks from youtube_dl """
# title
filename = response['filename'][12:].replace('_', ' ')
title = "Downloading: " + os.path.split(filename)[-1]
# message
try:
percent = response['_percent_str']
size = response['_total_bytes_str']
speed = response['_speed_str']
eta = response['_eta_str']
message = f'{percent} of {size} at {speed} - time left: {eta}'
except KeyError:
message = ''
mess_dict = {
"status": "downloading",
"level": "info",
"title": title,
"message": message
}
set_message('progress:download', mess_dict)
def dl_single_vid(self, youtube_id):
""" download single video """
obs = {
'default_search': 'ytsearch',
'merge_output_format': 'mp4', 'restrictfilenames': True,
'outtmpl': (self.config['application']['cache_dir'] +
'/download/' +
self.config['application']['file_template']),
'progress_hooks': [self.progress_hook],
'quiet': True, 'continuedl': True, 'retries': 3
}
if self.config['downloads']['format']:
obs['format'] = self.config['downloads']['format']
if self.config['downloads']['limit_speed']:
obs['ratelimit'] = self.config['downloads']['limit_speed'] * 1024
external = False
if external:
obs['external_downloader'] = 'aria2c'
# check if already in cache to continue from there
cache_dir = self.config['application']['cache_dir']
all_cached = os.listdir(cache_dir + '/download/')
for file_name in all_cached:
if youtube_id in file_name:
obs['outtmpl'] = cache_dir + '/download/' + file_name
with youtube_dl.YoutubeDL(obs) as ydl:
try:
ydl.download([youtube_id])
except youtube_dl.utils.DownloadError:
print('retry failed download: ' + youtube_id)
sleep(10)
ydl.download([youtube_id])
def move_to_archive(self, vid_dict):
""" move downloaded video from cache to archive """
videos = self.config['application']['videos']
channel_name = vid_dict['channel']['channel_name']
channel_name_clean = clean_string(channel_name)
media_url = vid_dict['media_url']
youtube_id = vid_dict['youtube_id']
# make archive folder
videos = self.config['application']['videos']
new_folder = os.path.join(videos, channel_name_clean)
os.makedirs(new_folder, exist_ok=True)
# find real filename
cache_dir = self.config['application']['cache_dir']
for file_str in os.listdir(cache_dir + '/download'):
if youtube_id in file_str:
old_file = file_str
old_file_path = os.path.join(cache_dir, 'download', old_file)
new_file_path = os.path.join(videos, media_url)
# move and fix permission
shutil.move(old_file_path, new_file_path)
os.chown(
new_file_path,
self.config['application']['HOST_UID'],
self.config['application']['HOST_GID']
)
def delete_from_pending(self, youtube_id):
""" delete downloaded video from pending index if its there """
es_url = self.config['application']['es_url']
url = f'{es_url}/ta_download/_doc/{youtube_id}'
response = requests.delete(url)
if not response.ok and not response.status_code == 404:
print(response.text)

View File

@ -0,0 +1,145 @@
"""
Loose collection of helper functions
- don't import AppConfig class here to avoid circular imports
"""
import json
import os
import re
import string
import subprocess
import unicodedata
import requests
import redis
REDIS_HOST = os.environ.get('REDIS_HOST')
def get_total_hits(index, es_url, match_field):
""" get total hits from index """
headers = {'Content-type': 'application/json'}
data = {"query": {"match": {match_field: True}}}
payload = json.dumps(data)
url = f'{es_url}/{index}/_search?filter_path=hits.total'
request = requests.post(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
total_json = json.loads(request.text)
total_hits = total_json['hits']['total']['value']
return total_hits
def clean_string(file_name):
""" clean string to only asci characters """
whitelist = "-_.() " + string.ascii_letters + string.digits
normalized = unicodedata.normalize('NFKD', file_name)
ascii_only = normalized.encode('ASCII', 'ignore').decode().strip()
white_listed = ''.join(c for c in ascii_only if c in whitelist)
cleaned = re.sub(r'[ ]{2,}', ' ', white_listed)
return cleaned
def process_url_list(url_str):
""" parse url_list to find valid youtube video or channel ids """
url_list = re.split('\n+', url_str[0])
youtube_ids = []
for url in url_list:
url_clean = url.strip().split('/')[-1].replace('watch?v=', '')
url_no_param = url_clean.split('&')[0]
str_len = len(url_no_param)
if str_len == 11:
link_type = 'video'
elif str_len == 24:
link_type = 'channel'
youtube_ids.append({"url": url_no_param, "type": link_type})
return youtube_ids
def set_message(key, message, expire=True):
""" write new message to redis """
redis_connection = redis.Redis(host=REDIS_HOST)
redis_connection.execute_command(
'JSON.SET', key, '.', json.dumps(message)
)
if expire:
redis_connection.execute_command('EXPIRE', key, 20)
def get_message(key):
""" get any message from JSON key """
redis_connection = redis.Redis(host=REDIS_HOST)
reply = redis_connection.execute_command('JSON.GET', key)
if reply:
json_str = json.loads(reply)
else:
json_str = {"status": False}
return json_str
def get_dl_message(cache_dir):
""" get latest message if available """
redis_connection = redis.Redis(host=REDIS_HOST)
reply = redis_connection.execute_command('JSON.GET', 'progress:download')
if reply:
json_str = json.loads(reply)
elif json_str := monitor_cache_dir(cache_dir):
json_str = monitor_cache_dir(cache_dir)
else:
json_str = {"status": False}
return json_str
def monitor_cache_dir(cache_dir):
"""
look at download cache dir directly as alterative progress info
"""
dl_cache = os.path.join(cache_dir, 'download')
cache_file = os.listdir(dl_cache)
if cache_file:
filename = cache_file[0][12:].replace('_', ' ').split('.')[0]
mess_dict = {
"status": "downloading",
"level": "info",
"title": "Downloading: " + filename,
"message": ""
}
else:
return False
return mess_dict
class DurationConverter:
"""
using ffmpeg to get and parse duration from filepath
"""
@staticmethod
def get_sec(file_path):
""" read duration from file """
duration = subprocess.run([
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", file_path
], capture_output=True, check=True)
duration_sec = int(float(duration.stdout.decode().strip()))
return duration_sec
@staticmethod
def get_str(duration_sec):
""" takes duration in sec and returns clean string """
hours = duration_sec // 3600
minutes = (duration_sec - (hours * 3600)) // 60
secs = duration_sec - (hours * 3600) - (minutes * 60)
duration_str = str()
if hours:
duration_str = str(hours).zfill(2) + ':'
if minutes:
duration_str = duration_str + str(minutes).zfill(2) + ':'
else:
duration_str = duration_str + '00:'
duration_str = duration_str + str(secs).zfill(2)
return duration_str

View File

@ -0,0 +1,380 @@
"""
Functionality:
- index new videos into elastisearch
- extract video info with yt_dlp
- scrape youtube channel page if needed
"""
import json
import re
from datetime import datetime
from time import sleep
import os
import requests
import yt_dlp as youtube_dl
from bs4 import BeautifulSoup
from home.src.config import AppConfig
from home.src.helper import clean_string, DurationConverter
class YoutubeChannel:
""" represents a single youtube channel """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
CACHE_DIR = CONFIG['application']['cache_dir']
def __init__(self, channel_id):
self.channel_id = channel_id
self.json_data = None
self.source = None
self.channel_dict = self.build_channel_dict()
def build_channel_dict(self, scrape=False):
""" combine the dicts build from extracted json payload """
if scrape:
channel_dict = False
else:
channel_dict = self.get_es_channel()
if not channel_dict:
print('scrape data from youtube')
self.scrape_channel()
channel_dict = self.parse_channel_main()
channel_dict.update(self.parse_channel_meta())
self.source = 'scraped'
return channel_dict
def get_es_channel(self):
""" get from elastic search first if possible """
channel_id = self.channel_id
url = f'{self.ES_URL}/ta_channel/_doc/{channel_id}'
response = requests.get(url)
if response.ok:
channel_source = response.json()['_source']
self.source = 'elastic'
return channel_source
return False
def scrape_channel(self):
""" scrape channel page for additional infos """
channel_id = self.channel_id
url = f'https://www.youtube.com/channel/{channel_id}/about?hl=en'
response = requests.get(url)
if response.ok:
channel_page = response.text
else:
print(f'failed to extract channel info for: {channel_id}')
raise ConnectionError
soup = BeautifulSoup(channel_page, 'html.parser')
# load script into json
all_scripts = soup.find('body').find_all('script')
for script in all_scripts:
if 'var ytInitialData = ' in str(script):
script_content = str(script)
break
# extract payload
script_content = script_content.split('var ytInitialData = ')[1]
json_raw = script_content.rstrip(';</script>')
json_data = json.loads(json_raw)
# add to self
self.json_data = json_data
def parse_channel_main(self):
""" extract maintab values from scraped channel json data """
main_tab = self.json_data['header']['c4TabbedHeaderRenderer']
channel_name = main_tab['title']
last_refresh = int(datetime.now().strftime("%s"))
# channel_subs
try:
sub_text_simple = main_tab['subscriberCountText']['simpleText']
sub_text = sub_text_simple.split(' ')[0]
if sub_text[-1] == 'K':
channel_subs = int(float(sub_text.replace('K', ''))*1000)
elif sub_text[-1] == 'M':
channel_subs = int(float(sub_text.replace('M', ''))*1000000)
elif int(sub_text) >= 0:
channel_subs = int(sub_text)
else:
message = f'{sub_text} not dealt with'
print(message)
except KeyError:
channel_subs = 0
# banner
try:
all_banners = main_tab['banner']['thumbnails']
banner = sorted(all_banners, key=lambda k: k['width'])[-1]['url']
except KeyError:
banner = False
# build and return dict
main_channel_dict = {
'channel_active': True,
'channel_last_refresh': last_refresh,
'channel_subs': channel_subs,
'channel_banner_url': banner,
'channel_name': channel_name,
'channel_id': self.channel_id
}
return main_channel_dict
def parse_channel_meta(self):
""" extract meta tab values from channel payload """
# meta tab
json_data = self.json_data
meta_tab = json_data['metadata']['channelMetadataRenderer']
description = meta_tab['description']
all_thumbs = meta_tab['avatar']['thumbnails']
thumb_url = sorted(all_thumbs, key=lambda k: k['width'])[-1]['url']
# stats tab
renderer = 'twoColumnBrowseResultsRenderer'
all_tabs = json_data['contents'][renderer]['tabs']
for tab in all_tabs:
if 'tabRenderer' in tab.keys():
if tab['tabRenderer']['title'] == 'About':
about_tab = (tab['tabRenderer']['content']
['sectionListRenderer']['contents'][0]
['itemSectionRenderer']['contents'][0]
['channelAboutFullMetadataRenderer'])
break
try:
channel_views_text = about_tab['viewCountText']['simpleText']
channel_views = int(re.sub(r"\D", "", channel_views_text))
except KeyError:
channel_views = 0
meta_channel_dict = {
'channel_description': description,
'channel_thumb_url': thumb_url,
'channel_views': channel_views
}
return meta_channel_dict
def upload_to_es(self):
""" upload channel data to elastic search """
url = f'{self.ES_URL}/ta_channel/_doc/{self.channel_id}'
response = requests.put(url, json=self.channel_dict)
print(f'added {self.channel_id} to es')
if not response.ok:
print(response.text)
def clear_cache(self):
""" delete banner and thumb from cache if available """
channel_cache = os.path.join(self.CACHE_DIR, 'channels')
thumb = os.path.join(channel_cache, self.channel_id + '_thumb.jpg')
banner = os.path.join(channel_cache, self.channel_id + '_banner.jpg')
if os.path.exists(thumb):
os.remove(thumb)
if os.path.exists(banner):
os.remove(banner)
def sync_to_videos(self):
""" sync new channel_dict to all videos of channel """
headers = {'Content-type': 'application/json'}
channel_id = self.channel_id
# add ingest pipeline
processors = []
for field, value in self.channel_dict.items():
line = {"set": {"field": "channel." + field, "value": value}}
processors.append(line)
data = {
"description": channel_id,
"processors": processors
}
payload = json.dumps(data)
url = self.ES_URL + '/_ingest/pipeline/' + channel_id
request = requests.put(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
# apply pipeline
data = {
"query": {"match": {"channel.channel_id": channel_id}}
}
payload = json.dumps(data)
url = self.ES_URL + '/ta_video/_update_by_query?pipeline=' + channel_id
request = requests.post(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
def get_total_hits(self):
""" get total channels indexed """
headers = {'Content-type': 'application/json'}
data = {"query": {"match_all": {}}}
payload = json.dumps(data)
url = f'{self.ES_URL}/ta_channel/_search?filter_path=hits.total'
request = requests.post(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
total_hits = json.loads(request.text)['hits']['total']['value']
return total_hits
class YoutubeVideo:
""" represents a signle youtube video """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
CACHE_DIR = CONFIG['application']['cache_dir']
def __init__(self, youtube_id):
self.youtube_id = youtube_id
self.channel_id = None
self.vid_dict = self.get_wrapper()
def get_wrapper(self):
""" wrapper to loop around youtube_dl to retry on failure """
print(f'get video data for {self.youtube_id}')
for i in range(3):
try:
vid_dict = self.get_youtubedl_vid_data()
except KeyError as e:
print(e)
sleep((i + 1) ** 2)
continue
else:
break
return vid_dict
def get_youtubedl_vid_data(self):
""" parse youtubedl extract info """
youtube_id = self.youtube_id
obs = {
'quiet': True,
'default_search': 'ytsearch',
'skip_download': True
}
try:
vid = youtube_dl.YoutubeDL(obs).extract_info(youtube_id)
except (
youtube_dl.utils.ExtractorError,
youtube_dl.utils.DownloadError
):
print('failed to get info for ' + youtube_id)
return False
# extract
self.channel_id = vid['channel_id']
upload_date = vid['upload_date']
upload_date_time = datetime.strptime(upload_date, "%Y%m%d")
published = upload_date_time.strftime("%Y-%m-%d")
last_refresh = int(datetime.now().strftime("%s"))
# likes
try:
like_count = vid['like_count']
except KeyError:
like_count = 0
try:
dislike_count = vid['dislike_count']
except KeyError:
dislike_count = 0
# build dicts
stats = {
"view_count": vid['view_count'],
"like_count": like_count,
"dislike_count": dislike_count,
"average_rating": vid['average_rating']
}
vid_basic = {
"title": vid['title'],
"description": vid['description'],
"category": vid['categories'],
"vid_thumb_url": vid['thumbnail'],
"tags": vid['tags'],
"published": published,
"stats": stats,
"vid_last_refresh": last_refresh,
"date_downloaded": last_refresh,
"youtube_id": youtube_id,
"active": True,
"channel": False
}
return vid_basic
def add_new_player(self):
""" add player information for new videos """
cache_path = self.CACHE_DIR + '/download/'
all_cached = os.listdir(cache_path)
for file_cached in all_cached:
if self.youtube_id in file_cached:
vid_path = os.path.join(cache_path, file_cached)
duration_handler = DurationConverter()
duration = duration_handler.get_sec(vid_path)
duration_str = duration_handler.get_str(duration)
player = {
"watched": False,
"duration": duration,
"duration_str": duration_str
}
break
self.vid_dict['player'] = player
def build_file_path(self, channel_name):
""" build media_url from where file will be located """
clean_channel_name = clean_string(channel_name)
timestamp = self.vid_dict['published'].replace('-', '')
youtube_id = self.vid_dict['youtube_id']
title = self.vid_dict['title']
clean_title = clean_string(title)
filename = f'{timestamp}_{youtube_id}_{clean_title}.mp4'
media_url = os.path.join(clean_channel_name, filename)
self.vid_dict['media_url'] = media_url
def get_es_data(self):
""" get current data from elastic search """
url = self.ES_URL + '/ta_video/_doc/' + self.youtube_id
response = requests.get(url)
if not response.ok:
print(response.text)
es_vid_dict = json.loads(response.text)
return es_vid_dict
def upload_to_es(self):
""" upload channel data to elastic search """
url = f'{self.ES_URL}/ta_video/_doc/{self.youtube_id}'
response = requests.put(url, json=self.vid_dict)
if not response.ok:
print(response.text)
def delete_cache(self):
""" delete thumbnail from cache if exist """
video_cache = os.path.join(self.CACHE_DIR, 'videos')
thumb = os.path.join(video_cache, self.youtube_id + '.jpg')
if os.path.exists(thumb):
os.remove(thumb)
def deactivate(self):
""" deactivate document on extractor error """
youtube_id = self.youtube_id
headers = {'Content-type': 'application/json'}
url = f'{self.ES_URL}/ta_video/_update/{youtube_id}'
data = {"script": "ctx._source.active = false"}
json_str = json.dumps(data)
response = requests.post(url, data=json_str, headers=headers)
print(f'deactivated {youtube_id}')
if not response.ok:
print(response.text)
def index_new_video(youtube_id):
""" combine video and channel classes for new video index """
vid_handler = YoutubeVideo(youtube_id)
channel_handler = YoutubeChannel(vid_handler.channel_id)
# add filepath to vid_dict
channel_name = channel_handler.channel_dict['channel_name']
vid_handler.build_file_path(channel_name)
# add channel and player to video
vid_handler.add_new_player()
vid_handler.vid_dict['channel'] = channel_handler.channel_dict
# add new channel to es
if channel_handler.source == 'scraped':
channel_handler.channel_dict['channel_subscribed'] = False
channel_handler.upload_to_es()
# upload video to es
vid_handler.upload_to_es()
# return vid_dict for further processing
return vid_handler.vid_dict

View File

@ -0,0 +1,517 @@
"""
Functionality:
- initial elastic search setup
- index configuration is represented in INDEX_CONFIG
- index mapping and settings validation
- backup and restore
"""
import json
import os
from datetime import datetime
import requests
from home.src.config import AppConfig
# expected mapping and settings
INDEX_CONFIG = [
{
'index_name': 'channel',
'expected_map': {
"channel_id": {
"type": "keyword",
},
"channel_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "to_lower"
},
"search_as_you_type": {
"type": "search_as_you_type",
"doc_values": False,
"max_shingle_size": 3
}
}
},
"channel_banner_url": {
"type": "keyword",
"index": False
},
"channel_thumb_url": {
"type": "keyword",
"index": False
},
"channel_description": {
"type": "text"
},
"channel_last_refresh": {
"type": "date",
"format": "epoch_second"
}
},
'expected_set': {
"analysis": {
"normalizer": {
"to_lower": {
"type": "custom",
"filter": ["lowercase"]
}
}
},
"number_of_replicas": 0
}
},
{
'index_name': 'video',
'expected_map': {
"vid_thumb_url": {
"type": "text",
"index": False
},
"date_downloaded": {
"type": "date"
},
"channel": {
"properties": {
"channel_id": {
"type": "keyword",
},
"channel_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "to_lower"
},
"search_as_you_type": {
"type": "search_as_you_type",
"doc_values": False,
"max_shingle_size": 3
}
}
},
"channel_banner_url": {
"type": "keyword",
"index": False
},
"channel_thumb_url": {
"type": "keyword",
"index": False
},
"channel_description": {
"type": "text"
},
"channel_last_refresh": {
"type": "date",
"format": "epoch_second"
}
}
},
"description": {
"type": "text"
},
"media_url": {
"type": "keyword",
"index": False
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "to_lower"
},
"search_as_you_type": {
"type": "search_as_you_type",
"doc_values": False,
"max_shingle_size": 3
}
}
},
"vid_last_refresh": {
"type": "date"
},
"youtube_id": {
"type": "keyword"
},
"published": {
"type": "date"
},
},
'expected_set': {
"analysis": {
"normalizer": {
"to_lower": {
"type": "custom",
"filter": ["lowercase"]
}
}
},
"number_of_replicas": 0
}
},
{
'index_name': 'download',
'expected_map': {
"timestamp": {
"type": "date"
},
"channel_id": {
"type": "keyword"
},
"channel_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "to_lower"
}
}
},
"status": {
"type": "keyword"
},
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "to_lower"
}
}
},
"vid_thumb_url": {
"type": "keyword"
},
"youtube_id": {
"type": "keyword"
}
},
'expected_set': {
"analysis": {
"normalizer": {
"to_lower": {
"type": "custom",
"filter": ["lowercase"]
}
}
},
"number_of_replicas": 0
}
}
]
class ElasticIndex:
"""
handle mapping and settings on elastic search for a given index
"""
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
HEADERS = {'Content-type': 'application/json'}
def __init__(self, index_name, expected_map, expected_set):
self.index_name = index_name
self.expected_map = expected_map
self.expected_set = expected_set
self.exists, self.details = self.index_exists()
def index_exists(self):
""" check if index already exists and return mapping if it does """
index_name = self.index_name
url = f'{self.ES_URL}/ta_{index_name}'
response = requests.get(url)
exists = response.ok
if exists:
details = response.json()[f'ta_{index_name}']
else:
details = False
return exists, details
def validate(self):
"""
check if all expected mappings and settings match
returns True when rebuild is needed
"""
if self.expected_map:
rebuild = self.validate_mappings()
if rebuild:
return rebuild
if self.expected_set:
rebuild = self.validate_settings()
if rebuild:
return rebuild
return False
def validate_mappings(self):
""" check if all mappings are as expected """
expected_map = self.expected_map
now_map = self.details['mappings']['properties']
for key, value in expected_map.items():
# nested
if list(value.keys()) == ['properties']:
for key_n, value_n in value['properties'].items():
if key_n not in now_map[key]['properties'].keys():
print(key_n, value_n)
return True
if not value_n == now_map[key]['properties'][key_n]:
print(key_n, value_n)
return True
continue
# not nested
if key not in now_map.keys():
print(key, value)
return True
if not value == now_map[key]:
print(key, value)
return True
return False
def validate_settings(self):
""" check if all settings are as expected """
now_set = self.details['settings']['index']
for key, value in self.expected_set.items():
if key not in now_set.keys():
print(key, value)
return True
if not value == now_set[key]:
print(key, value)
return True
return False
def rebuild_index(self):
""" rebuild with new mapping """
# backup
self.reindex('backup')
# delete original
self.delete_index(backup=False)
# create new
self.create_blank()
self.reindex('restore')
# delete backup
self.delete_index()
def reindex(self, method):
""" create on elastic search """
index_name = self.index_name
if method == 'backup':
source = f'ta_{index_name}'
destination = f'ta_{index_name}_backup'
elif method == 'restore':
source = f'ta_{index_name}_backup'
destination = f'ta_{index_name}'
query = {
"source": {
"index": source
},
"dest": {
"index": destination
}
}
data = json.dumps(query)
url = self.ES_URL + '/_reindex?refresh=true'
response = requests.post(url=url, data=data, headers=self.HEADERS)
if not response.ok:
print(response.text)
def delete_index(self, backup=True):
""" delete index passed as argument """
if backup:
url = f'{self.ES_URL}/ta_{self.index_name}_backup'
else:
url = f'{self.ES_URL}/ta_{self.index_name}'
response = requests.delete(url)
if not response.ok:
print(response.text)
def create_blank(self):
""" apply new mapping and settings for blank new index """
expected_map = self.expected_map
expected_set = self.expected_set
# stich payload
payload = {}
if expected_set:
payload.update({"settings": expected_set})
if expected_map:
payload.update({"mappings": {"properties": expected_map}})
# create
url = f'{self.ES_URL}/ta_{self.index_name}'
data = json.dumps(payload)
response = requests.put(url=url, data=data, headers=self.HEADERS)
if not response.ok:
print(response.text)
class ElasticBackup:
""" dump index to nd-json files for later bulk import """
def __init__(self, index_config):
self.config = AppConfig().config
self.index_config = index_config
self.timestamp = datetime.now().strftime('%Y%m%d')
def get_all_documents(self, index_name):
""" export all documents of a single index """
headers = {'Content-type': 'application/json'}
es_url = self.config['application']['es_url']
# get PIT ID
url = f'{es_url}/ta_{index_name}/_pit?keep_alive=1m'
response = requests.post(url)
json_data = json.loads(response.text)
pit_id = json_data['id']
# build query
data = {
"query": {"match_all": {}},
"size": 100, "pit": {"id": pit_id, "keep_alive": "1m"},
"sort": [ {"_id": {"order": "asc"}} ]
}
query_str = json.dumps(data)
url = es_url + '/_search'
# loop until nothing left
all_results = []
while True:
response = requests.get(url, data=query_str, headers=headers)
json_data = json.loads(response.text)
all_hits = json_data['hits']['hits']
if all_hits:
for hit in all_hits:
search_after = hit['sort']
all_results.append(hit)
# update search_after with last hit data
data['search_after'] = search_after
query_str = json.dumps(data)
else:
break
# clean up PIT
query_str = json.dumps({"id": pit_id})
requests.delete(es_url + '/_pit', data=query_str, headers=headers)
return all_results
@staticmethod
def build_bulk(all_results):
""" build bulk query data from all_results """
bulk_list = []
for document in all_results:
document_id = document['_id']
es_index = document['_index']
action = { "index" : { "_index": es_index, "_id": document_id } }
source = document['_source']
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(source))
# add last newline
bulk_list.append('\n')
file_content = '\n'.join(bulk_list)
return file_content
def write_json_file(self, file_content, index_name):
""" write json file to disk """
cache_dir = self.config['application']['cache_dir']
file_name = f'ta_{index_name}-{self.timestamp}.json'
file_path = os.path.join(cache_dir, file_name)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(file_content)
def post_bulk_restore(self, file_name):
""" send bulk to es """
cache_dir = self.config['application']['cache_dir']
es_url = self.config['application']['es_url']
headers = {'Content-type': 'application/x-ndjson'}
file_path = os.path.join(cache_dir, file_name)
with open(file_path, 'r', encoding='utf-8') as f:
query_str = f.read()
url = es_url + '/_bulk'
request = requests.post(url, data=query_str, headers=headers)
if not request.ok:
print(request.text)
def restore_from_file(self):
""" restore all available backup files """
cache_dir = self.config['application']['cache_dir']
all_available_backups = [
i for i in os.listdir(cache_dir) if
i.startswith('ta_') and i.endswith('.json')
]
for file_name in all_available_backups:
self.post_bulk_restore(file_name)
def backup_all_indexes():
""" backup all es indexes to disk """
backup_handler = ElasticBackup(INDEX_CONFIG)
for index in backup_handler.index_config:
index_name = index['index_name']
all_results = backup_handler.get_all_documents(index_name)
file_content = backup_handler.build_bulk(all_results)
backup_handler.write_json_file(file_content, index_name)
def restore_from_backup():
""" restore indexes from backup file """
# delete
index_check(force_restore=True)
# recreate
backup_handler = ElasticBackup(INDEX_CONFIG)
backup_handler.restore_from_file()
def index_check(force_restore=False):
""" check if all indexes are created and have correct mapping """
for index in INDEX_CONFIG:
index_name = index['index_name']
expected_map = index['expected_map']
expected_set = index['expected_set']
handler = ElasticIndex(index_name, expected_map, expected_set)
# force restore
if force_restore:
handler.delete_index(backup=False)
handler.create_blank()
continue
# create new
if not handler.exists:
print(f'create new blank index with name ta_{index_name}...')
handler.create_blank()
continue
# validate index
rebuild = handler.validate()
if rebuild:
print(f'applying new mappings to index ta_{index_name}...')
handler.rebuild_index()
continue
# else all good
print(f'ta_{index_name} index is created and up to date...')

View File

@ -0,0 +1,347 @@
"""
Functionality:
- reindexing old documents
- syncing updated values between indexes
- scan the filesystem to delete or index
"""
import json
import os
from datetime import datetime
from time import sleep
from math import ceil
import requests
from home.src.download import ChannelSubscription, PendingList
from home.src.config import AppConfig
from home.src.index import (
YoutubeChannel,
YoutubeVideo,
index_new_video
)
from home.src.helper import get_total_hits, clean_string, set_message
class Reindex:
""" check for outdated documents and refresh data from youtube """
def __init__(self):
self.video_daily, self.channel_daily = self.get_daily()
self.all_youtube_ids = False
self.all_channel_ids = False
# config
config = AppConfig().config
self.sleep_interval = config['downloads']['sleep_interval']
self.es_url = config['application']['es_url']
self.refresh_interval = 90
def get_daily(self):
""" get daily refresh values """
total_videos = get_total_hits(
'ta_video', self.es_url, 'active'
)
video_daily = ceil(total_videos / self.refresh_interval * 1.2)
total_channels = get_total_hits(
'ta_channel', self.es_url, 'channel_active'
)
channel_daily = ceil(total_channels / self.refresh_interval * 1.2)
return (video_daily, channel_daily)
def get_outdated_vids(self):
""" get daily videos to refresh """
headers = {'Content-type': 'application/json'}
now = int(datetime.now().strftime("%s"))
now_3m = now - 3 * 30 * 24 * 60 * 60
size = self.video_daily
data = {
"size": size,
"query": {
"bool": {
"must": [
{"match": {"active": True}},
{"range": {"vid_last_refresh": {"lte": now_3m}}}
]
}
},
"sort": [{"vid_last_refresh": {"order": "asc"}}], "_source": False
}
query_str = json.dumps(data)
url = self.es_url + '/ta_video/_search'
response = requests.get(url, data=query_str, headers=headers)
if not response.ok:
print(response.text)
response_dict = json.loads(response.text)
all_youtube_ids = [i['_id'] for i in response_dict['hits']['hits']]
return all_youtube_ids
def get_outdated_channels(self):
""" get daily channels to refresh """
headers = {'Content-type': 'application/json'}
now = int(datetime.now().strftime("%s"))
now_3m = now - 3 * 30 * 24 * 60 * 60
size = self.channel_daily
data = {
"size": size,
"query": {
"bool": {
"must": [
{"match": {"channel_active": True}},
{"range": {"channel_last_refresh": {"lte": now_3m}}}
]
}
},
"sort": [{"channel_last_refresh": {"order": "asc"}}],
"_source": False
}
query_str = json.dumps(data)
url = self.es_url + '/ta_channel/_search'
response = requests.get(url, data=query_str, headers=headers)
if not response.ok:
print(response.text)
response_dict = json.loads(response.text)
all_channel_ids = [i['_id'] for i in response_dict['hits']['hits']]
return all_channel_ids
def check_outdated(self):
""" add missing vids and channels """
self.all_youtube_ids = self.get_outdated_vids()
self.all_channel_ids = self.get_outdated_channels()
def rescrape_all_channels(self):
""" sync new data from channel to all matching videos """
sleep_interval = self.sleep_interval
channel_sub_handler = ChannelSubscription()
all_channels = channel_sub_handler.get_channels(
subscribed_only=False
)
all_channel_ids = [i['channel_id'] for i in all_channels]
counter = 1
for channel_id in all_channel_ids:
message = f'Progress: {counter}/{len(all_channels)}'
mess_dict = {
"status": "scraping",
"level": "info",
"title": "Scraping all youtube channels",
"message": message
}
set_message('progress:download', mess_dict)
channel_index = YoutubeChannel(channel_id)
subscribed = channel_index.channel_dict['channel_subscribed']
channel_index.channel_dict = channel_index.build_channel_dict(
scrape=True
)
channel_index.channel_dict['channel_subscribed'] = subscribed
channel_index.upload_to_es()
channel_index.sync_to_videos()
counter = counter + 1
if sleep_interval:
sleep(sleep_interval)
@staticmethod
def reindex_single_video(youtube_id):
""" refresh data for single video """
vid_handler = YoutubeVideo(youtube_id)
if not vid_handler.vid_dict:
# stop if deactivated
vid_handler.deactivate()
return
es_vid_dict = vid_handler.get_es_data()
player = es_vid_dict['_source']['player']
date_downloaded = es_vid_dict['_source']['date_downloaded']
channel_dict = es_vid_dict['_source']['channel']
channel_name = channel_dict['channel_name']
vid_handler.build_file_path(channel_name)
# add to vid_dict
vid_handler.vid_dict['player'] = player
vid_handler.vid_dict['date_downloaded'] = date_downloaded
vid_handler.vid_dict['channel'] = channel_dict
# update
vid_handler.upload_to_es()
vid_handler.delete_cache()
@staticmethod
def reindex_single_channel(channel_id):
""" refresh channel data and sync to videos """
channel_handler = YoutubeChannel(channel_id)
subscribed = channel_handler.channel_dict['channel_subscribed']
channel_handler.channel_dict = channel_handler.build_channel_dict(
scrape=True
)
channel_handler.channel_dict['channel_subscribed'] = subscribed
channel_handler.upload_to_es()
channel_handler.sync_to_videos()
channel_handler.clear_cache()
def reindex(self):
""" reindex what's needed """
# videos
for youtube_id in self.all_youtube_ids:
self.reindex_single_video(youtube_id)
if self.sleep_interval:
sleep(self.sleep_interval)
# channels
for channel_id in self.all_channel_ids:
self.reindex_single_channel(channel_id)
if self.sleep_interval:
sleep(self.sleep_interval)
class FilesystemScanner:
""" handle scanning and fixing from filesystem """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
VIDEOS = CONFIG['application']['videos']
def __init__(self):
self.all_downloaded = self.get_all_downloaded()
self.all_indexed = self.get_all_indexed()
self.missmatch = None
self.to_rename = None
self.to_index = None
self.to_delete = None
def get_all_downloaded(self):
""" get a list of all video files downloaded """
all_channels = os.listdir(self.VIDEOS)
all_channels.sort()
all_downloaded = []
for channel_name in all_channels:
channel_path = os.path.join(self.VIDEOS, channel_name)
for video in os.listdir(channel_path):
youtube_id = video[9:20]
all_downloaded.append((channel_name, video, youtube_id))
return all_downloaded
@staticmethod
def get_all_indexed():
""" get a list of all indexed videos """
index_handler = PendingList()
all_indexed_raw = index_handler.get_all_indexed()
all_indexed = []
for video in all_indexed_raw:
youtube_id = video['_id']
media_url = video['_source']['media_url']
published = video['_source']['published']
title = video['_source']['title']
all_indexed.append((youtube_id, media_url, published, title))
return all_indexed
def list_comarison(self):
""" compare the lists to figure out what to do """
self.find_unindexed()
self.find_missing()
self.find_bad_media_url()
def find_unindexed(self):
""" find video files without a matching document indexed """
all_indexed_ids = [i[0] for i in self.all_indexed]
to_index = []
for downloaded in self.all_downloaded:
if downloaded[2] not in all_indexed_ids:
to_index.append(downloaded)
self.to_index = to_index
def find_missing(self):
""" find indexed videos without matching media file """
all_downloaded_ids = [i[2] for i in self.all_downloaded]
to_delete = []
for video in self.all_indexed:
youtube_id = video[0]
if youtube_id not in all_downloaded_ids:
to_delete.append(video)
self.to_delete = to_delete
def find_bad_media_url(self):
""" rename media files not matching the indexed title """
to_fix = []
to_rename = []
for downloaded in self.all_downloaded:
channel, filename, downloaded_id = downloaded
# find in indexed
for indexed in self.all_indexed:
indexed_id, media_url, published, title = indexed
if indexed_id == downloaded_id:
# found it
title_c = clean_string(title)
pub = published.replace('-', '')
expected_filename = f'{pub}_{indexed_id}_{title_c}.mp4'
new_url = os.path.join(channel, expected_filename)
if expected_filename != filename:
# file to rename
to_rename.append(
(channel, filename, expected_filename)
)
if media_url != new_url:
# media_url to update in es
to_fix.append((indexed_id, new_url))
break
self.missmatch = to_fix
self.to_rename = to_rename
def rename_files(self):
""" rename media files as identified by find_bad_media_url """
for bad_filename in self.to_rename:
channel, filename, expected_filename = bad_filename
old_path = os.path.join(self.VIDEOS, channel, filename)
new_path = os.path.join(self.VIDEOS, channel, expected_filename)
os.rename(old_path, new_path)
def send_missmatch_bulk(self):
""" build bulk update """
bulk_list = []
for video_missmatch in self.missmatch:
youtube_id, media_url = video_missmatch
action = {"update": {"_id": youtube_id, "_index": 'ta_video'}}
source = {"doc": {"media_url": media_url}}
bulk_list.append(json.dumps(action))
bulk_list.append(json.dumps(source))
# add last newline
bulk_list.append('\n')
query_str = '\n'.join(bulk_list)
# make the call
headers = {'Content-type': 'application/x-ndjson'}
url = self.ES_URL + '/_bulk'
request = requests.post(url, data=query_str, headers=headers)
if not request.ok:
print(request.text)
def delete_from_index(self):
""" find indexed but deleted mediafile """
for indexed in self.to_delete:
youtube_id, _ = indexed
url = self.ES_URL + '/ta_video/_doc/' + youtube_id
request = requests.delete(url)
if not request.ok:
print(request.text)
def scan_filesystem():
""" grouped function to delete and update index """
filesystem_handler = FilesystemScanner()
filesystem_handler.list_comarison()
if filesystem_handler.to_rename:
filesystem_handler.rename_files()
if filesystem_handler.missmatch:
filesystem_handler.send_missmatch_bulk()
if filesystem_handler.to_delete:
filesystem_handler.delete_from_index()
if filesystem_handler.to_index:
for missing_vid in filesystem_handler.to_index:
youtube_id = missing_vid[2]
index_new_video(youtube_id)
def reindex_old_documents():
""" daily refresh of old documents """
reindex_handler = Reindex()
reindex_handler.check_outdated()
reindex_handler.reindex()

View File

@ -0,0 +1,237 @@
"""
Functionality:
- handle search to populate results to view
- cache youtube video thumbnails and channel artwork
- parse values in hit_cleanup for frontend
- calculate pagination values
"""
import math
import os
import urllib.parse
from datetime import datetime
import requests
from PIL import Image
from home.src.config import AppConfig
class SearchHandler:
""" search elastic search """
CONFIG = AppConfig().config
CACHE_DIR = CONFIG['application']['cache_dir']
def __init__(self, url, data, cache=True):
self.max_hits = None
self.url = url
self.data = data
self.cache = cache
def get_data(self):
""" get the data """
if self.data:
response = requests.get(self.url, json=self.data).json()
else:
response = requests.get(self.url).json()
if 'hits' in response.keys():
self.max_hits = response['hits']['total']['value']
return_value = response['hits']['hits']
else:
# simulate list for single result to reuse rest of class
return_value = [response]
# stop if empty
if not return_value:
return False
all_videos = []
all_channels = []
for idx, hit in enumerate(return_value):
return_value[idx] = self.hit_cleanup(hit)
if hit['_index'] == 'ta_video':
video_dict, channel_dict = self.vid_cache_link(hit)
if video_dict not in all_videos:
all_videos.append(video_dict)
if channel_dict not in all_channels:
all_channels.append(channel_dict)
elif hit['_index'] == 'ta_channel':
channel_dict = self.channel_cache_link(hit)
if channel_dict not in all_channels:
all_channels.append(channel_dict)
if self.cache:
# validate cache
self.cache_dl_vids(all_videos)
self.cache_dl_chan(all_channels)
return return_value
@staticmethod
def vid_cache_link(hit):
""" download thumbnails into chache """
vid_thumb = hit['source']['vid_thumb_url']
youtube_id = hit['source']['youtube_id']
channel_id_hit = hit['source']['channel']['channel_id']
chan_thumb = hit['source']['channel']['channel_thumb_url']
try:
chan_banner = hit['source']['channel']['channel_banner_url']
except KeyError:
chan_banner = False
video_dict = {
'youtube_id': youtube_id,
'vid_thumb': vid_thumb
}
channel_dict = {
'channel_id': channel_id_hit,
'chan_thumb': chan_thumb,
'chan_banner': chan_banner
}
return video_dict, channel_dict
@staticmethod
def channel_cache_link(hit):
""" build channel thumb links """
channel_id_hit = hit['source']['channel_id']
chan_thumb = hit['source']['channel_thumb_url']
try:
chan_banner = hit['source']['channel_banner_url']
except KeyError:
chan_banner = False
channel_dict = {
'channel_id': channel_id_hit,
'chan_thumb': chan_thumb,
'chan_banner': chan_banner
}
return channel_dict
def cache_dl_vids(self, all_videos):
""" video thumbs links for cache """
vid_cache = os.path.join(self.CACHE_DIR, 'videos')
all_vid_cached = os.listdir(vid_cache)
# videos
for video_dict in all_videos:
youtube_id = video_dict['youtube_id']
if not youtube_id + '.jpg' in all_vid_cached:
cache_path = os.path.join(vid_cache, youtube_id + '.jpg')
thumb_url = video_dict['vid_thumb']
img_raw = requests.get(thumb_url, stream=True).raw
img = Image.open(img_raw)
width, height = img.size
if not width / height == 16 / 9:
new_height = width / 16 * 9
offset = (height - new_height) / 2
img = img.crop((0, offset, width, height - offset))
img.save(cache_path)
def cache_dl_chan(self, all_channels):
""" download channel thumbs """
chan_cache = os.path.join(self.CACHE_DIR, 'channels')
all_chan_cached = os.listdir(chan_cache)
for channel_dict in all_channels:
channel_id_cache = channel_dict['channel_id']
channel_banner_url = channel_dict['chan_banner']
channel_banner = channel_id_cache + '_banner.jpg'
channel_thumb_url = channel_dict['chan_thumb']
channel_thumb = channel_id_cache + '_thumb.jpg'
# thumb
if channel_thumb_url and channel_thumb not in all_chan_cached:
cache_path = os.path.join(chan_cache, channel_thumb)
img_raw = requests.get(channel_thumb_url, stream=True).content
with open(cache_path, 'wb') as f:
f.write(img_raw)
# banner
if channel_banner_url and channel_banner not in all_chan_cached:
cache_path = os.path.join(chan_cache, channel_banner)
img_raw = requests.get(channel_banner_url, stream=True).content
with open(cache_path, 'wb') as f:
f.write(img_raw)
@staticmethod
def hit_cleanup(hit):
""" clean up and parse data from a single hit """
hit['source'] = hit.pop('_source')
hit_keys = hit['source'].keys()
if 'media_url' in hit_keys:
parsed_url = urllib.parse.quote(hit['source']['media_url'])
hit['source']['media_url'] = parsed_url
if 'published' in hit_keys:
published = hit['source']['published']
date_pub = datetime.strptime(published, "%Y-%m-%d")
date_str = datetime.strftime(date_pub, "%d %b, %Y")
hit['source']['published'] = date_str
if 'vid_last_refresh' in hit_keys:
vid_last_refresh = hit['source']['vid_last_refresh']
date_refresh = datetime.fromtimestamp(vid_last_refresh)
date_str = datetime.strftime(date_refresh, "%d %b, %Y")
hit['source']['vid_last_refresh'] = date_str
if 'channel_last_refresh' in hit_keys:
refreshed = hit['source']['channel_last_refresh']
date_refresh = datetime.fromtimestamp(refreshed)
date_str = datetime.strftime(date_refresh, "%d %b, %Y")
hit['source']['channel_last_refresh'] = date_str
if 'channel' in hit_keys:
channel_keys = hit['source']['channel'].keys()
if 'channel_last_refresh' in channel_keys:
refreshed = hit['source']['channel']['channel_last_refresh']
date_refresh = datetime.fromtimestamp(refreshed)
date_str = datetime.strftime(date_refresh, "%d %b, %Y")
hit['source']['channel']['channel_last_refresh'] = date_str
return hit
class Pagination:
"""
figure out the pagination based on page size and total_hits
"""
def __init__(self, page_get, search_get=False):
config = AppConfig().config
self.page_size = config['archive']['page_size']
self.page_get = page_get
self.search_get = search_get
self.pagination = self.first_guess()
def first_guess(self):
""" build first guess before api call """
page_get = self.page_get
if page_get in [0, 1]:
page_from = 0
prev_pages = False
elif page_get > 1:
page_from = (page_get - 1) * self.page_size
prev_pages = [
i for i in range(page_get - 1, page_get - 6, -1) if i > 1
]
prev_pages.reverse()
pagination = {
"page_size": self.page_size,
"page_from": page_from,
"prev_pages": prev_pages,
"current_page": page_get
}
if self.search_get:
pagination.update({"search_get": self.search_get})
return pagination
def validate(self, total_hits):
""" validate pagination with total_hits after making api call """
page_get = self.page_get
max_pages = math.ceil(total_hits / self.page_size)
if page_get < max_pages and max_pages > 1:
self.pagination['last_page'] = max_pages
else:
self.pagination['last_page'] = False
next_pages = [
i for i in range(page_get + 1, page_get + 6) if 1 < i < max_pages
]
self.pagination['next_pages'] = next_pages

View File

@ -0,0 +1,68 @@
"""
Functionality:
- initiate celery app
- collect tasks
"""
import os
from celery import Celery, shared_task
from home.src.download import (
PendingList,
ChannelSubscription,
VideoDownloader
)
from home.src.config import AppConfig
CONFIG = AppConfig().config
LIMIT_COUNT = CONFIG['downloads']['limit_count']
REDIS_HOST = CONFIG['application']['REDIS_HOST']
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'home.settings')
app = Celery('tasks', broker='redis://' + REDIS_HOST)
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@shared_task
def update_subscribed():
""" look for missing videos and add to pending """
channel_handler = ChannelSubscription()
missing_videos = channel_handler.find_missing()
if missing_videos:
pending_handler = PendingList()
pending_handler.add_to_pending(missing_videos)
@shared_task
def download_pending():
""" download latest pending videos """
pending_handler = PendingList()
pending_vids = pending_handler.get_all_pending()[0]
pending = [i['youtube_id'] for i in pending_vids]
pending.reverse()
if LIMIT_COUNT:
to_download = pending[:LIMIT_COUNT]
else:
to_download = pending
if to_download:
download_handler = VideoDownloader(to_download)
download_handler.download_list()
@shared_task
def download_single(youtube_id):
""" start download single video now """
to_download = [youtube_id]
download_handler = VideoDownloader(to_download)
download_handler.download_list()
@shared_task
def extrac_dl(youtube_ids):
""" parse list passed and add to pending """
pending_handler = PendingList()
missing_videos = pending_handler.parse_url_list(youtube_ids)
pending_handler.add_to_pending(missing_videos)

View File

@ -0,0 +1,38 @@
{% extends "home/base.html" %}
{% load static %}
{% block content %}
<div class="title-bar">
<h1>About The Tube Archivist</h1>
</div>
<div class="about-section">
<h2>Getting started</h2>
<ol>
<li>Before adding some videos to the download queue, take a look at the download format settings on your <a href="{% url 'settings' %}#format">settings</a> page and set your desired download quality.</li>
<li>While at the settings page also set the value for the Subscriptions <a href="{% url 'settings' %}#subscriptions">page size</a>. This will define the max amount of videos that will get added once you run <i>Rescan Subscriptions</i>. yt-dlp by default uses 50 video page size. Any value higher than that will significantly slow down the scanning process.</li>
<li>Subscribe to some of your favourite youtube channels in the <a href="{% url 'channel' %}">channel</a> page. To subscribe to a channel you have a few options:
<ul>
<li>Enter the Youtube channel ID, a 25 character alphanumeric string. For example <span class="settings-current">UCBa659QWEk1AI4Tg--mrJ2A</span></li>
<li>Enter the url to the channel page on youtube. For example <span class="settings-current">https://www.youtube.com/channel/UCBa659QWEk1AI4Tg--mrJ2A</span></li>
<li>Enter the video url for any video and let <i>Tube Archivist</i> extract the channel ID for you. For example <span class="settings-current">https://www.youtube.com/watch?v=2tdiKTSdE9Y</span></li>
</ul>
</li>
<li>After that head over to the <a href="{% url 'downloads' %}">Downloads</a> Page. Once you click on the <i>Rescan Subscriptions</i> button, Tube Archivist will go through all your subscribed channels and look for new videos. Initially these are the latest videos depending on the page size as described above.</li>
<li>Click on <span class="settings-current">ignore</span> for any video you don't want to download or on <span class="settings-current">Download now</span> for any video you want to start downloading now independently from the queue.</li>
<li>Click on the <span class="settings-current">Download queue</span> button to start downloading. Tube Archivist will then start the queue from the bottom and download as many videos as defined in <a href="{% url 'settings' %}#downloads">download limit</a>. There is currently no good way to cancel the download process.</li>
</ol>
</div>
<div class="about-section">
<h2>Additional</h2>
<ul>
<li>You can manually add videos to the queue on the <a href="{% url 'downloads' %}">download page</a> by clicking on <i>Add to download queue</i> and then entering a list of videos. Add one link per line. You have a few options:
<ul>
<li>Add a link to a Youtube video. For example <span class="settings-current">https://www.youtube.com/watch?v=2tdiKTSdE9Y</span>.</li>
<li>Add a Youtube video ID. For example <span class="settings-current">2tdiKTSdE9Y</span>.</li>
<li>Add a link to a Youtube video by providing the shortened url, for example <span class="settings-current">https://youtu.be/2tdiKTSdE9Y</span>.</li>
<li>Add a Channel ID or Channel Url to add every available video to the download queue. This will ignore the page size as described above. You can still ignore selected videos before starting the download.</li>
</ul>
</li>
<li>As you watch videos, mark them as watched by clicking on the unseen icon <span class="about-icon"><img src="{% static 'img/icon-unseen.svg' %}" alt="unseen-icon" class="unseen-icon"></span>. Once marked as watched, the icon will change to <span class="about-icon"><img src="{% static 'img/icon-seen.svg' %}" alt="seen-icon" class="seen-icon"></span>.</li>
</ul>
</div>
{% endblock content %}

View File

@ -0,0 +1,103 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
{% if title %}
<title>TA | {{ title }}</title>
{% else %}
<title>TubeArchivist</title>
{% endif %}
{% if colors == "dark" %}
<link rel="stylesheet" href="{% static 'css/dark.css' %}">
{% else %}
<link rel="stylesheet" href="{% static 'css/light.css' %}">
{% endif %}
<script type="text/javascript" src="{% static 'script.js' %}"></script>
</head>
<body>
<div class="boxed-content">
<div class="top-banner">
<a href="{% url 'home' %}">
{% if colors == 'dark' %}
<img src="{% static 'img/banner-tube-archivist-dark.png' %}" alt="tube-archivist-banner">
{% endif %}
{% if colors == 'light' %}
<img src="{% static 'img/banner-tube-archivist-light.png' %}" alt="tube-archivist-banner">
{% endif %}
</a>
</div>
<div class="top-nav">
<div class="nav-items">
<a href="{% url 'home' %}">
<div class="nav-item">home</div>
</a>
<a href="{% url 'channel' %}">
<div class="nav-item">channels</div>
</a>
<a href="{% url 'downloads' %}">
<div class="nav-item">downloads</div>
</a>
</div>
<div class="nav-icons">
<a href="{% url 'about' %}">
<img src="{% static 'img/icon-help.svg' %}" alt="help-icon">
</a>
<a href="{% url 'settings' %}">
<img src="{% static 'img/icon-gear.svg' %}" alt="gear-icon">
</a>
</div>
</div>
{% block content %}{% endblock %}
<div class="pagination">
{% if pagination %}
{% if pagination.current_page > 1 %}
{% if pagination.search_get %}
<a class="pagination-item" href="{{ request.path }}?search={{ pagination.search_get }}">First</a>
{% else %}
<a class="pagination-item" href="{{ request.path }}">First</a>
{% endif %}
{% endif %}
{% if pagination.prev_pages %}
{% for page in pagination.prev_pages %}
{% if pagination.search_get %}
<a class="pagination-item" href="?page={{ page }}&search={{ pagination.search_get }}">{{ page }}</a>
{% else %}
<a class="pagination-item" href="?page={{ page }}">{{ page }}</a>
{% endif %}
{% endfor %}
{% endif %}
{% if pagination.current_page %}
<span>< Page {{ pagination.current_page }}</span>
{% endif %}
{% if pagination.next_pages %}
<span> ></span>
{% for page in pagination.next_pages %}
{% if pagination.search_get %}
<a class="pagination-item" href="?page={{ page }}&search={{ pagination.search_get }}">{{ page }}</a>
{% else %}
<a class="pagination-item" href="?page={{ page }}">{{ page }}</a>
{% endif %}
{% endfor %}
{% endif %}
{% if pagination.last_page > 0 %}
{% if pagination.search_get %}
<a class="pagination-item" href="?page={{ pagination.last_page }}&search={{ pagination.search_get }}">Last ({{ pagination.last_page }})</a>
{% else %}
<a class="pagination-item" href="?page={{ pagination.last_page }}">Last ({{ pagination.last_page }})</a>
{% endif %}
{% endif %}
{% endif %}
</div>
</div>
<div class="footer">
<div class="boxed-content">
<span>© 2021 | The Tube Archivist</span>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,85 @@
{% extends "home/base.html" %}
{% load static %}
{% load humanize %}
{% block content %}
<div class="title-bar">
<h1>Channels</h1>
</div>
<div class="two-col">
<div>
<h2>Subscribe to channel</h2>
<p>Input channel ID, channel URL or Video of a channel</p>
<form action="/channel/" method="post">
{% csrf_token %}
<input type="text" id="subscribe" name="subscribe" autocomplete="off">
<button type="submit">Subscribe</button>
</form>
</div>
<div class="search-form">
<form onSubmit="return channelRedirect();" id="search-box">
{% csrf_token %}
<input name="videoSearch" list="resultBox" type="text" id="searchInput" autocomplete="off" oninput="searchChannels(this.value)">
<datalist id="resultBox">
</datalist>
</form>
<div class="search-icon">
<img src="{% static 'img/icon-search.svg' %}" alt="search-icon" onclick="showSearch()">
</div>
</div>
</div>
<div class="padding-box">
<h2>Total matching channels: {{ max_hits }}</h2>
<span>Change show / hide subscribed only </span><span class="settings-current">{{ show_subed_only }}</span>
<select name="watched" id="watched" onchange="showSubscribedOnly(this.value)">
<option value="" disabled selected> -- change -- </option>
<option value="0">show all channels</option>
<option value="1">show subscribed channels only</option>
</select>
</div>
<div>
{% if channels %}
{% for channel in channels %}
<div class="channel-item">
{% if channel.source.channel_banner_url %}
<div class="channel-banner">
<a href="{% url 'channel_id' channel.source.channel_id %}">
<img src="/cache/channels/{{ channel.source.channel_id }}_banner.jpg" alt="{{ channel.source.channel_id }}-banner">
</a>
</div>
{% endif %}
<div class="info-box info-box-2">
<div class="info-box-item">
<div class="round-img">
<a href="{% url 'channel_id' channel.source.channel_id %}">
<img src="/cache/channels/{{ channel.source.channel_id }}_thumb.jpg" alt="channel-thumb">
</a>
</div>
<div>
<h3><a href="{% url 'channel_id' channel.source.channel_id %}">{{ channel.source.channel_name }}</a></h3>
{% if channel.source.channel_subs >= 1000000 %}
<p>Subscribers: {{ channel.source.channel_subs|intword }}</p>
{% else %}
<p>Subscribers: {{ channel.source.channel_subs|intcomma }}</p>
{% endif %}
</div>
</div>
<div class="info-box-item">
<div>
<p>Last refreshed: {{ channel.source.channel_last_refresh }}</p>
<p>Subscribed:
{% if channel.source.channel_subscribed %}
<button type="button" id="{{ channel.source.channel_id }}" onclick="unsubscribe(this.id)" title="Unsubscribe from {{ channel.source.channel_name }}">Unsubscribe</button>
{% else %}
false
{% endif %}
</p>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>No channels found...</h2>
{% endif %}
</div>
{% endblock content %}

View File

@ -0,0 +1,99 @@
{% extends "home/base.html" %}
{% block content %}
{% load static %}
{% load humanize %}
<div class="title-bar">
<h1>Channel: {{ channel_info.channel_name }}</h1>
</div>
<div class="channel-banner">
{% if channel_info.channel_banner_url %}
<a href="/channel/{{ channel_info.channel_id }}/"><img src="/cache/channels/{{ channel_info.channel_id }}_banner.jpg" alt="channel_banner"></a>
{% endif %}
</div>
<div class="info-box info-box-3 padding-box">
<div class="info-box-item">
<div class="round-img">
<a href="{% url 'channel_id' channel_info.channel_id %}">
<img src="/cache/channels/{{ channel_info.channel_id }}_thumb.jpg" alt="channel-thumb">
</a>
</div>
<div>
<h3><a href="{% url 'channel_id' channel_info.channel_id %}">{{ channel_info.channel_name }}</a></h3>
{% if channel_info.channel_subs >= 1000000 %}
<span>Subscribers: {{ channel_info.channel_subs|intword }}</span>
{% else %}
<span>Subscribers: {{ channel_info.channel_subs|intcomma }}</span>
{% endif %}
</div>
</div>
<div class="info-box-item">
<div>
<p>Last refreshed: {{ channel_info.channel_last_refresh }}</p>
<p>Subscribed:
{% if channel_info.channel_subscribed %}
<button type="button" id="{{ channel_info.channel_id }}" onclick="unsubscribe(this.id)" title="Unsubscribe from {{ channel_info.channel_name }}">Unsubscribe</button>
{% else %}
false
{% endif %}
</p>
</div>
</div>
{% if videos %}
<div class="info-box-item">
<div>
{% if channel_info.channel_views >= 1000000 %}
<p>Channel views: {{ channel_info.channel_views|intword }}</p>
{% else %}
<p>Channel views: {{ channel_info.channel_views|intcomma }}</p>
{% endif %}
<p>Total Videos archived: {{ max_hits }}</p>
<p>Watched: <button title="Mark all videos from {{ channel_info.channel_name }} as watched" type="button" id="{{ channel_info.channel_id }}" onclick="isWatched(this.id)">Mark as watched</button></p>
<p>Channel id: {{ channel_info.channel_id }}</p>
</div>
</div>
{% endif %}
</div>
{% if channel_info.channel_description %}
<div class="info-box-item description-box">
<p>Description: <button onclick="textReveal()" id="text-reveal-button">Show</button></p>
<div id="text-reveal" class="description-text">
{{ channel_info.channel_description|linebreaks }}
</div>
</div>
{% endif %}
<div id="player" class="video-player"></div>
<h2>Videos</h2>
<div class="video-list">
{% if videos %}
{% for video in videos %}
<div class="video-item">
<a href="#player" data-src="/media/{{ video.source.media_url }}" data-thumb="/cache/videos/{{ video.source.youtube_id }}.jpg" data-title="{{ video.source.title }}" data-channel="{{ video.source.channel.channel_name }}" data-id="{{ video.source.youtube_id }}" onclick="createPlayer(this)">
<div class="video-thumb-wrap">
<div class="video-thumb">
<img src="/cache/videos/{{ video.source.youtube_id }}.jpg" alt="video-thumb">
</div>
<div class="video-play">
<img src="{% static 'img/icon-play.svg' %}" alt="play-icon">
</div>
</div>
</a>
<div class="video-desc">
<div class="video-desc-player" id="video-info-{{ video.source.youtube_id }}">
{% if video.source.player.watched %}
<img src="{% static 'img/icon-seen.svg' %}" alt="seen-icon" id="{{ video.source.youtube_id }}" class="seen-icon">
{% else %}
<img src="{% static 'img/icon-unseen.svg' %}" alt="unseen-icon" id="{{ video.source.youtube_id }}" onclick="isWatched(this.id)" class="unseen-icon" title="Mark as watched.">
{% endif %}
<span>{{ video.source.published }} | {{ video.source.player.duration_str }}</span>
</div>
<div>
<a class="video-more" href="{% url 'video' video.source.youtube_id %}"><h2>{{ video.source.title }}</h2></a>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>No videos found...</h2>
{% endif %}
</div>
{% endblock content %}

View File

@ -0,0 +1,56 @@
{% extends "home/base.html" %}
{% load static %}
{% block content %}
<div class="title-bar">
<h1>Downloads</h1>
</div>
<div id="downloadMessage"></div>
<div class="info-box info-box-3 padding-box">
<div class="icon-text">
<img id="rescan-icon" onclick="rescanPending()" src="{% static 'img/icon-rescan.svg' %}" alt="rescan-icon">
<p>Rescan subscriptions</p>
</div>
<div class="icon-text">
<img id="download-icon" onclick="dlPending()" src="{% static 'img/icon-download.svg' %}" alt="download-icon">
<p>Download queue</p>
</div>
<div class="icon-text">
<img id="add-icon" onclick="showForm()" src="{% static 'img/icon-add.svg' %}" alt="add-icon">
<p>Add to download queue</p>
<div class="show-form">
<form id='hidden-form' action="/downloads/" method="post">
{% csrf_token %}
<textarea rows="4" placeholder="Enter Video Urls or IDs here..." id="vid-url" name="vid-url"></textarea>
<button type="submit">Add to download queue</button>
</form>
</div>
</div>
</div>
<h2>Download queue</h2>
<div>
{% if pending %}
<h3>Total pending downloads: {{ pending|length }}</h3>
{% for video in pending %}
<div class="dl-item" id="dl-{{ video.youtube_id }}">
<div class="dl-thumb">
<img src="{{ video.vid_thumb_url }}" alt="video_thumb">
</div>
<div class="dl-desc">
<h3>{{ video.title }}</h3>
{% if video.channel_indexed %}
<a href="{% url 'channel_id' video.channel_id %}">{{ video.channel_name }}</a>
{% else %}
<span>{{ video.channel_name }}</span>
{% endif %}
<p>Published: {{ video.published }} | Duration: {{ video.duration }} | {{ video.youtube_id }}</p>
<button data-id="{{ video.youtube_id }}" onclick="toIgnore(this)">Ignore</button>
<button data-id="{{ video.youtube_id }}" onclick="downloadNow(this)">Download now</button>
</div>
</div>
{% endfor %}
{% else %}
<h3>No pending downloads</h3>
{% endif %}
</div>
<script type="text/javascript" src="{% static 'progress.js' %}"></script>
{% endblock content %}

View File

@ -0,0 +1,71 @@
{% extends "home/base.html" %}
{% block content %}
{% load static %}
<div class="title-bar">
<h1>Recent Videos</h1>
</div>
<div class="two-col">
<div class="sort">
<div>
<p>Sort order from <span class="settings-current">{{ sortorder }}</span>
<select name="sort" id="sort" onchange="sortChange(this.value)">
<option value="" disabled selected> -- change sort order -- </option>
<option value="published">date published</option>
<option value="downloaded">date downloaded</option>
</select></p>
</div>
<div>
<p>Hide watched videos <span class="settings-current">{{ hide_watched }}</span>
<select name="watched" id="watched" onchange="hideWatched(this.value)">
<option value="" disabled selected> -- change hide watched -- </option>
<option value="0">show watched videos</option>
<option value="1">hide watched videos</option>
</select></p>
</div>
</div>
<div class="search-form">
<form action="/" method="POST" id="search-box">
{% csrf_token %}
<input name="videoSearch" list="resultBox" type="text" id="searchInput" autocomplete="off">
</form>
<div class="search-icon">
<img src="{% static 'img/icon-search.svg' %}" alt="search-icon" onclick="showSearch()">
</div>
</div>
</div>
<div id="player" class="video-player"></div>
<div class="video-list">
{% if videos %}
{% for video in videos %}
<div class="video-item">
<a href="#player" data-src="/media/{{ video.source.media_url }}" data-thumb="/cache/videos/{{ video.source.youtube_id }}.jpg" data-title="{{ video.source.title }}" data-channel="{{ video.source.channel.channel_name }}" data-id="{{ video.source.youtube_id }}" onclick="createPlayer(this)">
<div class="video-thumb-wrap">
<div class="video-thumb">
<img src="/cache/videos/{{ video.source.youtube_id }}.jpg" alt="video-thumb">
</div>
<div class="video-play">
<img src="{% static 'img/icon-play.svg' %}" alt="play-icon">
</div>
</div>
</a>
<div class="video-desc">
<div class="video-desc-player" id="video-info-{{ video.source.youtube_id }}">
{% if video.source.player.watched %}
<img src="{% static 'img/icon-seen.svg' %}" alt="seen-icon" id="{{ video.source.youtube_id }}" class="seen-icon">
{% else %}
<img src="{% static 'img/icon-unseen.svg' %}" alt="unseen-icon" id="{{ video.source.youtube_id }}" onclick="isWatched(this.id)" class="unseen-icon" title="Mark as watched.">
{% endif %}
<span>{{ video.source.published }} | {{ video.source.player.duration_str }}</span>
</div>
<div>
<a href="{% url 'channel_id' video.source.channel.channel_id %}"><h3>{{ video.source.channel.channel_name }}</h3></a>
<a class="video-more" href="{% url 'video' video.source.youtube_id %}"><h2>{{ video.source.title }}</h2></a>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>No videos found...</h2>
{% endif %}
</div>
{% endblock content %}

View File

@ -0,0 +1,127 @@
{% extends "home/base.html" %}
{% block content %}
<div class="title-bar">
<h1>Settings</h1>
</div>
<form action="/settings/" method="POST">
{% csrf_token %}
<div class="settings-group">
<h2>Color scheme</h2>
<div class="settings-item">
<p>Current color scheme: <span class="settings-current">{{ config.application.colors }}</span></p>
<i>Select yout prefered color scheme between dark and light mode.</i><br>
<select name="application.colors" id="application.colors">
<option value="" disabled selected> -- change color scheme -- </option>
<option value="dark">dark mode</option>
<option value="light">light mode</option>
</select>
</div>
</div>
<div class="settings-group">
<h2>Archive View</h2>
<div class="settings-item">
<p>Current default Sort: <span class="settings-current">{{ config.archive.sort }}</span></p>
<i>Change how the home view and channels view sorts by defaults.</i><br>
<select name="archive.sort" id="archive.sort"">
<option value="" disabled selected> -- change sort order -- </option>
<option value="published">date published</option>
<option value="downloaded">date downloaded</option>
</select>
</div>
<div class="settings-item">
<p>Current default hide watched: <span class="settings-current">{{ config.archive.hide_watched }}</span></p>
<i>Show or hide watched videos by default.</i><br>
<select name="archive.hide_watched" id="archive.hide_watched"">
<option value="" disabled selected> -- change visibility -- </option>
<option value="0">show watched</option>
<option value="1">hide watched</option>
</select>
</div>
<div class="settings-item">
<p>Current default show subscribed channels only: <span class="settings-current">{{ config.archive.show_subed_only }}</span></p>
<i>Show subscribed channels only by default.</i><br>
<select name="archive.show_subed_only" id="archive.show_subed_only"">
<option value="" disabled selected> -- change visibility -- </option>
<option value="0">show subscribed only</option>
<option value="1">hide not subscribed</option>
</select>
</div>
<div class="settings-item">
<p>Current page size: <span class="settings-current">{{ config.archive.page_size }}</span></p>
<i>Result of videos showing in archive page</i><br>
<input type="number" name="archive.page_size" id="archive.page_size">
</div>
</div>
<div class="settings-group">
<h2 id="subscriptions">Subscriptions</h2>
<div class="settings-item">
<p>Currend channel page size: <span class="settings-current">{{ config.subscriptions.channel_size }}</span></p>
<i>Recent videos to check on check pending, max recommended 50.</i><br>
<input type="number" name="subscriptions.channel_size" id="subscriptions.channel_size">
</div>
<div class="settings-item">
<p>Auto scan subscribed channels:</p>
<i>Coming soon</i>
</div>
<div class="settings-item">
<p>Auto download pending:</p>
<i>Coming soon</i>
</div>
</div>
<div class="settings-group">
<h2 id="downloads">Downloads</h2>
<div class="settings-item">
<p>Current download limit: <span class="settings-current">{{ config.downloads.limit_count }}</span></p>
<i>Limit the count of videos getting downloaded on every run. 0 (zero) to deactivate.</i><br>
<input type="number" name="downloads.limit_count" id="downloads.limit_count">
</div>
<div class="settings-item">
<p>Currend Download speed limit: <span class="settings-current">{{ config.downloads.limit_speed }}</span></p>
<i>Limit download speed. 0 (zero) to deactivate.</i><br>
<input type="number" name="downloads.limit_speed" id="downloads.limit_speed"><span>KB/sec</span>
</div>
<div class="settings-item">
<p>Current scraping sleep interval: <span class="settings-current">{{ config.downloads.sleep_interval }}</p>
<i>Seconds to sleep between calls to youtube. Might be necessary to avoid throttling. Recommended 3.</i><br>
<input type="number" name="downloads.sleep_interval" id="downloads.sleep_interval">
</div>
<div class="settings-item">
<p>External downloader:</p>
<i>Coming soon</i>
</div>
</div>
<div class="settings-group">
<h2 id="format">Download Format</h2>
<div class="settings-item">
<p>Video and audio quality format for yt-dlp.<br>
Currently: <span class="settings-current">{{ config.downloads.format }}</span>
</p>
<p>Example configurations:</p>
<ul>
<li><span class="settings-current">bestvideo[height<=720]+bestaudio/best[height<=720]</span>: best audio and max video height of 720p.</li>
<li><span class="settings-current">bestvideo[height<=1080]+bestaudio/best[height<=1080]</span>: best audio and max video height of 1080p.</li>
<li><span class="settings-current">0</span>: deactivate and download the best quality possible as decided by yt-dlp.</li>
</ul>
<i>Make sure your custom format gets merged into a single file. Check out the <a href="https://github.com/yt-dlp/yt-dlp#format-selection" target="_blank">documentation</a> for valid configurations.</i><br>
<input type="text" name="downloads.format" id="downloads.format">
<br>
</div>
</div>
<button type="submit">Update Settings</button>
</form>
<div class="title-bar">
<h1>Actions</h1>
</div>
<div class="settings-group">
<p>Rescan filesystem.</p>
<i>Coming soon</i>
</div>
<div class="settings-group">
<p>Manual media files import.</p>
<i>Coming soon</i>
</div>
<div class="settings-group">
<p>Backup database.</p>
<i>Coming soon</i>
</div>
{% endblock content %}

View File

@ -0,0 +1,67 @@
{% extends "home/base.html" %}
{% block content %}
{% load static %}
{% load humanize %}
<div class="title-bar">
<h1>Video: {{ video.title }}</h1>
</div>
<div class="video-main">
<video
src="/media/{{ video.media_url }}"
poster="/cache/videos/{{ video.youtube_id }}.jpg" controls preload="false"
type='video/mp4' width="100%">
</video>
</div>
<div class="info-box info-box-3 padding-box">
<div class="info-box-item">
<div class="round-img">
<a href="{% url 'channel_id' video.channel.channel_id %}">
<img src="/cache/channels/{{ video.channel.channel_id }}_thumb.jpg" alt="channel-thumb">
</a>
</div>
<div>
<h3><a href="{% url 'channel_id' video.channel.channel_id %}">{{ video.channel.channel_name }}</a></h3>
{% if video.channel.channel_subs >= 1000000 %}
<p>Subscribers: {{ video.channel.channel_subs|intword }}</p>
{% else %}
<p>Subscribers: {{ video.channel.channel_subs|intcomma }}</p>
{% endif %}
</div>
</div>
<div class="info-box-item">
<div>
<p>Published: {{ video.published }}</p>
<p>Last refreshed: {{ video.vid_last_refresh }}</p>
<p class="video-info-watched">Watched:
{% if video.player.watched %}
<img src="{% static 'img/icon-seen.svg' %}" alt="seen-icon" class="seen-icon" id="{{ video.youtube_id }}">
{% else %}
<img src="{% static 'img/icon-unseen.svg' %}" alt="unseen-icon" id="{{ video.youtube_id }}" onclick="isWatched(this.id)" class="unseen-icon" title="Mark as watched.">
{% endif %}
</p>
{% if video.active %}
<p>Youtube: Active</p>
{% else %}
<p>Youtube: Deactivated</p>
{% endif %}
<p>Video ID: {{ video.youtube_id }}</p>
</div>
</div>
<div class="info-box-item">
<div>
<p>Views: {{ video.stats.view_count|intcomma }}</p>
<p class="thumb-icon like"><img src="{% static 'img/icon-thumb.svg' %}" alt="thumbs-up">: {{ video.stats.like_count|intcomma }}</p>
<p class="thumb-icon dislike"><img src="{% static 'img/icon-thumb.svg' %}" alt="thumbs-down">: {{ video.stats.dislike_count|intcomma }}</p>
<p>Rating: {{ video.stats.average_rating }}</p>
</div>
</div>
</div>
{% if video.description %}
<div class="info-box-item description-box">
<p>Description: <button onclick="textReveal()" id="text-reveal-button">Show</button></p>
<div id="text-reveal" class="description-text">
{{ video.description|linebreaks }}
</div>
</div>
{% endif %}
{% endblock content %}

View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View File

@ -0,0 +1,27 @@
""" all home app urls """
from django.urls import path
from home.views import (
HomeView,
DownloadView,
ChannelView,
ChannelIdView,
VideoView,
SettingsView,
AboutView
)
from . import views
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('about/', AboutView.as_view(), name='about'),
path('downloads/', DownloadView.as_view(), name='downloads'),
path('settings/', SettingsView.as_view(), name='settings'),
path('process/', views.process, name='process'),
path('downloads/progress', views.progress, name='progress'),
path('channel/', ChannelView.as_view(), name='channel'),
path('channel/<slug:channel_id_detail>/', ChannelIdView.as_view(), name='channel_id'),
path('video/<slug:video_id>/', VideoView.as_view(), name='video')
]

562
tubearchivist/home/views.py Normal file
View File

@ -0,0 +1,562 @@
"""
Functionality:
- all views for home app
- process post data recieved from frontend via ajax
"""
import urllib.parse
import json
from datetime import datetime
from time import sleep
import requests
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views import View
from django.utils.http import urlencode
from home.src.download import PendingList, ChannelSubscription
from home.src.searching import SearchHandler, Pagination
from home.src.config import AppConfig
from home.src.helper import (
process_url_list,
get_dl_message,
get_message,
set_message
)
from home.tasks import (
update_subscribed,
download_pending,
extrac_dl,
download_single
)
class HomeView(View):
""" handle home page and video search post functionality """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
def get(self, request):
""" return home search results """
colors, sort_order, hide_watched = self.read_config()
# handle search
search_get = request.GET.get('search', False)
if search_get:
search_encoded = urllib.parse.quote(search_get)
else:
search_encoded = False
# define page size
page_get = int(request.GET.get('page', 0))
pagination_handler = Pagination(page_get, search_encoded)
url = self.ES_URL + '/ta_video/_search'
data = self.build_data(
pagination_handler, sort_order, search_get, hide_watched
)
search = SearchHandler(url, data)
videos_hits = search.get_data()
max_hits = search.max_hits
pagination_handler.validate(max_hits)
context = {
'videos': videos_hits,
'pagination': pagination_handler.pagination,
'sortorder': sort_order,
'hide_watched': hide_watched,
'colors': colors
}
return render(request, 'home/home.html', context)
@staticmethod
def build_data(pagination_handler, sort_order, search_get, hide_watched):
""" build the data dict for the search query """
page_size = pagination_handler.pagination['page_size']
page_from = pagination_handler.pagination['page_from']
data = {
"size": page_size, "from": page_from, "query": {"match_all": {}},
"sort": [
{"published": {"order": "desc"}},
{"date_downloaded": {"order": "desc"}}
]
}
# define sort
if sort_order == 'downloaded':
del data['sort'][0]
if search_get:
del data['sort']
if hide_watched:
data['query'] = {"term": {"player.watched": {"value": False}}}
if search_get:
query = {
"multi_match": {
"query": search_get,
"fields": ["title", "channel.channel_name", "tags"],
"type": "cross_fields",
"operator": "and"
}
}
data['query'] = query
return data
@staticmethod
def read_config():
""" read needed values from redis """
config_handler = AppConfig().config
colors = config_handler['application']['colors']
sort_order = get_message('sort_order')
hide_watched = get_message('hide_watched')
return colors, sort_order, hide_watched
@staticmethod
def post(request):
""" handle post from search form """
post_data = dict(request.POST)
search_query = post_data['videoSearch'][0]
search_url = '/?' + urlencode({'search': search_query})
return redirect(search_url, permanent=True)
class AboutView(View):
""" resolves to /about/
show helpful how to information
"""
@staticmethod
def get(request):
""" handle http get """
config = AppConfig().config
colors = config['application']['colors']
context = {
'title': 'About',
'colors': colors
}
return render(request, 'home/about.html', context)
class DownloadView(View):
"""
resolves to /download/
takes POST for downloading youtube links
"""
@staticmethod
def get(request):
""" handle get requests """
config = AppConfig().config
colors = config['application']['colors']
pending_handler = PendingList()
all_pending, _ = pending_handler.get_all_pending()
context = {
'pending': all_pending,
'title': 'Downloads',
'colors': colors
}
return render(request, 'home/downloads.html', context)
@staticmethod
def post(request):
""" handle post requests """
download_post = dict(request.POST)
if 'vid-url' in download_post.keys():
url_str = download_post['vid-url']
print('adding to queue')
youtube_ids = process_url_list(url_str)
print(youtube_ids)
extrac_dl.delay(youtube_ids)
sleep(2)
return redirect('downloads', permanent=True)
class ChannelIdView(View):
""" display single channel page from channel_id """
def get(self, request, channel_id_detail):
""" get method """
es_url, colors = self.read_config()
context = self.get_channel_videos(request, channel_id_detail, es_url)
context.update({'colors': colors})
return render(request, 'home/channel_id.html', context)
@staticmethod
def read_config():
""" read config file """
config = AppConfig().config
es_url = config['application']['es_url']
colors = config['application']['colors']
return es_url, colors
def get_channel_videos(self, request, channel_id_detail, es_url):
""" get channel from video index """
page_get = int(request.GET.get('page', 0))
pagination_handler = Pagination(page_get)
# get data
url = es_url + '/ta_video/_search'
data = self.build_data(pagination_handler, channel_id_detail)
search = SearchHandler(url, data)
videos_hits = search.get_data()
max_hits = search.max_hits
if max_hits:
channel_info = videos_hits[0]['source']['channel']
channel_name = channel_info['channel_name']
pagination_handler.validate(max_hits)
pagination = pagination_handler.pagination
else:
# get details from channel index when when no hits
channel_info, channel_name = self.get_channel_info(
channel_id_detail, es_url
)
videos_hits = False
pagination = False
context = {
'channel_info': channel_info,
'videos': videos_hits,
'max_hits': max_hits,
'pagination': pagination,
'title': 'Channel: ' + channel_name,
}
return context
@staticmethod
def build_data(pagination_handler, channel_id_detail):
""" build data dict for search """
page_size = pagination_handler.pagination['page_size']
page_from = pagination_handler.pagination['page_from']
data = {
"size": page_size, "from": page_from,
"query": {
"term": {"channel.channel_id": {"value": channel_id_detail}}
},
"sort": [
{"published": {"order": "desc"}},
{"date_downloaded": {"order": "desc"}}
]
}
return data
@staticmethod
def get_channel_info(channel_id_detail, es_url):
""" get channel info from channel index if no videos """
url = f'{es_url}/ta_channel/_doc/{channel_id_detail}'
data = False
search = SearchHandler(url, data)
channel_data = search.get_data()
channel_info = channel_data[0]['source']
channel_name = channel_info['channel_name']
return channel_info, channel_name
class ChannelView(View):
""" handle functionality for channel overview page """
def get(self, request):
""" handle http get requests """
es_url, colors = self.read_config()
page_get = int(request.GET.get('page', 0))
pagination_handler = Pagination(page_get)
page_size = pagination_handler.pagination['page_size']
page_from = pagination_handler.pagination['page_from']
# get
url = es_url + '/ta_channel/_search'
data = {
"size": page_size, "from": page_from, "query": {"match_all": {}},
"sort": [{"channel_name.keyword": {"order": "asc"}}]
}
show_subed_only = get_message('show_subed_only')
if show_subed_only:
data['query'] = {"term": {"channel_subscribed": {"value": True}}}
search = SearchHandler(url, data)
channel_hits = search.get_data()
max_hits = search.max_hits
pagination_handler.validate(search.max_hits)
context = {
'channels': channel_hits,
'max_hits': max_hits,
'pagination': pagination_handler.pagination,
'show_subed_only': show_subed_only,
'title': 'Channels',
'colors': colors
}
return render(request, 'home/channel.html', context)
@staticmethod
def read_config():
""" read config file """
config = AppConfig().config
es_url = config['application']['es_url']
colors = config['application']['colors']
return es_url, colors
@staticmethod
def post(request):
""" handle http post requests """
subscriptions_post = dict(request.POST)
print(subscriptions_post)
subscriptions_post = dict(request.POST)
if 'subscribe' in subscriptions_post.keys():
youtube_ids = process_url_list(subscriptions_post['subscribe'])
if youtube_ids[0]['type'] == 'video':
youtube_id = youtube_ids[0]['url']
vid_details = PendingList().get_youtube_details(youtube_id)
channel_id_sub = vid_details['channel_id']
else:
channel_id_sub = youtube_ids[0]['url']
ChannelSubscription().change_subscribe(
channel_id_sub, channel_subscribed=True
)
print('subscribed to: ' + channel_id_sub)
sleep(1)
return redirect('channel', permanent=True)
class VideoView(View):
""" display details about a single video """
def get(self, request, video_id):
""" get single video """
es_url, colors = self.read_config()
url = f'{es_url}/ta_video/_doc/{video_id}'
data = None
look_up = SearchHandler(url, data)
video_hit = look_up.get_data()
video_data = video_hit[0]['source']
video_title = video_data['title']
context = {
'video': video_data,
'title': video_title,
'colors': colors
}
return render(request, 'home/video.html', context)
@staticmethod
def read_config():
""" read config file """
config = AppConfig().config
es_url = config['application']['es_url']
colors = config['application']['colors']
return es_url, colors
class SettingsView(View):
""" handle the settings page """
@staticmethod
def get(request):
""" read and display current settings """
config = AppConfig().config
colors = config['application']['colors']
context = {
'title': 'Settings',
'config': config,
'colors': colors
}
return render(request, 'home/settings.html', context)
@staticmethod
def post(request):
""" handle form post to update settings """
form_post = dict(request.POST)
del form_post['csrfmiddlewaretoken']
print(form_post)
config_handler = AppConfig()
config_handler.update_config(form_post)
return redirect('settings', permanent=True)
def progress(request):
# pylint: disable=unused-argument
""" endpoint for download progress ajax calls """
config = AppConfig().config
cache_dir = config['application']['cache_dir']
json_data = get_dl_message(cache_dir)
return JsonResponse(json_data)
def process(request):
""" handle all the buttons calls via POST ajax """
if request.method == 'POST':
post_dict = json.loads(request.body.decode())
post_handler = PostData(post_dict)
if post_handler.to_do:
task_result = post_handler.run_task()
return JsonResponse(task_result)
return JsonResponse({'success': False})
class PostData:
""" generic post handler from process route """
CONFIG = AppConfig().config
ES_URL = CONFIG['application']['es_url']
VALID_KEYS = [
"watched", "rescan_pending", "ignore", "dl_pending",
"unsubscribe", "sort_order", "hide_watched", "show_subed_only",
"channel-search", "video-search", "dlnow"
]
def __init__(self, post_dict):
self.post_dict = post_dict
self.to_do = self.validate()
def validate(self):
""" validate the post_dict """
to_do = []
for key, value in self.post_dict.items():
if key in self.VALID_KEYS:
task_item = {'task': key, 'status': value}
print(task_item)
to_do.append(task_item)
else:
print(key + ' not a valid key')
return to_do
def run_task(self):
""" run through the tasks to do """
for item in self.to_do:
task = item['task']
if task == 'watched':
youtube_id = item['status']
self.parse_watched(youtube_id)
elif task == 'rescan_pending':
print('download pending videos')
update_subscribed.delay()
elif task == 'ignore':
print('ignore video')
handler = PendingList()
ignore_list = item['status']
handler.ignore_from_pending([ignore_list])
elif task == 'dl_pending':
print('download pending')
download_pending.delay()
elif task == 'vid-url':
status_str = item['status']
print(urllib.parse.quote(status_str))
elif task == 'unsubscribe':
channel_id_unsub = item['status']
print('unsubscribe from ' + channel_id_unsub)
ChannelSubscription().change_subscribe(
channel_id_unsub, channel_subscribed=False
)
elif task == 'sort_order':
sort_order = item['status']
set_message('sort_order', sort_order, expire=False)
elif task == 'hide_watched':
hide_watched = bool(int(item['status']))
print(item['status'])
set_message('hide_watched', hide_watched, expire=False)
elif task == 'show_subed_only':
show_subed_only = bool(int(item['status']))
print(show_subed_only)
set_message('show_subed_only', show_subed_only, expire=False)
elif task == 'channel-search':
search_query = item['status']
print('searching for: ' + search_query)
search_results = self.search_channels(search_query)
return search_results
elif task == 'video-search':
search_query = item['status']
print('searching for: ' + search_query)
search_results = self.search_videos(search_query)
return search_results
elif task == 'dlnow':
youtube_id = item['status']
print('downloading: ' + youtube_id)
download_single(youtube_id)
return {'success': True}
def search_channels(self, search_query):
""" fancy searching channels as you type """
url = self.ES_URL + '/ta_channel/_search'
data = {
"size": 10,
"query": {
"multi_match": {
"query": search_query,
"type": "bool_prefix",
"fields": [
"channel_name.search_as_you_type",
"channel_name._2gram",
"channel_name._3gram"
]
}
}
}
look_up = SearchHandler(url, data, cache=False)
search_results = look_up.get_data()
return {'results': search_results}
def search_videos(self, search_query):
""" fancy searching videos as you type """
url = self.ES_URL + '/ta_video/_search'
data = {
"size": 10,
"query": {
"multi_match": {
"query": search_query,
"type": "bool_prefix",
"fields": [
"title.search_as_you_type",
"title._2gram",
"title._3gram"
]
}
}
}
look_up = SearchHandler(url, data, cache=False)
search_results = look_up.get_data()
return {'results': search_results}
def parse_watched(self, youtube_id):
""" marked as watched based on id type """
es_url = self.ES_URL
id_type = process_url_list([youtube_id])[0]['type']
stamp = int(datetime.now().strftime("%s"))
if id_type == 'video':
stamp = int(datetime.now().strftime("%s"))
url = self.ES_URL + '/ta_video/_update/' + youtube_id
source = {
"doc": {"player": {"watched": True, "watched_date": stamp}}
}
request = requests.post(url, json=source)
if not request.ok:
print(request.text)
elif id_type == 'channel':
headers = {'Content-type': 'application/json'}
data = {
"description": youtube_id,
"processors": [
{"set": {"field": "player.watched", "value": True}},
{"set": {"field": "player.watched_date", "value": stamp}}
]
}
payload = json.dumps(data)
url = es_url + '/_ingest/pipeline/' + youtube_id
request = requests.put(url, data=payload, headers=headers)
if not request.ok:
print(request.text)
# apply pipeline
must_list = [
{"term": {"channel.channel_id": {"value": youtube_id}}},
{"term": {"player.watched": {"value": False}}}
]
data = {"query": {"bool": {"must": must_list}}}
payload = json.dumps(data)
url = f'{es_url}/ta_video/_update_by_query?pipeline={youtube_id}'
request = requests.post(url, data=payload, headers=headers)
if not request.ok:
print(request.text)

22
tubearchivist/manage.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,9 @@
requests==2.26.0
redis==3.5.3
yt_dlp==2021.8.10
celery==5.1.2
Django==3.2.6
beautifulsoup4==4.9.3
Pillow==8.3.1
uWSGI==2.0.19.1
whitenoise==5.3.0

View File

@ -0,0 +1,9 @@
:root {
--main-bg: #00202f;
--highlight-bg: #00293b;
--highlight-bg-transparent: #00293baf;
--main-font: #eeeeee;
--accent-font-dark: #259485;
--accent-font-light: #97d4c8;
--img-filter: invert(50%) sepia(9%) saturate(2940%) hue-rotate(122deg) brightness(94%) contrast(90%);
}

View File

@ -0,0 +1,19 @@
:root {
--main-bg: #eeeeee;
--highlight-bg: #d9e0d9;
--highlight-bg-transparent: #00293baf;
--main-font: #00202f;
--accent-font-dark: #259485;
--accent-font-light: #35b399;
--img-filter: invert(50%) sepia(9%) saturate(2940%) hue-rotate(122deg) brightness(94%) contrast(90%);
}
/* :root {
--main-bg: #00202f;
--highlight-bg: #00293b;
--highlight-bg-transparent: #00293baf;
--main-font: #eeeeee;
--accent-font-dark: #259485;
--accent-font-light: #97d4c8;
--img-filter: invert(50%) sepia(9%) saturate(2940%) hue-rotate(122deg) brightness(94%) contrast(90%);
} */

View File

@ -0,0 +1,631 @@
@font-face {
font-family: 'Sen-Bold';
src: url('../font/Sen-Bold.ttf.woff');
font-family: 'Sen-Bold';
}
@font-face {
font-family: 'Sen-Regular';
src: url('../font/Sen-Regular.ttf.woff');
font-family: 'Sen-Regular';
}
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
}
body {
background-color: var(--main-bg);
min-height: 100%;
display: grid;
grid-template-rows: 1fr auto;
}
a {
font-family: Sen-Regular, sans-serif;
text-decoration: none;
color: var(--accent-font-light);
}
h1 {
font-family: Sen-Bold, sans-serif;
font-size: 2.3em;
color: var(--accent-font-light);
}
h2 {
font-size: 1.2em;
margin-bottom: 10px;
font-family: Sen-Bold, sans-serif;
color: var(--accent-font-dark);
}
h3 {
font-size: 1.1em;
margin-bottom: 7px;
font-family: Sen-Regular, sans-serif;
color: var(--accent-font-light);
}
p, i, li {
font-family: Sen-Regular, sans-serif;
margin-bottom: 10px;
color: var(--main-font);
}
ul {
margin-left: 20px;
}
td, span {
font-family: Sen-Regular, sans-serif;
color: var(--main-font);
}
select, input {
padding: 5px;
margin: 5px;
border-radius: 0;
color: var(--main-bg);
background-color: var(--accent-font-light);
}
select {
border: none;
}
input {
border: solid 1px var(--main-font);
}
textarea {
width: 100%;
}
button {
border-radius: 0;
padding: 5px 13px;
border: none;
cursor: pointer;
background-color: var(--accent-font-dark);
color: #ffffff;
}
button:hover {
background-color: var(--accent-font-light);
transform: scale(1.05);
color: var(--main-bg);
}
.boxed-content {
max-width: 1000px;
width: 80%;
margin: 0 auto;
}
.round-img img {
border-radius: 50%;
}
.settings-current {
color: var(--accent-font-light);
}
.top-banner {
text-align: center;
margin-top: 10px;
}
.top-banner img {
width: 100%;
max-width: 700px;
}
.footer {
margin: 0;
padding: 20px 0;
background-color: var(--accent-font-dark);
grid-row-start: 2;
grid-row-end: 3;
}
/* navigation */
.top-nav {
display: block;
padding: 15px 0;
/* justify-content: space-around; */
position: relative;
}
.nav-items {
width: 100%;
display: flex;
justify-content: center;
}
.nav-item {
font-size: 1.3em;
padding: 10px 20px;
margin: 0 10px;
border-bottom: 2px solid;
color: var(--accent-font-dark);
}
.nav-icons {
width: auto;
display: inline-flex;
position: absolute;
top: 50%;
right: 0;
transform: translate(0,-50%);
}
.nav-icons img {
width: 40px;
padding: 0 10px;
filter: var(--img-filter);
}
/* top of page */
.title-bar {
padding: 25px 0;
}
.sort {
display: flex;
flex-wrap: wrap;
}
.sort > div {
width: 100%;
display: inline;
}
.padding-box {
padding: 30px 0;
}
.two-col {
display: flex;
}
.two-col > div {
width: 50%;
}
.search-form {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
}
.search-form input {
width: 90%;
}
.search-icon {
flex: 0 0 40px;
}
.search-icon img {
width: 100%;
cursor: pointer;
filter: var(--img-filter);
}
#search-box {
display: none;
flex: auto;
padding: 10px;
}
#hidden-form {
display: none;
}
#text-reveal {
height: 0px;
overflow: hidden;
}
/* video player */
.video-player {
position: relative;
margin: 20px 0;
}
.video-player video {
max-height: 70vh;
}
.player-title img {
width: 30px;
}
.player-title:hover {
opacity: 1;
}
.player-title {
opacity: 0;
background-color: var(--highlight-bg-transparent);
position: absolute;
top: 0;
z-index: 1;
width: 100%;
padding: 20px 0;
}
.player-title > * {
margin-left: 20px;
}
/* video list */
.video-list {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 1rem;
}
.video-item {
overflow: hidden;
}
.video-thumb img {
width: 100%;
}
.video-play img {
width: 40px;
filter: var(--img-filter);
}
.video-thumb-wrap {
position: relative;
}
.video-thumb-wrap:hover > .video-play {
opacity: 1;
padding: 15px;
}
.video-play {
opacity: 0;
transition: all 0.3s ease-in-out;
position: absolute;
top: 50%;
right: 50%;
transform: translate(50%,-50%);
background-color: var(--highlight-bg);
border-radius: 50%;
padding: 8px;
}
.video-desc {
padding: 10px;
height: 100%;
background-color: var(--highlight-bg);
}
.video-desc img {
width: 20px;
margin-right: 10px;
}
.video-desc a {
text-decoration: none;
text-align: left;
}
.video-desc h3 {
font-size: 0.9em;
text-transform: uppercase;
}
.video-desc-player {
margin-bottom: 8px;
display: flex;
align-items: center;
}
.unseen-icon,
.close-button {
cursor: pointer;
filter: var(--img-filter);
}
.seen-icon {
filter: var(--img-filter);
}
.video-more {
text-decoration: underline;
text-align: right;
}
/* pagination */
.pagination {
padding: 30px 0;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.pagination-item {
padding: 5px;
border: 1px solid;
}
/* info box */
.info-box {
display: grid;
grid-gap: 1rem;
}
.info-box-3 {
grid-template-columns: 1fr 1fr 1fr;
}
.info-box-2 {
grid-template-columns: 1fr 1fr;
}
.info-box img {
width: 80px;
margin: 0 15px;
}
.info-box-item {
display: flex;
align-items: center;
padding: 15px;
background-color: var(--highlight-bg);
}
.description-text {
width: 100%;
}
.description-text br {
margin-bottom: 10px;
}
/* video page */
.video-main video {
max-height: 70vh;
}
.video-info-watched {
display: flex;
align-items: center;
}
.video-info-watched img {
width: 20px;
margin-left: 5px;
}
.thumb-icon img {
width: 20px;
margin: 0;
filter: var(--img-filter);
}
.thumb-icon.dislike img {
transform: rotate(180deg);
}
/* channel overview page */
.channel-item {
padding: 20px 0;
}
.channel-banner img {
width: 100%;
}
/* download page */
.icon-text {
background-color: var(--highlight-bg);
text-align: center;
padding: 15px;
}
.icon-text img {
filter: var(--img-filter);
cursor: pointer;
}
.dl-item {
display: flex;
margin: 15px 0;
align-items: center;
background-color: var(--highlight-bg);
}
.dl-check {
width: 30px;
}
.dl-thumb {
width: 25%;
}
.dl-item img {
width: 100%;
}
.dl-desc {
padding-left: 15px;
width: 75%;
}
/* status message */
.download-progress {
background-color: var(--highlight-bg);
text-align: center;
padding: 30px 0 15px 0;
}
/* settings */
.settings-group {
background-color: var(--highlight-bg);
padding: 20px;
margin: 20px 0;
}
.settings-item {
margin-top: 25px;
}
.settings-item input {
min-width: 300px;
}
/* about */
.about-section {
padding: 20px 0;
}
.about-section ol {
margin-left: 20px;
}
.about-section ul {
margin-top: 15px;
}
.about-section li {
margin-bottom: 10px;
}
.about-icon img {
margin-left: 5px;
width: 20px;
cursor: unset;
}
/* animation */
.rotate-img {
animation: rotation 4s infinite linear;
}
.bounce-img {
animation: bounce 1.5s infinite ease-in-out alternate;
}
.pulse-img {
animation: pulse 1.5s infinite ease-in-out alternate;
}
@keyframes rotation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(359deg);
}
}
@keyframes bounce {
0% {
transform: translateY(-5%);
}
100% {
transform: translateY(5%);
scale: 1.15;
}
}
@keyframes pulse {
0% {
scale: 1;
}
100% {
scale: 1.15;
}
}
/* tablet */
@media screen and (max-width: 1000px) {
.boxed-content {
width: 90%;
}
.video-list {
grid-template-columns: 1fr 1fr;
}
.two-col {
display: block;
}
.two-col > div {
width: 100%;
}
}
/* phone */
@media screen and (max-width: 600px) {
* {
word-wrap: anywhere;
}
.video-list {
grid-template-columns: 1fr;
}
.boxed-content {
width: 95%;
}
.footer {
text-align: center;
}
.top-nav {
flex-wrap: wrap-reverse;
display: flex;
}
.nav-icons {
width: 100%;
justify-content: center;
position: unset;
transform: unset;
}
.nav-item {
padding: unset;
margin: 15px;
}
.sort {
display: block;
}
.sort > div {
display: block;
}
.sort select {
width: 100%;
margin: unset;
}
.info-box-2,
.info-box-3 {
grid-template-columns: 1fr;
}
.description-box {
display: block;
}
.dl-item {
display: block;
}
.dl-thumb {
width: 100%;
}
.dl-desc {
padding: 15px;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icon_add.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.85859018"
inkscape:cx="-97.380081"
inkscape:cy="261.09215"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1"
showguides="true"
inkscape:guide-bbox="true">
<sodipodi:guide
position="-221.87586,143.2945"
orientation="1,0"
id="guide1072"
inkscape:locked="false" />
</sodipodi:namedview>
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 58.600542,170.62113 c -1.62283,1.61686 -2.626579,3.8573 -2.631447,6.33943 l -0.08037,43.5977 -43.597706,-0.0803 c -4.9648228,-0.009 -8.9691711,3.98046 -8.9784054,8.94536 l -0.00482,2.62846 c -0.00925,4.9649 3.9804459,8.96933 8.9452674,8.97832 l 43.597694,0.0805 -0.08027,43.59778 c -0.0093,4.96488 3.980368,8.96922 8.945263,8.9783 l 2.628471,0.005 c 4.964897,0.009 8.969245,-3.98054 8.978406,-8.94536 l 0.08035,-43.59771 43.597715,0.0803 c 4.96484,0.009 8.96917,-3.98046 8.9784,-8.94534 l 0.005,-2.62847 c 0.009,-4.96489 -3.98037,-8.96923 -8.94525,-8.97831 l -43.597784,-0.0805 0.08034,-43.59771 c 0.0093,-4.96481 -3.980379,-8.96923 -8.945267,-8.97831 l -2.628469,-0.005 c -2.482483,-0.005 -4.724106,0.98906 -6.346936,2.60592 z"
id="rect1073"
inkscape:connector-curvature="0" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_close.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4291625"
inkscape:cx="122.66624"
inkscape:cy="202.38142"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 115.5244,167.09017 c -3.04348,0 -6.08905,1.16742 -8.42111,3.49893 L 66.146003,211.54641 25.18874,170.5891 c -4.664143,-4.66413 -12.173961,-4.66413 -16.8382429,0 l -2.4692132,2.46935 c -4.664282,4.66413 -4.664282,12.17408 0,16.83807 l 40.9572491,40.9573 -40.9572491,40.95745 c -4.664282,4.66412 -4.664282,12.17393 0,16.83806 l 2.4692132,2.46935 c 4.6642819,4.66413 12.1740999,4.66413 16.8382429,0 l 40.957263,-40.9573 40.957287,40.9573 c 4.66413,4.66413 12.17393,4.66413 16.8382,0 l 2.46921,-2.46935 c 4.66427,-4.66413 4.66427,-12.17394 0,-16.83806 L 85.453463,230.85382 126.4107,189.89652 c 4.66427,-4.66399 4.66427,-12.17394 0,-16.83807 l -2.46921,-2.46935 c -2.33221,-2.33206 -5.37361,-3.49893 -8.41709,-3.49893 z"
id="rect1073"
inkscape:connector-curvature="0" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Download.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.71458126"
inkscape:cx="-376.84122"
inkscape:cy="260.65826"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="M 249.89062 39.6875 L 249.88477 39.693359 C 229.11581 39.693359 212.39453 59.135896 212.39453 83.289062 L 212.39453 289.66016 L 159.20312 236.46875 L 127.63867 268.05469 L 218.74805 359.14258 L 218.73242 359.1582 L 249.93555 390.33789 L 281.52148 358.77344 L 372.36133 267.91211 L 341.1582 236.73047 L 287.37891 290.50977 L 287.37891 83.283203 C 287.37891 59.130339 270.65971 39.6875 249.89062 39.6875 z M 50.566406 407.88867 C 44.284822 407.88867 39.228516 412.94498 39.228516 419.22656 L 39.228516 444.62695 C 39.228516 450.90854 44.284822 455.96484 50.566406 455.96484 L 449.43359 455.96484 C 455.71518 455.96484 460.77148 450.90854 460.77148 444.62695 L 460.77148 419.22656 C 460.77148 412.94498 455.71518 407.88867 449.43359 407.88867 L 50.566406 407.88867 z "
transform="matrix(0.26458394,0,0,0.26458394,0,164.70749)"
id="rect1208" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_Settings02.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.0105705"
inkscape:cx="-25.63665"
inkscape:cy="191.7261"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 57.383938,165.28042 c -4.849506,0 -8.753067,3.9047 -8.753067,8.75416 v 9.09569 a 50.663505,50.95301 0 0 0 -15.06221,8.94072 l -8.089206,-4.6705 c -4.199751,-2.42477 -9.533198,-0.99601 -11.957934,3.20377 l -8.61619,14.92534 c -2.4247365,4.19977 -0.9959782,9.53208 3.2037853,11.95684 l 8.3097237,4.79724 a 50.663505,50.95301 0 0 0 -0.791619,8.56976 50.663505,50.95301 0 0 0 0.811977,8.72482 l -8.0405786,4.64225 c -4.1997499,2.42476 -5.6285156,7.75707 -3.2037853,11.95677 l 8.6161899,14.92541 c 2.424737,4.19978 7.758197,5.62854 11.95794,3.20377 l 7.930877,-4.57893 a 50.663505,50.95301 0 0 0 14.93103,8.81636 v 9.12958 c 0,4.84953 3.903561,8.75306 8.753067,8.75306 h 17.234564 c 4.849471,0 8.753032,-3.90353 8.753032,-8.75306 v -8.90228 a 50.663505,50.95301 0 0 0 15.393578,-8.94415 l 7.757848,4.47942 c 4.19982,2.42477 9.53324,0.99601 11.95796,-3.20377 l 8.61621,-14.92541 c 2.42472,-4.1997 0.99596,-9.53201 -3.20378,-11.95677 l -7.78614,-4.49524 a 50.663505,50.95301 0 0 0 0.84705,-8.87183 50.663505,50.95301 0 0 0 -0.81197,-8.72475 l 8.0405,-4.64225 c 4.19982,-2.42476 5.62859,-7.75707 3.20385,-11.95684 l -8.6162,-14.92534 c -2.42474,-4.19978 -7.75823,-5.62854 -11.95797,-3.20377 l -7.930861,4.57893 a 50.663505,50.95301 0 0 0 -15.510075,-9.02895 v -8.91589 c 0,-4.84946 -3.903561,-8.75416 -8.753032,-8.75416 z m 8.9068,28.59545 A 36.767228,36.977328 0 0 1 103.05797,230.85344 36.767228,36.977328 0 0 1 66.290738,267.83108 36.767228,36.977328 0 0 1 29.5235,230.85344 36.767228,36.977328 0 0 1 66.290738,193.87587 Z"
id="path981"
inkscape:connector-curvature="0" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_Help.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.0105705"
inkscape:cx="58.993585"
inkscape:cy="143.32456"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<g
transform="matrix(6.2585232,0,0,6.2585232,-555.66096,-762.59652)"
id="g1069"
style="fill:#000000">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="M 99.35362,148.32944 A 10.406119,10.406119 0 0 0 88.947542,158.73553 10.406119,10.406119 0 0 0 99.35362,169.14162 10.406119,10.406119 0 0 0 109.7597,158.73553 10.406119,10.406119 0 0 0 99.35362,148.32944 Z m 0.022,2.79535 c 0.58489,0 1.12588,0.073 1.62304,0.2192 0.51178,0.14622 0.95018,0.37308 1.31574,0.68016 0.38018,0.30706 0.67262,0.70157 0.87734,1.18411 0.21933,0.46791 0.32933,1.02372 0.32933,1.6671 0,0.4533 -0.0809,0.86261 -0.24176,1.22816 -0.16084,0.35094 -0.3655,0.67987 -0.61408,0.98694 -0.23396,0.30706 -0.48991,0.60692 -0.76774,0.89936 -0.26321,0.27783 -0.51176,0.57027 -0.74571,0.87734 -0.21932,0.30707 -0.39436,0.63601 -0.52597,0.98694 -0.1316,0.33631 -0.17549,0.72394 -0.13163,1.16261 h -2.829714 c -0.07311,-0.49715 -0.0583,-0.95035 0.04406,-1.35979 0.116978,-0.40941 0.277739,-0.78965 0.482453,-1.14059 0.204712,-0.35093 0.431586,-0.67246 0.680164,-0.96491 0.263203,-0.29244 0.511747,-0.57062 0.745707,-0.83381 0.23395,-0.27783 0.4238,-0.54119 0.57002,-0.78977 0.16086,-0.26321 0.24123,-0.53344 0.24123,-0.81125 0,-0.4533 -0.13908,-0.79704 -0.41691,-1.03099 -0.2632,-0.23397 -0.61381,-0.35083 -1.052474,-0.35083 -0.409426,0 -0.774845,0.0952 -1.096536,0.28528 -0.307068,0.19009 -0.606919,0.43123 -0.899364,0.72368 l -1.7767,-1.62304 c 0.511782,-0.59952 1.118345,-1.08235 1.820217,-1.4479 0.716494,-0.36557 1.506571,-0.548 2.369287,-0.548 z m -0.307306,11.16414 c 0.555636,0 1.016256,0.19727 1.381816,0.59205 0.38018,0.38019 0.57003,0.86249 0.57003,1.44737 0,0.57028 -0.18985,1.05311 -0.57003,1.4479 -0.36556,0.38018 -0.82618,0.57002 -1.381816,0.57002 -0.555651,0 -1.016262,-0.18984 -1.38182,-0.57002 -0.36556,-0.39479 -0.548536,-0.87762 -0.548536,-1.4479 0,-0.58488 0.182976,-1.06718 0.548536,-1.44737 0.365558,-0.39478 0.826169,-0.59205 1.38182,-0.59205 z"
id="path1038"
inkscape:connector-curvature="0" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_play.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="3.4343607"
inkscape:cx="51.709313"
inkscape:cy="230.85077"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
sodipodi:type="star"
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
id="path1206"
sodipodi:sides="3"
sodipodi:cx="-142.60593"
sodipodi:cy="272.75879"
sodipodi:r1="30.817924"
sodipodi:r2="15.408962"
sodipodi:arg1="0.52359878"
sodipodi:arg2="1.5707963"
inkscape:flatsided="false"
inkscape:rounded="-3.46945e-18"
inkscape:randomized="0"
d="m -115.91682,288.16775 -26.68911,0 -26.6891,0 13.34455,-23.11344 13.34455,-23.11345 13.34456,23.11345 z"
transform="matrix(0,1.7014617,-1.7014617,0,530.04498,473.492)"
inkscape:transform-center-x="-18.792756" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Rescan Subscriptions.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.85859018"
inkscape:cx="125.63373"
inkscape:cy="156.7016"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="M 240.35352 18.810547 L 240.35352 29.246094 A 221.29301 221.29301 0 0 0 64.912109 129.45898 L 95.701172 150.14453 A 184.02261 184.02261 0 0 1 240.35352 66.369141 L 240.35352 87.705078 L 270.18359 70.480469 L 300.01562 53.257812 L 270.18359 36.035156 L 240.35352 18.810547 z M 312.28516 37.798828 L 301.08398 73.353516 A 184.02261 184.02261 0 0 1 422.6875 187.33594 L 406.34375 192.03125 L 431.13281 215.94922 L 455.92188 239.86719 L 464.24219 206.44141 L 472.56055 173.01367 L 458.55078 177.03711 A 221.29301 221.29301 0 0 0 312.28516 37.798828 z M 73.375 144.88281 L 48.585938 168.80078 L 23.796875 192.71875 L 35.617188 196.11328 A 221.29301 221.29301 0 0 0 28.707031 250 A 221.29301 221.29301 0 0 0 77.992188 388.9375 L 107.99805 366.83789 A 184.02261 184.02261 0 0 1 65.976562 250 A 184.02261 184.02261 0 0 1 71.474609 206.41211 L 90.013672 211.73633 L 81.693359 178.30859 L 73.375 144.88281 z M 433.95312 248.4375 A 184.02261 184.02261 0 0 1 434.02344 250 A 184.02261 184.02261 0 0 1 367.40625 391.49219 L 358.92773 380.14844 L 345.34375 411.80469 L 331.75977 443.45898 L 365.9668 439.39648 L 400.17188 435.33203 L 389.71484 421.33984 A 221.29301 221.29301 0 0 0 471.29297 250 A 221.29301 221.29301 0 0 0 471.23047 248.77539 L 433.95312 248.4375 z M 94.9375 385.80273 L 108.97852 417.25781 L 123.02148 448.71289 L 131.60156 436.87891 A 221.29301 221.29301 0 0 0 250 471.29297 A 221.29301 221.29301 0 0 0 328.64648 456.57227 L 315.99023 421.74805 A 184.02261 184.02261 0 0 1 250 434.02344 A 184.02261 184.02261 0 0 1 153.63867 406.48047 L 163.45898 392.93555 L 129.19727 389.36914 L 94.9375 385.80273 z "
transform="matrix(0.26458394,0,0,0.26458394,0,164.70749)"
id="path826" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_Lupe.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.0105705"
inkscape:cx="-23.955221"
inkscape:cy="207.58555"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#002130;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 15.593586,179.85791 c 18.094683,-18.09394 47.431291,-18.09355 65.52552,7.7e-4 16.496472,16.53809 18.102694,42.7696 3.747207,61.19678 17.821687,15.21024 24.490877,18.93088 42.171347,34.20969 4.41254,4.71717 4.29213,12.08299 -0.27223,16.65347 -4.57089,4.56126 -11.93421,4.68001 -16.65007,0.26874 l -8.4e-4,9.1e-4 -0.0173,-0.0152 C 94.335453,273.50898 90.211408,265.24542 76.792795,249.15281 58.360539,263.5048 32.12693,261.89037 15.593512,245.38662 c -18.0947127,-18.09455 -18.0947127,-47.43175 0,-65.52636 z m 7.908493,7.90846 c -13.7275962,13.72683 -13.7279739,35.98299 -8.23e-4,49.71019 13.72719,13.72714 35.983444,13.72678 49.710173,-8.2e-4 13.726834,-13.72692 13.726834,-35.98245 0,-49.70937 -13.726863,-13.72676 -35.982478,-13.72676 -49.70935,0 z"
id="rect826"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccccccccccccccc" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_seen-02.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.0316211"
inkscape:cx="67.654116"
inkscape:cy="175.0818"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="M 9.4628906 4.9277344 C 6.9502624 4.9277344 4.9277344 6.6131716 4.9277344 8.7070312 L 4.9277344 491.29297 C 4.9277344 493.38683 6.9502624 495.07227 9.4628906 495.07227 L 490.53711 495.07227 C 493.04974 495.07227 495.07227 493.38683 495.07227 491.29297 L 495.07227 8.7070312 C 495.07227 6.6131716 493.04974 4.9277344 490.53711 4.9277344 L 9.4628906 4.9277344 z M 53.607422 49.070312 L 446.39258 49.070312 C 448.90521 49.070312 450.92969 50.757703 450.92969 52.851562 L 450.92969 447.14844 C 450.92969 449.2423 448.90521 450.92969 446.39258 450.92969 L 53.607422 450.92969 C 51.094794 450.92969 49.070313 449.2423 49.070312 447.14844 L 49.070312 52.851562 C 49.070312 50.757703 51.094794 49.070312 53.607422 49.070312 z M 394.99414 104.48242 C 392.62745 104.47692 390.27922 105.49181 388.64453 107.46484 L 212.35547 320.24414 L 111.90625 232.94141 C 108.46825 229.95328 103.29681 230.31403 100.30859 233.75195 L 73.150391 264.99805 C 70.162261 268.43605 70.524968 273.60942 73.962891 276.59766 L 212.05469 396.62109 C 214.1632 398.4537 216.92406 399.02085 219.43359 398.39648 C 221.58781 398.24033 223.67676 397.24363 225.16992 395.44141 L 249.54883 366.01758 L 250.8125 364.5625 C 251.04106 364.29953 251.24412 364.0237 251.43359 363.74219 L 433.18555 144.36914 C 436.09166 140.86148 435.60727 135.69713 432.09961 132.79102 L 400.2207 106.37891 C 398.68612 105.10748 396.8349 104.4867 394.99414 104.48242 z "
transform="matrix(0.26458394,0,0,0.26458394,0,164.70749)"
id="rect816" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="Icons_thumbs.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.71458126"
inkscape:cx="-133.80736"
inkscape:cy="163.34297"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#1a1a1a;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 74.762046,169.84647 c -0.757275,-0.0266 -1.556205,0.0266 -2.398918,0.17006 -17.977757,2.9811 5.863528,29.19697 -15.075776,44.15933 -17.503229,14.60104 -23.870308,10.01972 -24.044759,14.80451 v 47.00292 c 2.623747,6.94761 20.093043,14.05087 38.660635,15.56434 18.567588,1.51346 44.529822,-2.41107 44.816272,-10.49357 0.15245,-7.31882 -4.01785,-7.48655 -4.01785,-7.48655 0,0 9.14077,-0.56532 9.44575,-8.4939 0.15212,-7.77626 -8.85445,-8.88809 -8.85445,-8.88809 0,0 11.53636,-0.3275 11.53636,-8.34902 0,-8.20546 -8.87381,-8.85175 -11.6189,-8.99092 1.70324,-0.10363 8.42562,-2.42967 8.3861,-10.53741 -0.0399,-8.37053 -12.87508,-7.67987 -35.956784,-9.20144 2.66326,-15.52873 4.52035,-48.76031 -10.87768,-49.26032 z m -63.387663,53.22425 c -2.167221,0 -3.911718,1.45375 -3.911718,3.25977 v 53.07599 c 0,1.80609 1.744497,3.25983 3.911718,3.25983 h 14.602385 c 2.167228,0 3.911725,-1.45374 3.911725,-3.25983 v -53.07599 c 0,-1.80602 -1.744497,-3.25977 -3.911725,-3.25977 z"
id="rect1278"
inkscape:connector-curvature="0" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="500"
height="500"
viewBox="0 0 132.29197 132.29167"
version="1.1"
id="svg1303"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
sodipodi:docname="icon-unseen.svg">
<defs
id="defs1297" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.72946627"
inkscape:cx="216.49148"
inkscape:cy="168.6324"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
units="px"
inkscape:window-width="1920"
inkscape:window-height="1017"
inkscape:window-x="-8"
inkscape:window-y="-8"
inkscape:window-maximized="1" />
<metadata
id="metadata1300">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Ebene 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-164.70764)">
<path
style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0;stroke-linecap:round;stroke-linejoin:bevel;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers fill stroke"
d="m 9.6367188,5.1015625 c -2.5126284,0 -4.5351563,1.6854372 -4.5351563,3.7792969 V 491.11914 c 0,2.09386 2.022528,3.7793 4.5351563,3.7793 H 490.36328 c 2.51263,0 4.53516,-1.68544 4.53516,-3.7793 V 8.8808594 c 0,-2.0938597 -2.02253,-3.7792969 -4.53516,-3.7792969 z M 53.748047,49.212891 H 446.25195 c 2.51263,0 4.53516,1.685437 4.53516,3.779297 V 447.00781 c 0,2.09386 -2.02253,3.7793 -4.53516,3.7793 H 53.748047 c -2.512628,0 -4.535156,-1.68544 -4.535156,-3.7793 V 52.992188 c 0,-2.09386 2.022528,-3.779297 4.535156,-3.779297 z"
transform="matrix(0.26458394,0,0,0.26458394,0,164.70749)"
id="rect816"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ssssssssssssssssss" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,84 @@
/**
* Handle progress bar on /download
*
*/
setTimeout(function(){
checkMessage();
}, 1000);
// initial check for messages
function checkMessage() {
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/downloads/progress', true);
req.onload = function() {
var dlProgress = req.response;
if (dlProgress['status']) {
console.log('start interval');
buildDownloadMessage(dlProgress);
handleInterval();
};
console.log(JSON.stringify(dlProgress));
};
req.send();
}
// set interval until no more messages
function handleInterval() {
var watchDownload = setInterval(function() {
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', '/downloads/progress', true);
req.onload = function() {
var dlProgress = req.response;
if (dlProgress['status']) {
console.log('continue interval');
buildDownloadMessage(dlProgress);
} else {
console.log('stop interval');
clearInterval(watchDownload);
location.reload();
};
console.log(JSON.stringify(dlProgress));
};
req.send();
}, 3000);
};
// remove and set message
function buildDownloadMessage(dlProgress) {
var box = document.getElementById('downloadMessage');
box.innerHTML = '';
var dlStatus = dlProgress['status'];
var dlTitle = dlProgress['title'];
var dlMessage = dlProgress['message'];
// animate
if (dlStatus === 'rescan') {
animate('rescan-icon', 'rotate-img');
} else if (dlStatus === 'downloading') {
animate('download-icon', 'bounce-img');
};
// div box
var box = document.getElementById('downloadMessage');
var message = document.createElement('div');
message.classList.add('download-progress');
message.id = 'progress';
message.setAttribute('data', dlStatus);
var title = document.createElement('h3');
title.innerHTML = dlTitle;
var messageText = document.createElement('p');
messageText.innerHTML = dlMessage;
message.appendChild(title);
message.appendChild(messageText);
box.appendChild(message);
};
function animate(elementId, animationClass) {
var toAnimate = document.getElementById(elementId);
if (toAnimate.className !== animationClass) {
toAnimate.className = animationClass;
console.log(elementId, animationClass);
}
}

View File

@ -0,0 +1,271 @@
function sortChange(sortValue) {
var payload = JSON.stringify({'sort_order': sortValue});
sendPost(payload);
setTimeout(function(){
location.reload();
return false;
}, 500);
}
function hideWatched(hideValue) {
var payload = JSON.stringify({'hide_watched': hideValue});
sendPost(payload);
setTimeout(function(){
location.reload();
return false;
}, 500);
}
function showSubscribedOnly(showValue) {
var payload = JSON.stringify({'show_subed_only': showValue});
sendPost(payload);
setTimeout(function(){
location.reload();
return false;
}, 500);
}
function isWatched(youtube_id) {
var payload = JSON.stringify({'watched': youtube_id});
sendPost(payload);
var seenIcon = document.createElement('img');
seenIcon.setAttribute('src', "/static/img/icon-seen.svg");
seenIcon.setAttribute('alt', 'seen-icon');
seenIcon.setAttribute('id', youtube_id);
seenIcon.classList = 'seen-icon';
document.getElementById(youtube_id).replaceWith(seenIcon);
}
function unsubscribe(channel_id) {
var payload = JSON.stringify({'unsubscribe': channel_id});
sendPost(payload);
document.getElementById('sub-' + channel_id).remove();
}
// download page buttons
function rescanPending() {
var payload = JSON.stringify({'rescan_pending': true});
animate('rescan-icon', 'rotate-img');
sendPost(payload);
setTimeout(function(){
handleInterval();
}, 500);
}
function dlPending() {
var payload = JSON.stringify({'dl_pending': true});
animate('download-icon', 'bounce-img');
sendPost(payload);
setTimeout(function(){
handleInterval();
}, 500);
}
function toIgnore(button) {
var youtube_id = button.getAttribute('data-id');
var payload = JSON.stringify({'ignore': youtube_id});
console.log(payload);
sendPost(payload);
document.getElementById('dl-' + youtube_id).remove();
}
function downloadNow(button) {
var youtube_id = button.getAttribute('data-id');
var payload = JSON.stringify({'dlnow': youtube_id});
animate('download-icon', 'bounce-img');
sendPost(payload);
setTimeout(function(){
handleInterval();
}, 500);
}
// player
function createPlayer(button) {
var mediaUrl = button.getAttribute('data-src');
var mediaThumb = button.getAttribute('data-thumb');
var mediaTitle = button.getAttribute('data-title');
var mediaChannel = button.getAttribute('data-channel');
var dataId = button.getAttribute('data-id');
// get watched status
var playedStatus = document.createDocumentFragment();
playedStatus.appendChild(document.getElementById(dataId));
// create player
removePlayer();
var playerElement = document.getElementById('player');
playerElement.setAttribute('data-id', dataId);
// playerElement.innerHTML = '';
var videoPlayer = document.createElement('video');
videoPlayer.setAttribute('src', mediaUrl);
videoPlayer.setAttribute('controls', true);
videoPlayer.setAttribute('autoplay', true);
videoPlayer.setAttribute('width', '100%');
videoPlayer.setAttribute('poster', mediaThumb);
playerElement.appendChild(videoPlayer);
// title bar
var titleBar = document.createElement('div');
titleBar.className = 'player-title';
// close
var closeButton = document.createElement('img');
closeButton.className = 'close-button';
closeButton.setAttribute('src', "/static/img/icon-close.svg");
closeButton.setAttribute('alt', 'close-icon');
closeButton.setAttribute('data', dataId);
closeButton.setAttribute('onclick', "removePlayer()");
closeButton.setAttribute('title', 'Close player');
titleBar.appendChild(closeButton);
// played
titleBar.appendChild(playedStatus);
playerElement.appendChild(titleBar);
// title
var videoTitle = document.createElement('p');
videoTitle.innerText = mediaTitle;
titleBar.appendChild(videoTitle);
var videoChannel = document.createElement('p');
videoChannel.innerText = mediaChannel
titleBar.appendChild(videoChannel);
// button
var videoButton = document.createElement('button');
videoButton.innerText = 'Details';
videoButton.setAttribute('onclick', "window.location.href='/video/" + dataId + "/';");
titleBar.appendChild(videoButton);
}
function removePlayer() {
var playerElement = document.getElementById('player');
if (playerElement.hasChildNodes()) {
var youtubeId = playerElement.getAttribute('data-id');
var playedStatus = document.createDocumentFragment();
playedStatus.appendChild(document.getElementById(youtubeId));
playerElement.innerHTML = '';
// append played status
var videoInfo = document.getElementById('video-info-' + youtubeId);
videoInfo.insertBefore(playedStatus, videoInfo.firstChild);
};
}
// searching channels
function searchChannels(query) {
var searchResultBox = document.getElementById('resultBox');
searchResultBox.innerHTML = '';
if (query.length > 1) {
var payload = JSON.stringify({'channel-search': query})
sendSearchAsYouType(payload);
console.log(payload);
};
}
function populateChannelResults(allResults) {
var searchResultBox = document.getElementById('resultBox');
for (let i = 0; i < allResults.length; i++) {
var singleResult = allResults[i];
var source = singleResult['source'];
var channelName = source['channel_name'];
var channelId = source['channel_id'];
var optionElement = document.createElement('option');
optionElement.value = channelName;
optionElement.setAttribute('data', channelId);
searchResultBox.appendChild(optionElement);
console.log(channelId, channelName);
}
}
function channelRedirect(){
var response = document.getElementById('resultBox');
var firstChild = response.firstChild
if (firstChild) {
var redirectId = firstChild.getAttribute('data');
console.log('redirecting: ' + redirectId);
location = '/channel/' + redirectId;
}
return false;
}
function sendSearchAsYouType(payload) {
console.log(payload);
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === 4) {
allResults = JSON.parse(http.response)['results'];
populateChannelResults(allResults);
}
}
http.open("POST", "/process/", true);
http.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
http.setRequestHeader("Content-type", "application/json");
http.send(payload);
}
// generic
function sendPost(payload) {
console.log(payload);
var http = new XMLHttpRequest();
http.open("POST", "/process/", true);
http.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
http.setRequestHeader("Content-type", "application/json");
http.send(payload);
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
};
};
return "";
}
// animations
function textReveal() {
var textBox = document.getElementById('text-reveal');
var button = document.getElementById('text-reveal-button');
var textBoxHeight = textBox.style.height;
if (textBoxHeight === 'unset') {
textBox.style.height = '0px';
button.innerText = 'Show';
} else {
textBox.style.height = 'unset';
button.innerText = 'Hide';
};
}
function showSearch() {
var searchBox = document.getElementById('search-box');
var displayStyle = searchBox.style.display
if (displayStyle === "") {
searchBox.style.display = 'block';
} else {
searchBox.style.display = "";
}
var inputBox = document.getElementById('searchInput');
inputBox.focus();
}
function showForm() {
console.log('show hidden form');
var formElement = document.getElementById('hidden-form');
var displayStyle = formElement.style.display
if (displayStyle === "") {
formElement.style.display = 'block';
animate('add-icon', 'pulse-img');
} else {
formElement.style.display = "";
}
}

8
uwsgi.ini Normal file
View File

@ -0,0 +1,8 @@
[uwsgi]
; chdir = /app
module=config.wsgi:application
master=True
pidfile=/tmp/project-master.pid
vacuum=True
max-requests=5000
socket = :8080