Initial commit

master 0.1
farfalleflickan 2 years ago
commit 35d84b3731
No known key found for this signature in database
GPG Key ID: 6506CE3E020FAF59
  1. 661
      LICENSE.md
  2. 75
      Makefile
  3. 45
      README.md
  4. 53
      extras/cmyflix.cfg
  5. 82
      extras/html/css/movie.css
  6. 140
      extras/html/css/tv.css
  7. 127
      extras/html/js/Mscript.js
  8. 260
      extras/html/js/TVScript.js
  9. 75
      extras/html/js/mainTVScript.js
  10. 379
      src/conf.c
  11. 73
      src/conf.h
  12. 1479
      src/cwalk.c
  13. 498
      src/cwalk.h
  14. 298
      src/fileList.c
  15. 33
      src/fileList.h
  16. 96
      src/iofiles.c
  17. 12
      src/iofiles.h
  18. 535
      src/main.c
  19. 22
      src/main.h
  20. 503
      src/movies.c
  21. 21
      src/movies.h
  22. 14
      src/thread.h
  23. 972
      src/tvshow.c
  24. 46
      src/tvshow.h
  25. 985
      src/utils.c
  26. 142
      src/utils.h

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

@ -0,0 +1,75 @@
SHELL:=/bin/bash
CFLAGS=-O2 -Wall -Wpedantic -Werror=vla -std=gnu99 -lcurl -lpthread -lbsd -lcjson -ggdb
BINARY_FILE=cmyflix
BUILD_DIR=bin/
BINARY_PATH=${BUILD_DIR}${BINARY_FILE}
EXTRAS_DIR=extras/
DESTDIR=/
INSTALL_BIN_DIR=${DESTDIR}usr/local/bin/
INSTALL_ETC_DIR=${DESTDIR}etc/cmyflix/
.PHONY: bin clean ctags deb help install run uninstall valgrind callgrind
bin:
mkdir -p ${BUILD_DIR}
${CC} src/*.c ${CFLAGS} -o ${BINARY_PATH}
cp -r ${EXTRAS_DIR}* ${BUILD_DIR}
clean:
rm -rf ${BUILD_DIR}
@rm -rf deb
ctags:
@ctags -R --exclude=.git -f .tags src/ extras/
help:
@echo -e "The following are some of the valid targets for this Makefile:\n\tbin (the default if no target is provided)\n\tclean\n\tctags\n\thelp\n\tinstall\n\trun\n\tuninstall\n\tvalgrind\n\tcallgrind\n\tdeb\n"
install: bin
ifneq ($(shell id -u), 0)
@echo "You must be root to perform this action."
else
install -d ${INSTALL_BIN_DIR}
install -d ${INSTALL_ETC_DIR}
install ${BINARY_PATH} ${INSTALL_BIN_DIR}
cp -r ${EXTRAS_DIR}* ${INSTALL_ETC_DIR}
endif
run: bin
cd ${BUILD_DIR} && exec ./${BINARY_FILE} && cd ${PWD}
uninstall:
ifneq ($(shell id -u), 0)
@echo "You must be root to perform this action."
else
rm ${INSTALL_BIN_DIR}${BINARY_FILE}
rm -rf ${INSTALL_ETC_DIR}
endif
valgrind: bin
cd ${BUILD_DIR} && valgrind --max-threads=4096 --log-file=valgrindLog.txt --tool=memcheck --leak-check=full --show-leak-kinds=all --track-origins=yes -s ./${BINARY_FILE} && cat valgrindLog.txt
callgrind: bin
cd ${BUILD_DIR} && valgrind --tool=callgrind --dump-instr=yes --collect-jumps=yes ./${BINARY_FILE}
deb: bin
@ARCH_STR=$$(if command -v dpkg &> /dev/null; then dpkg --print-architecture; else arch=$$(uname -m); if [[ $$arch == *"i386"* ]]; then echo "i386"; elif [[ $$arch == *"i686"* ]]; then echo "i386"; elif [[ $$arch == *"x86_64"* ]]; then echo "amd64"; elif [[ $$arch == *"aarch64"* ]]; then echo "arm64"; elif [[ $$arch == *"armv8b"* ]]; then echo "arm64"; elif [[ $$arch == *"armv"*"l" ]]; then echo "armhf"; elif [[ $$arch == *"arm"* ]]; then echo "arm"; fi; fi); \
VERSION_STR=$$(grep -i '#define VERSION_STRING "' src/main.c | sed -e 's/\#define VERSION_STRING\ //g;s/\"//g'); \
PKG_DIR=${BINARY_FILE}_$${VERSION_STR}_$${ARCH_STR}; \
PKG_BIN_DIR=deb/$${PKG_DIR}/usr/local/bin/; \
PKG_ETC_DIR=deb/$${PKG_DIR}/etc/${BINARY_FILE}/; \
BIN=${BINARY_PATH}; \
EXTRAS=${EXTRAS_DIR}*; \
mkdir -p $${PKG_BIN_DIR}; \
mkdir -p $${PKG_ETC_DIR}; \
cp $${BIN} $${PKG_BIN_DIR}; \
cp -r $${EXTRAS}* $${PKG_ETC_DIR}; \
mkdir deb/$${PKG_DIR}/DEBIAN; \
echo -e "Package: cmyflix\nVersion: $${VERSION_STR}\nArchitecture: $${ARCH_STR}\nDepends: ffmpeg,imagemagick,libcjson1\nMaintainer: farfalleflickan <farfalleflickan@gmail.com>\nDescription: A static webpage generator for your movies and tv shows.\n For more info see: https://github.com/farfalleflickan/cmyflix" > deb/$${PKG_DIR}/DEBIAN/control; \
echo -e "#!/usr/bin/make -f\n%:\n dh $@\noverride_dh_install:\n dh_install $${PKG_ETC_DIR} /etc/${BINARY_FILE}\n" > deb/$${PKG_DIR}/DEBIAN/rules; \
cd deb && dpkg-deb --build --root-owner-group $${PKG_DIR}

@ -0,0 +1,45 @@
# cmyflix
*A Netflix clone, now in C!*
cmyflix is also a complete rewrite of my original ![Myflix](https://github.com/farfalleflickan/Myflix/) using C, so it's about 30x **faster** than the original whilst keeping almost all functionality.
cmyflix tries to be a somewhat simple and lightweight "DIY Netflix", similar to Plex, streama or Emby, for your NAS, especially aimed at the Raspberry Pi/Odroid/etc ecosystem. It's not **meant** or **designed** to be fancy (if you have the hardware and want a ton of functionality, go for other solutions :) ), but the bare minimum to be somewhat pretty, fast and usable. The program create json databases that store the files location and metadata, these databases are then used to create static web pages that can be served from any web server!
Big props to the following libraries: ![cwalk](https://github.com/likle/cwalk), ![cjson](https://github.com/DaveGamble/cJSON).
If you want to password protect your cmyflix files, you might want to look at ![this](https://github.com/farfalleflickan/JSONlogin)!
Do you like my work? Feel free to donate :)
[<img src="https://raw.githubusercontent.com/andreostrovsky/donate-with-paypal/master/dark.svg" alt="donation" width="150"/>](https://www.paypal.com/donate?hosted_button_id=YEAQ4WGKJKYQQ)
# Sreenshots:
TV shows page
![TV shows](https://github.com/farfalleflickan/Myflix/blob/master/screenshots/ec53e53f252f908bc8bac7f8c4486790.jpg)
TV show season/episode modal
![TV show episodes](https://github.com/farfalleflickan/Myflix/blob/master/screenshots/fb31129a22d81b732ce88f02cae27fea.jpg)
TV show episode player
![TV show episode player](https://github.com/farfalleflickan/Myflix/blob/master/screenshots/102b3df4924efeae7476d6ceee79bec9.png)
Movies page
![Movies](https://github.com/farfalleflickan/Myflix/blob/master/screenshots/d4271907a9af78d8dd84f3941ca1e56a.jpg)
Movies player
![Movies player](https://github.com/farfalleflickan/Myflix/blob/master/screenshots/2eb41c935d1c11e19adb66466bcdf97e.png)
# How to compile:
Simply compile by running make, the required libraries are (in Ubuntu) `libbsd-dev libcjson-dev libcurl4-openssl-dev`.
# How to install:
Either install from source with make install OR use a pre-compiled package from the release tab.
Beware, the pre-compiled `deb` file is built using the default `libcurl4-openssl-dev` backend.
# Requirements to run:
cmyflix uses libcjson(>=1.7.15), libcurl(>=7.68), imagemagick, ffmpeg and a TMDB api key.
# Configuration & usage:
For starters, cmyflix looks for `cmyflix.cfg` first in the same folder as the binary, then in `$HOME/.config/cmyflix/` and lastly in `/etc/cmyflix/`. Same thing applies for folder `html` and its contents.
For more options and information, look in the configuration file or see the help menu, which can be invoked by passing `--help`.

@ -0,0 +1,53 @@
TVpath="/etc/cmyflix/TV/"; # REMEMBER / at the end of path! identifies the path to the folder containing tv shows
MoviesPath="/etc/cmyflix/Movies/"; # identifies the path to the folder containing movies
dbNameMovie="/etc/cmyflix/dbM.json"; # identifies path and name of the movie database
dbNameTV="/etc/cmyflix/dbTV.json"; # identifies path and name of the tv show database
# regex used to identify tv shows, uses the sS1eE01 or sS01eE01 or 01x01 or 1x01 format, in that order
regexTVnum="2";
regexTVstr1="(.*)[.][sS]([0-9]{1,2})[eE]([0-9]{1,3})[.\-\_](.*)";
regexTVstr2="(.*)[.]([0-9]{1,2})[x]([0-9]{1,3})[.\-\_](.*)";
# name of extras folder used to identify tv shows extras, default is "Season.Extra"
TVextraStr="Season.Extra";
regexTVgroups="5"; # expected number of capture groups of regex
regexM="(.*)[.](.*)"; # movie regex
regexHM="([0-9]+\-[0-9]+\-[0-9]+)"; # home movie regex
TVhtml="/etc/cmyflix/output/TV.html"; # path to the TV html page
showHTMLFolder="/etc/cmyflix/output/shows/"; # path to where to put html of every tv show
Mhtml="/etc/cmyflix/output/Movies.html"; # path to the movie html page
dTVImg="true"; # download TV poster images true/false
dTVFolder="/etc/cmyflix/output/TVimg/"; # path to folder containing the images once downloaded
AutogenImgResizeTVCmd="convert -background purple -fill white -size 500x735 -pointsize 36 -gravity center caption:";
compressImgTVCmd="convert -resize 500x -gravity center -crop 500x735+0+0 -strip -interlace Plane -gaussian-blur 0.05 -quality 80%"; #might need some tweaking?
compressImgTV="false"; # wether the image should be comprossed
prefImgWidthTV="2000"; # preferred width of poster image
prefImgRatioTV="0.667"; # preferred width/height ratio of poster image
prefImgLangTV="en"; # preferred language for poster image
# exactly the same as above
dMoImg="true";
dMoFolder="/etc/cmyflix/output/MoImg/";
AutogenImgResizeMoCmd="convert -background purple -fill white -size 500x735 -pointsize 36 -gravity center caption:";
compressImgMoCmd="convert -resize 500x -gravity center -crop 500x735+0+0 -strip -interlace Plane -gaussian-blur 0.05 -quality 80%"; #might need some tweaking?
compressImgMo="false";
prefImgWidthM="2000";
prefImgRatioM="0.667";
prefImgLangM="en";
getTVposter="true"; # download tv show metadata poster
getEpisodeName="true"; # download every episode name
createTVsubs="true"; # search for subs in same folder
getMposter="true"; # same as above
createMsubs="true"; # search for subs for movies
homeMovies="false"; # $MoviesPath contains home movies, do NOT treat as actual movies. homeMovies are sorted by filename
fileLimit="8192"; # sets rlimit for max number of open files, 8192 seems a good value
# your TMDB api key
TMDBapi="";

@ -0,0 +1,82 @@
body {
margin: 0;
padding: 0;
border: 0;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 5% auto; /* 15% from the top and centered */
padding: 10px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
min-height: 50px;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
.movieDiv{
margin: 5px;
}
.myBtn {
width: 18vw;
}
.myBtn:hover {
filter: brightness(30%);
}
@media only screen and (max-width: 768px) {
.myBtn {
height: auto;
width: 45vw;
}
}
.video_player{
width: 80%;
margin-left: 10%;
}
#wrapper {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
#paddingDiv {
content: "";
width: 0px;
height: 0px;
}

@ -0,0 +1,140 @@
body {
margin: 0;
padding: 0;
border: 0;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: auto;
margin-top: 2%; /* 15% from the top and centered */
padding: 10px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
min-height: 50px;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
#epTitle{
text-align: center;
}
.showDiv{
margin: 5px;
}
.myBtn {
width: 19vw;
}
.myBtn:hover {
filter: brightness(30%);
}
@media only screen and (max-width: 768px) {
.myBtn {
height:auto;
width: 45vw;
}
}
.video_player{
width: 60%;
width: calc(60% - 5px);
margin-left: 20%;
}
.showEpUl{
display: none;
list-style-type: none;
padding: 0;
margin: 0;
}
.epButton{
border: none;
width: 100%;
margin: 0;
padding: 0;
background-color: #F0F0F0;
}
.epButton:hover {
background-color: #999999;
}
.nextEpDiv {
width: 100%;
text-align: center;
}
.nextEpButton {
margin: 0 auto;
display: inline-block;
}
.prevEpButton {
margin: 0 auto;
display: inline-block;
}
.autoButtonLabel {
margin: 0 auto;
display: inline-block;
}
.autoButton {
}
#wrapper {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
#paddingDiv {
content: "";
width: 0px;
height: 0px;
}

@ -0,0 +1,127 @@
var modal = "";
var player = "";
var isFullscreen = 1;
document.addEventListener("fullscreenchange", FShandler);
document.addEventListener("webkitfullscreenchange", FShandler);
document.addEventListener("mozfullscreenchange", FShandler);
document.addEventListener("MSFullscreenChange", FShandler);
document.addEventListener("keydown", function (e) {
if (e.keyCode === 70) {
e.preventDefault();
e.stopPropagation();
if (isFullscreen % 2 === 0) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
if (player.requestFullscreen) {
player.requestFullscreen();
} else if (player.msRequestFullscreen) {
player.msRequestFullscreen();
} else if (player.mozRequestFullScreen) {
player.mozRequestFullScreen();
} else if (player.webkitRequestFullscreen) {
player.webkitRequestFullscreen();
}
}
} else if (e.keyCode === 37) {
e.preventDefault();
e.stopPropagation();
player.currentTime -= 5;
} else if (e.keyCode === 39) {
e.preventDefault();
e.stopPropagation();
player.currentTime += 5;
} else if (e.keyCode === 32) {
e.preventDefault();
e.stopPropagation();
if(player.paused){
player.play();
} else {
player.pause();
}
}
}, false);
function FShandler() {
isFullscreen++;
}
function showModal(elem){
var tempStr = elem.id;
tempStr = tempStr.replace("A", "B");
modal = document.getElementById(String(tempStr));
tempStr = tempStr.replace("B", "C");
player = document.getElementById(String(tempStr));
modal.style.display = "block";
}
function hideModal(){
modal.style.display = "none";
player.pause();
player = "";
}
function setAlt(elem, altStr){
var me = document.getElementById(elem.id);
me.alt = altStr;
me.style.display = "inline";
}
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
player.pause();
player = "";
}
};
function showModalsetSubs(elem, srcStr) {
var tempStr = elem.id;
tempStr = tempStr.replace("A", "B");
modal = document.getElementById(String(tempStr));
tempStr = tempStr.replace("B", "C");
player = document.getElementById(String(tempStr));
modal.style.display = "block";
var subNum=parseInt(player.childElementCount)-1;
var array = srcStr.split(',');
for (var i=1, j=0; i<=subNum; i++, j++){
player.children[i].src=array[j];
}
}
function setPadding(){
document.getElementById("paddingDiv").style.display="block";
var wrapper = document.getElementById("wrapper");
var wDiv = wrapper.offsetWidth;
var tempArr = document.getElementsByClassName("movieDiv");
var temp1 = tempArr[0];
var temp2 = tempArr[1];
var style = getComputedStyle(temp1);
var extraSpace = Math.abs(parseFloat((temp1.offsetLeft + temp1.getBoundingClientRect().width)-temp2.offsetLeft));
var sDiv = parseFloat(temp1.getBoundingClientRect().width);
var currentElHeight=parseInt(style.marginTop)+temp1.offsetHeight;
var rate = Math.floor(wDiv/(sDiv+(extraSpace/2)));
var numbEl = (wrapper.childElementCount-1)%rate;
var realRate = Math.floor(rate-numbEl);
var extraElementW=sDiv*realRate+extraSpace*(realRate-1)+parseFloat(style.marginLeft);
if (numbEl <= 0){
extraElementW=0;
currentElHeight=0;
document.getElementById("paddingDiv").style.display="none";
} else {
document.getElementById("paddingDiv").style.width=extraElementW.toString()+"px";
document.getElementById("paddingDiv").style.paddingLeft="5px";
document.getElementById("paddingDiv").style.height=currentElHeight.toString()+"px";
}
}
window.onload=setPadding;
window.onresize=setPadding;

@ -0,0 +1,260 @@
var modal = "";
var ulElement = "";
var selElement = "";
var videoModal = "";
var player = "";
var myFrame = "";
var frameDiv = "";
var vidModalStatus=false;
var autoSwitchEpisode = false;
var isFullscreen = 1;
document.addEventListener("resize", rezHandler);
document.addEventListener("fullscreenchange", FShandler);
document.addEventListener("webkitfullscreenchange", FShandler);
document.addEventListener("mozfullscreenchange", FShandler);
document.addEventListener("MSFullscreenChange", FShandler);
document.addEventListener("keydown", function (e) {
if (e.keyCode === 70) {
e.preventDefault();
e.stopPropagation();
if (isFullscreen % 2 === 0) {
if (document.exitFullscreen) {
document.exitFullscreen();
rezHandler();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
rezHandler();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
rezHandler();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
rezHandler();
}
} else {
if (player.requestFullscreen) {
player.requestFullscreen();
} else if (player.msRequestFullscreen) {
player.msRequestFullscreen();
} else if (player.mozRequestFullScreen) {
player.mozRequestFullScreen();
} else if (player.webkitRequestFullscreen) {
player.webkitRequestFullscreen();
}
}
} else if (e.keyCode === 37) {
e.preventDefault();
e.stopPropagation();
player.currentTime -= 5;
} else if (e.keyCode === 39) {
e.preventDefault();
e.stopPropagation();
player.currentTime += 5;
if (player.currentTime >= player.duration){
nextEp();
}
} else if (e.keyCode === 32) {
e.preventDefault();
e.stopPropagation();
if(player.paused){
player.play();
} else {
player.pause();
}
}
}, false);
function rezHandler() {
if (vidModalStatus===true){
var tempHeight=videoModal.firstElementChild.offsetHeight+20;
parent.frameDiv.style.height=String(tempHeight)+"px";
document.body.style.overflow="hidden";
}
}
function FShandler() {
isFullscreen++;
}
function isDescendant(parent, child) {
var node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function changeSeason(elem) {
ulElement.style.display = "none";
var e = document.getElementById(elem.id);
var myVal = e.options[e.selectedIndex].value;
var tempStr = elem.id.replace("selector", "C");
tempStr = tempStr.split("C").pop();
tempStr = "C" + tempStr + String(myVal);
ulElement = document.getElementById(String(tempStr));
ulElement.style.display = "block";
parent.resizeFrame();
}
function showModal(id) {
var tempStr = id;
selElement = document.getElementById(String(id));
var myVal = selElement.value;
tempStr = tempStr.replace("selector", "C");
tempStr = tempStr.split("C").pop();
tempStr = "C" + tempStr + String(myVal);
ulElement = document.getElementById(String(tempStr));
ulElement.style.display = "block";
}
function showVideoModal(elem) {
var tempStr = elem.id;
tempStr = tempStr.replace("D", "E");
videoModal = document.getElementById(String(tempStr));
tempStr = tempStr.replace("E", "F");
player = document.getElementById(String(tempStr));
videoModal.style.cssText = "background-color: white; display: block;";
videoModal.firstElementChild.style.cssText = "width: auto; height: auto; margin: 0; padding: 0; border: 0;";
var tempHeight=(videoModal.firstElementChild.offsetHeight)+18;
parent.frameDiv.style.height=String(tempHeight)+"px";
vidModalStatus=true;
document.body.style.overflow="hidden";
}
function showVideoModalsetSubs(elem, srcStr) {
var tempStr = elem.id;
tempStr = tempStr.replace("D", "E");
videoModal = document.getElementById(String(tempStr));
tempStr = tempStr.replace("E", "F");
player = document.getElementById(String(tempStr));
videoModal.style.cssText = "background-color: white; display: block;";
videoModal.firstElementChild.style.cssText = "width: auto; height: auto; margin: 0; padding: 0; border: 0;";
var tempHeight=(videoModal.firstElementChild.offsetHeight)+18;
parent.frameDiv.style.height=String(tempHeight)+"px";
vidModalStatus=true;
document.body.style.overflow="hidden";
var subNum = parseInt(player.childElementCount) - 1;
var array = srcStr.split(',');
for (var i = 1, j = 0; i <= subNum; i++, j++) {
player.children[i].src = array[j];
}
}
function hideModal() {
parent.modal.style.display = "none";
parent.frameDiv = "";
}
function hideVideoModal() {
videoModal.style.display = "none";
document.body.style.overflow="auto";
player.pause();
player = "";
vidModalStatus=false;
parent.resizeFrame();
}
function resetPlayer(){
var myTime = player.currentTime;
var mySrc = player.children[0].src;
player.children[0].src="";
player.load();
player.children[0].src=mySrc;
player.currentTime = myTime;
player.load();
player.play();
}
function prevEp() {
var index = videoModal.id.indexOf("_");
var myID = videoModal.id.substr(0, index + 1);
var currentNum = parseInt(videoModal.id.substr(index + 1));
if (currentNum !== 0) {
videoModal.style.display = "none";
player.pause();
player = "";
currentNum -= 1;
tempStr = String(myID) + String(currentNum);
videoModal = document.getElementById(tempStr);
videoModal.style.display = "block";
if (isDescendant(ulElement, videoModal) === false && selElement.value !== 1) {
selElement.selectedIndex = parseInt(parseInt(selElement.value) - 2);
changeSeason(selElement);
}
tempStr = tempStr.replace("E", "F");
player = document.getElementById(String(tempStr));
player.play();
}
}
function nextEp() {
var index = videoModal.id.indexOf("_");
var myID = videoModal.id.substr(0, index + 1);
var currentNum = parseInt(videoModal.id.substr(index + 1));
currentNum += 1;
var tempStr = String(myID) + String(currentNum);
tempStr = tempStr.replace("E", "D");
var btnElem = document.getElementById(tempStr);
oldVolume = player.volume;
if (document.getElementById(tempStr) !== null) {
hideVideoModal();
btnElem.click();
if (isDescendant(ulElement, videoModal) === false) {
selElement.selectedIndex = parseInt(parseInt(selElement.value));
changeSeason(selElement);
}
if (autoSwitchEpisode === true) {
player.addEventListener('ended', nextEp);
}
if (isFullscreen % 2 === 0) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
player.volume = oldVolume;
player.play();
}
}
function autoSwitch() {
if (autoSwitchEpisode === false) {
autoSwitchEpisode = true;
var e = document.getElementsByClassName("autoButton");
player.addEventListener('ended', nextEp);
for (var i = 0; i < e.length; i++) {
e[i].checked = true;
}
} else {
autoSwitchEpisode = false;
player.removeEventListener('ended', nextEp);
var e = document.getElementsByClassName("autoButton");
for (var i = 0; i < e.length; i++) {
e[i].checked = false;
}
}
}
window.parent.onclick = function (event) {
if (event.target === parent.modal) {
if (player==""){
parent.modal.style.display = "none";
parent.myFrame="";
} else {
hideVideoModal();
}
}
};
parent.window.onresize=rezHandler;

@ -0,0 +1,75 @@
var modal = "";
var selElement = "";
var player = "";
var myFrame = "";
var frameDiv = "";
function setFrame(elem, name){
var tempStr = elem.id;
tempStr = tempStr.replace("A", "IN");
tempFrame = document.getElementById(String(tempStr));
myFrame=tempFrame;
tempStr = tempStr.replace("IN", "B");
modal = document.getElementById(String(tempStr));
modal.style.display = "block";
tempFrame.src=name;
}
function setAlt(elem, altStr) {
var me = document.getElementById(elem.id);
me.alt = altStr;
me.style.display = "inline";
}
function isDescendant(parent, child) {
var node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function setPadding(){
if (document.getElementById("paddingDiv")!=null){
document.getElementById("paddingDiv").style.display="block";
var wrapper = document.getElementById("wrapper");
var wDiv = wrapper.offsetWidth;
var tempArr = document.getElementsByClassName("showDiv");
var temp1 = tempArr[0];
var temp2 = tempArr[1];
var style = getComputedStyle(temp1);
var extraSpace = Math.abs(parseFloat((temp1.offsetLeft + temp1.getBoundingClientRect().width)-temp2.offsetLeft));
var sDiv = parseFloat(temp1.getBoundingClientRect().width);
var currentElHeight=parseInt(style.marginTop)+temp1.offsetHeight;
var rate = Math.floor(wDiv/(sDiv+(extraSpace/2)));
var numbEl = (wrapper.childElementCount-1)%rate;
var realRate = Math.floor(rate-numbEl);
var extraElementW=sDiv*realRate+extraSpace*(realRate-1)+parseFloat(style.marginLeft);
if (numbEl <= 0){
extraElementW=0;
currentElHeight=0;
document.getElementById("paddingDiv").style.display="none";
} else {
document.getElementById("paddingDiv").style.width=extraElementW.toString()+"px";
document.getElementById("paddingDiv").style.paddingLeft="5px";
document.getElementById("paddingDiv").style.height=currentElHeight.toString()+"px";
}
}
}
function resizeFrame(){
if (myFrame != null && myFrame != ""){
var tempHeight = myFrame.contentWindow.document.body.scrollHeight;
var tempStr = myFrame.id;
tempStr = tempStr.replace("IN", "frameDiv");
frameDiv = document.getElementById(String(tempStr));
frameDiv.style.height=String(tempHeight)+"px";
}
}
window.onload=setPadding;
window.onresize=setPadding;
window.onresize=resizeFrame;

@ -0,0 +1,379 @@
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <bsd/string.h>
#include <pthread.h>
#include "utils.h"
#include "conf.h"
progConfig *getConfig(char *srcPath) {
progConfig *options=calloc(1, sizeof(struct progConfig));
if (options==NULL) {
fatalError_abort("getConfig error", "could not calloc;\nError: %s;\n", strerror(errno));
}
// set all pointers to NULL
initAll(options);
// init all curl things
curl_global_init(CURL_GLOBAL_ALL);
options->cURLshare=curl_share_init();
mallocMacro(options->cURLconnLock, sizeof(pthread_mutex_t), "getConfig error");
pthread_mutex_init(options->cURLconnLock, NULL);
curl_share_setopt(options->cURLshare, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt(options->cURLshare, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
curl_share_setopt(options->cURLshare, CURLSHOPT_LOCKFUNC, curlLock);
curl_share_setopt(options->cURLshare, CURLSHOPT_UNLOCKFUNC, curlUnlock);
curl_share_setopt(options->cURLshare, CURLSHOPT_USERDATA, options->cURLconnLock);
// map config file
char *fileMap=fileToMem(srcPath);
if (fileMap==NULL) {
fatalError_exit("getConfig error", "configuration file \"%s\" is empty!\n%sUse \"cmyflix --gen-config > %s\" to generate default.\n", srcPath, HBLU, srcPath);
}
size_t fileSize=strlen(fileMap)+1;
char *buff=NULL;
mallocMacro(buff, fileSize, "getConfig error");
buff[0]='\0';
size_t properties=0;
int *offset=calloc(fileSize, sizeof(int));
if (offset==NULL) {
fatalError_abort("getConfig error", "could not calloc;\nError: %s;\n", strerror(errno));
}
// loop through config and find all "properties"
for (size_t i=0, mark=0, size=0, j=0; i<fileSize; i++) {
if (fileMap[i] == '"') {
mark++;
} else if ((fileMap[i] == '=' || fileMap[i]==';') && mark<10) { // we might have found a property!
offset[properties]=size;
properties++;
size=0;
} else if (fileMap[i] == '#') {
mark+=10;
} else if (fileMap[i] == '\n') {
mark=0;
} else if (mark<=1) {
size++;
buff[j]=fileMap[i];
j++;
}
}
options->properties=properties;
size_t buffSize=strlen(buff);
int tvReg=-1;
// loop through config and get value of each property
for (size_t i=0, pos=0; pos<buffSize; i+=2) {
char *confKey=NULL;
mallocMacro(confKey, offset[i]+1, "getConfig error");
confKey[0]='\0';
memcpy(confKey, buff+pos, offset[i]);
confKey[offset[i]]='\0';
char *confValue=NULL;
mallocMacro(confValue, offset[i+1]+1, "getConfig error");
confValue[0]='\0';
memcpy(confValue, buff+pos+offset[i], offset[i+1]);
confValue[offset[i+1]]='\0';
if (strcmp(confValue, "true")==0){
confValue[0]=true;
} else if (strcmp(confValue, "false")==0){
confValue[0]=false;
}
size_t tempPtrSize=strlen(confValue)+1;
if (strcmp(confKey, "TVpath")==0) {
options->TVpath=NULL;
mallocMacro(options->TVpath, tempPtrSize, "getConfig error");
strlcpy(options->TVpath, confValue, tempPtrSize);
} else if (strcmp(confKey, "MoviesPath")==0){
options->MoviesPath=NULL;
mallocMacro(options->MoviesPath, tempPtrSize, "getConfig error");
strlcpy(options->MoviesPath, confValue, tempPtrSize);
} else if (strcmp(confKey, "dbNameMovie")==0){
options->dbNameMovie=NULL;
mallocMacro(options->dbNameMovie, tempPtrSize, "getConfig error");
strlcpy(options->dbNameMovie, confValue, tempPtrSize);
} else if (strcmp(confKey, "dbNameTV")==0){
options->dbNameTV=NULL;
mallocMacro(options->dbNameTV, tempPtrSize, "getConfig error");
strlcpy(options->dbNameTV, confValue, tempPtrSize);
} else if (strcmp(confKey, "regexTVgroups")==0){
options->regexTVgroups=parseStrToInt(confValue);
} else if (strcmp(confKey, "regexTVnum")==0){
options->regexTVnum=parseStrToInt(confValue);
options->regexTVstr=NULL;
mallocMacro(options->regexTVstr, (1+options->regexTVnum)*sizeof(char *), "getConfig error");
tvReg=0;
} else if (strstr(confKey, "regexTVstr")){
/* add regex to regex array */
if (tvReg==-1){
confCleanup(options);
fatalError_abort("getConfig error", "regexTVstr declared before regexTVnum in the configuration!\n");
}
size_t iterSize=intSize(tvReg+1)+strlen("regexTVstr")+1;
char *tempBuff=NULL;
mallocMacro(tempBuff, iterSize, "getConfig error");
tempBuff[0]='\0';
snprintf(tempBuff, iterSize, "regexTVstr%d", tvReg+1);
if (strcmp(confKey, tempBuff)==0){
options->regexTVstr[tvReg]=NULL;
mallocMacro(options->regexTVstr[tvReg], tempPtrSize, "getConfig error");
strlcpy(options->regexTVstr[tvReg], confValue, tempPtrSize);
}
tryFree(tempBuff);
tvReg++;
} else if (strcmp(confKey, "TVextraStr")==0){
options->TVextraStr=NULL;
mallocMacro(options->TVextraStr, tempPtrSize, "getConfig error");
strlcpy(options->TVextraStr, confValue, tempPtrSize);
} else if (strcmp(confKey, "fileLimit")==0){
options->fileLimit=parseStrToInt(confValue);
} else if (strcmp(confKey, "regexM")==0){
options->regexM=NULL;
mallocMacro(options->regexM, tempPtrSize, "getConfig error");
strlcpy(options->regexM, confValue, tempPtrSize);
} else if (strcmp(confKey, "regexHM")==0){
options->regexHM=NULL;
mallocMacro(options->regexHM, tempPtrSize, "getConfig error");
strlcpy(options->regexHM, confValue, tempPtrSize);
} else if (strcmp(confKey, "TVhtml")==0){
options->TVhtml=NULL;
mallocMacro(options->TVhtml, tempPtrSize, "getConfig error");
strlcpy(options->TVhtml, confValue, tempPtrSize);
} else if (strcmp(confKey, "showHTMLFolder")==0){
options->showHTMLFolder=NULL;
mallocMacro(options->showHTMLFolder, tempPtrSize, "getConfig error");
strlcpy(options->showHTMLFolder, confValue, tempPtrSize);
} else if (strcmp(confKey, "Mhtml")==0){
options->Mhtml=NULL;
mallocMacro(options->Mhtml, tempPtrSize, "getConfig error");
strlcpy(options->Mhtml, confValue, tempPtrSize);
} else if (strcmp(confKey, "dTVImg")==0){
options->dTVImg=confValue[0];
} else if (strcmp(confKey, "dTVFolder")==0){
options->dTVFolder=NULL;
mallocMacro(options->dTVFolder, tempPtrSize, "getConfig error");
strlcpy(options->dTVFolder, confValue, tempPtrSize);
} else if (strcmp(confKey, "AutogenImgResizeTVCmd")==0){
options->AutogenImgResizeTVCmd=NULL;
mallocMacro(options->AutogenImgResizeTVCmd, tempPtrSize, "getConfig error");
strlcpy(options->AutogenImgResizeTVCmd, confValue, tempPtrSize);
} else if (strcmp(confKey, "compressImgTVCmd")==0){
options->compressImgTVCmd=NULL;
mallocMacro(options->compressImgTVCmd, tempPtrSize, "getConfig error");
strlcpy(options->compressImgTVCmd, confValue, tempPtrSize);
} else if (strcmp(confKey, "compressImgTV")==0){
options->compressImgTV=confValue[0];
} else if (strcmp(confKey, "prefImgWidthTV")==0){
options->prefImgWidthTV=parseStrToInt(confValue);
} else if (strcmp(confKey, "prefImgRatioTV")==0){
options->prefImgRatioTV=parseStrToDouble(confValue);
} else if (strcmp(confKey, "prefImgLangTV")==0){
options->prefImgLangTV=NULL;
mallocMacro(options->prefImgLangTV, tempPtrSize, "getConfig error");
strlcpy(options->prefImgLangTV, confValue, tempPtrSize);
} else if (strcmp(confKey, "dMoImg")==0){
options->dMoImg=confValue[0];
} else if (strcmp(confKey, "dMoFolder")==0){
options->dMoFolder=NULL;
mallocMacro(options->dMoFolder, tempPtrSize, "getConfig error");
strlcpy(options->dMoFolder, confValue, tempPtrSize);
} else if (strcmp(confKey, "AutogenImgResizeMoCmd")==0){
options->AutogenImgResizeMoCmd=NULL;
mallocMacro(options->AutogenImgResizeMoCmd, tempPtrSize, "getConfig error");
strlcpy(options->AutogenImgResizeMoCmd, confValue, tempPtrSize);
} else if (strcmp(confKey, "compressImgMoCmd")==0){
options->compressImgMoCmd=NULL;
mallocMacro(options->compressImgMoCmd, tempPtrSize, "getConfig error");
strlcpy(options->compressImgMoCmd, confValue, tempPtrSize);
} else if (strcmp(confKey, "compressImgMo")==0){
options->compressImgMo=confValue[0];
} else if (strcmp(confKey, "prefImgWidthM")==0){
options->prefImgWidthM=parseStrToInt(confValue);
} else if (strcmp(confKey, "prefImgRatioM")==0){
options->prefImgRatioM=parseStrToDouble(confValue);
} else if (strcmp(confKey, "prefImgLangM")==0){
options->prefImgLangM=NULL;
mallocMacro(options->prefImgLangM, tempPtrSize, "getConfig error");
strlcpy(options->prefImgLangM, confValue, tempPtrSize);
} else if (strcmp(confKey, "getTVposter")==0){
options->getTVposter=confValue[0];
} else if (strcmp(confKey, "getEpisodeName")==0){
options->getEpisodeName=confValue[0];
} else if (strcmp(confKey, "createTVsubs")==0){
options->createTVsubs=confValue[0];
} else if (strcmp(confKey, "getMposter")==0){
options->getMposter=confValue[0];
} else if (strcmp(confKey, "createMsubs")==0){
options->createMsubs=confValue[0];
} else if (strcmp(confKey, "homeMovies")==0){
options->homeMovies=confValue[0];
} else if (strcmp(confKey, "TMDBapi")==0){
options->TMDBapi=NULL;
mallocMacro(options->TMDBapi, tempPtrSize, "getConfig error");
strlcpy(options->TMDBapi, confValue, tempPtrSize);
} else {
fatalError_exit("getConfig error", "configuration file \"%s\" contains errors!\n%sUse \"cmyflix --gen-config > %s\" to generate default.\n", srcPath, HBLU, srcPath);
}
if (i<properties) {
pos+=offset[i]+offset[i+1];
} else {
pos=buffSize;
}
tryFree(confValue);
tryFree(confKey);
}
if (buffSize==0) {
fatalError_exit("getConfig error", "configuration file \"%s\" contains errors!\n%sUse \"cmyflix --gen-config > %s\" to generate default.\n", srcPath, HBLU, srcPath);
}
// TMDB api not set/incorrect length value, disable all related options
if ((options->TMDBapi==NULL || strlen(options->TMDBapi)!=32) && (options->getTVposter || options->getMposter || options->getEpisodeName)) {
options->getTVposter=false;
options->getMposter=false;
options->getEpisodeName=false;
printError("getConfig warning", false, HYEL, "TMDBapi invalid, disabling all related features...\n");
}
freeFileMem(srcPath, fileMap);
tryFree(offset);
tryFree(buff);
options->tvDB_exists=false;
options->moDB_exists=false;
if( access(options->dbNameTV, W_OK|R_OK) == -1 && errno!=ENOENT ) {
confCleanup(options);
fatalError_abort("getConfig error", "missing permissions for \"%s\";\nError: %s;\n", options->dbNameTV, strerror(errno));
} else {
// dbNameTV exists, load it to memory and parse the JSON
if (access(options->dbNameTV, F_OK)==0) {
options->JSON_tvDB=NULL;
options->tvDB_str=fileToMem(options->dbNameTV);
options->JSON_tvDB=cJSON_Parse(options->tvDB_str);
if (cJSON_GetErrorPtr()==NULL) {
options->tvDB_exists=true;
} else {
printError("getConfig warning", false, HYEL, "error whilst parsing %s, will rebuild DB...\n", options->dbNameTV);
}
}
}
if( access(options->dbNameMovie, W_OK|R_OK) == -1 && errno!=ENOENT ) {
confCleanup(options);
fatalError_abort("getConfig error", "missing permissions for \"%s\";\nError: %s;\n", options->dbNameMovie, strerror(errno));
} else {
// dbNameMovie exists, load it to memory and parse the JSON
if (access(options->dbNameMovie, F_OK)==0) {
options->JSON_moDB=NULL;
options->moDB_str=fileToMem(options->dbNameMovie);
options->JSON_moDB=cJSON_Parse(options->moDB_str);
if (cJSON_GetErrorPtr()==NULL) {
options->moDB_exists=true;
} else {
printError("getConfig warning", false, HYEL, "error whilst parsing %s, will rebuild DB...\n", options->dbNameMovie);
}
}
}
// set ulimit
if (options->fileLimit>0) {
if (getrlimit(RLIMIT_NOFILE, &(options->defLim))==0) {
if (options->defLim.rlim_cur<options->fileLimit) {
options->newLim.rlim_max=options->defLim.rlim_max;
options->newLim.rlim_cur=options->fileLimit;
if (setrlimit(RLIMIT_NOFILE, &(options->newLim))==-1){
confCleanup(options);
fatalError_abort("getConfig error", "could not set new fileLimit, error: %s\n", errno, strerror(errno));
}
}
}
}
// prepare PRNG for msleep
srand(time(NULL));
return options;
}
// free everything that conf allocates
void confCleanup(progConfig *options) {
if (options->tvDB_str!=NULL) {
freeFileMem(options->dbNameTV, options->tvDB_str);
}
if (options->moDB_str!=NULL) {
freeFileMem(options->dbNameMovie, options->moDB_str);
}
if (options->JSON_moDB!=NULL) {
cJSON_Delete(options->JSON_moDB);
}
if (options->JSON_tvDB!=NULL) {
cJSON_Delete(options->JSON_tvDB);
}
tryFree(options->TVpath);
tryFree(options->MoviesPath);
tryFree(options->dbNameMovie);
tryFree(options->dbNameTV);
for (int i=0; i<options->regexTVnum; i++) {
tryFree(options->regexTVstr[i]);
}
tryFree(options->regexTVstr);
tryFree(options->TVextraStr);
tryFree(options->regexM);
tryFree(options->regexHM);
tryFree(options->TVhtml);
tryFree(options->showHTMLFolder);
tryFree(options->Mhtml);
tryFree(options->dTVFolder);
tryFree(options->AutogenImgResizeTVCmd);
tryFree(options->prefImgLangTV);
tryFree(options->dMoFolder);
tryFree(options->AutogenImgResizeMoCmd);
tryFree(options->prefImgLangM);
tryFree(options->TMDBapi);
tryFree(options->compressImgMoCmd);
tryFree(options->compressImgTVCmd);
curl_share_cleanup(options->cURLshare);
pthread_mutex_destroy(options->cURLconnLock);
tryFree(options->cURLconnLock);
curl_global_cleanup();
tryFree(options);
}
// initialize all ptr of *options to NULL
void initAll(progConfig *options) {
if (options!=NULL) {
options->cURLshare=NULL;
options->cURLconnLock=NULL;
options->TVpath=NULL;
options->MoviesPath=NULL;
options->dbNameMovie=NULL;
options->dbNameTV=NULL;
options->regexTVstr=NULL;
options->TVextraStr=NULL;
options->regexM=NULL;
options->regexHM=NULL;
options->TVhtml=NULL;
options->showHTMLFolder=NULL;
options->Mhtml=NULL;
options->dTVFolder=NULL;
options->AutogenImgResizeTVCmd=NULL;
options->dMoFolder=NULL;
options->AutogenImgResizeMoCmd=NULL;
options->TMDBapi=NULL;
options->regexTVnum=-1;
options->getMposter=NULL;
options->getTVposter=NULL;
options->tvDB_str=NULL;
options->moDB_str=NULL;
options->prefImgLangM=NULL;
options->prefImgLangTV=NULL;
options->JSON_moDB=NULL;
options->JSON_tvDB=NULL;
} else {
fatalError_exit("initAll", "options is NULL.\n");
}
}

@ -0,0 +1,73 @@
#pragma once
#include <curl/curl.h>
#include <sys/resource.h>
#include <cjson/cJSON.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>
// default config
#define DEF_CONF "TVpath=\"/etc/cmyflix/TV/\"; # REMEMBER / at the end of path! identifies the path to the folder containing tv shows\nMoviesPath=\"/etc/cmyflix/Movies/\"; # identifies the path to the folder containing movies\n\ndbNameMovie=\"/etc/cmyflix/dbM.json\"; # identifies path and name of the movie database\ndbNameTV=\"/etc/cmyflix/dbTV.json\"; # identifies path and name of the tv show database\n\n# regex used to identify tv shows, uses the sS1eE01 or sS01eE01 or 01x01 or 1x01 format, in that order\nregexTVnum=\"2\";\nregexTVstr1=\"(.*)[.][sS]([0-9]{1,2})[eE]([0-9]{1,3})[.\\-\\_](.*)\";\nregexTVstr2=\"(.*)[.]([0-9]{1,2})[x]([0-9]{1,3})[.\\-\\_](.*)\";\n# name of extras folder used to identify tv shows extras, default is \"Season.Extra\"\nTVextraStr=\"Season.Extra\"; \nregexTVgroups=\"5\"; # expected number of capture groups of regex\n\nregexM=\"(.*)[.](.*)\"; # movie regex\n\nregexHM=\"([0-9]+\\-[0-9]+\\-[0-9]+)\"; # home movie regex\n\nTVhtml=\"/etc/cmyflix/output/TV.html\"; # path to the TV html page\nshowHTMLFolder=\"/etc/cmyflix/output/shows/\"; # path to where to put html of every tv show\nMhtml=\"/etc/cmyflix/output/Movies.html\"; # path to the movie html page\n\ndTVImg=\"true\"; # download TV poster images true/false\ndTVFolder=\"/etc/cmyflix/output/TVimg/\"; # path to folder containing the images once downloaded\nAutogenImgResizeTVCmd=\"convert -background purple -fill white -size 500x735 -pointsize 36 -gravity center caption:\";\ncompressImgTVCmd=\"convert -resize 500x -gravity center -crop 500x735+0+0 -strip -interlace Plane -gaussian-blur 0.05 -quality 80%\"; #might need some tweaking?\ncompressImgTV=\"false\"; # wether the image should be comprossed\nprefImgWidthTV=\"2000\"; # preferred width of poster image\nprefImgRatioTV=\"0.667\"; # preferred width/height ratio of poster image\nprefImgLangTV=\"en\"; # preferred language for poster image (ISO 639-1 code)\n\n# exactly the same as above\ndMoImg=\"true\";\ndMoFolder=\"/etc/cmyflix/output/MoImg/\";\nAutogenImgResizeMoCmd=\"convert -background purple -fill white -size 500x735 -pointsize 36 -gravity center caption:\";\ncompressImgMoCmd=\"convert -resize 500x -gravity center -crop 500x735+0+0 -strip -interlace Plane -gaussian-blur 0.05 -quality 80%\"; #might need some tweaking?\ncompressImgMo=\"false\";\nprefImgWidthM=\"2000\";\nprefImgRatioM=\"0.667\";\nprefImgLangM=\"en\"; # preferred language for poster image (ISO 639-1 code)\n\ngetTVposter=\"true\"; # download tv show metadata poster\ngetEpisodeName=\"true\"; # download every episode name\ncreateTVsubs=\"true\"; # search for subs in same folder\n\ngetMposter=\"true\"; # same as above\ncreateMsubs=\"true\"; # search for subs for movies\nhomeMovies=\"false\"; # $MoviesPath contains home movies, do NOT treat as actual movies. homeMovies are sorted by filename \n\nfileLimit=\"8192\"; # sets rlimit for max number of open files, 8192 seems a good value\n\n# your TMDB api key\nTMDBapi=\"\";"
typedef struct progConfig {
char *TVpath;
char *MoviesPath;
char *dbNameMovie;
char *dbNameTV;
char **regexTVstr;
char *TVextraStr;
char *regexM;
char *regexHM;
char *TVhtml;
char *showHTMLFolder;
char *Mhtml;
bool dTVImg;
char *dTVFolder;
char *AutogenImgResizeTVCmd;
char *compressImgTVCmd;
bool compressImgTV;
int prefImgWidthTV;
double prefImgRatioTV;
char *prefImgLangTV;
bool dMoImg;
char *dMoFolder;
char *AutogenImgResizeMoCmd;
char *compressImgMoCmd;
bool compressImgMo;
int prefImgWidthM;
double prefImgRatioM;
char *prefImgLangM;
bool getTVposter;
bool getEpisodeName;
bool createTVsubs;
bool getMposter;
bool createMsubs;
bool homeMovies;
char *TMDBapi;
int regexTVnum;
int regexTVgroups;
int properties;
size_t fileLimit;
bool tvDB_exists;
bool moDB_exists;
char *tvDB_str;
char *moDB_str;
cJSON *JSON_tvDB;
cJSON *JSON_moDB;
CURLSH *cURLshare;
pthread_mutex_t *cURLconnLock;
struct rlimit defLim;
struct rlimit newLim;
} progConfig;
progConfig *getConfig(char *srcPath);
void confCleanup(progConfig *options);
void initAll(progConfig *options);

File diff suppressed because it is too large Load Diff

@ -0,0 +1,498 @@
#pragma once
#ifndef CWK_LIBRARY_H
#define CWK_LIBRARY_H
#include <stdbool.h>
#include <stddef.h>
#if defined(_WIN32) || defined(__CYGWIN__)
#define CWK_EXPORT __declspec(dllexport)
#define CWK_IMPORT __declspec(dllimport)
#elif __GNUC__ >= 4
#define CWK_EXPORT __attribute__((visibility("default")))
#define CWK_IMPORT __attribute__((visibility("default")))
#else
#define CWK_EXPORT
#define CWK_IMPORT
#endif
#if defined(CWK_SHARED)
#if defined(CWK_EXPORTS)
#define CWK_PUBLIC CWK_EXPORT
#else
#define CWK_PUBLIC CWK_IMPORT
#endif
#else
#define CWK_PUBLIC
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/**
* A segment represents a single component of a path. For instance, on linux a
* path might look like this "/var/log/", which consists of two segments "var"
* and "log".
*/
struct cwk_segment
{
const char *path;
const char *segments;
const char *begin;
const char *end;
size_t size;
};
/**
* The segment type can be used to identify whether a segment is a special
* segment or not.
*
* CWK_NORMAL - normal folder or file segment
* CWK_CURRENT - "./" current folder segment
* CWK_BACK - "../" relative back navigation segment
*/
enum cwk_segment_type
{
CWK_NORMAL,
CWK_CURRENT,
CWK_BACK
};
/**
* @brief Determines the style which is used for the path parsing and
* generation.
*/
enum cwk_path_style
{
CWK_STYLE_WINDOWS,
CWK_STYLE_UNIX
};
/**
* @brief Generates an absolute path based on a base.
*
* This function generates an absolute path based on a base path and another
* path. It is guaranteed to return an absolute path. If the second submitted
* path is absolute, it will override the base path. The result will be
* written to a buffer, which might be truncated if the buffer is not large
* enough to hold the full path. However, the truncated result will always be
* null-terminated. The returned value is the amount of characters which the
* resulting path would take if it was not truncated (excluding the
* null-terminating character).
*
* @param base The absolute base path on which the relative path will be
* applied.
* @param path The relative path which will be applied on the base path.
* @param buffer The buffer where the result will be written to.
* @param buffer_size The size of the result buffer.
* @return Returns the total amount of characters of the new absolute path.
*/
CWK_PUBLIC size_t cwk_path_get_absolute(const char *base, const char *path,
char *buffer, size_t buffer_size);
/**
* @brief Generates a relative path based on a base.
*
* This function generates a relative path based on a base path and another
* path. It determines how to get to the submitted path, starting from the
* base directory. The result will be written to a buffer, which might be
* truncated if the buffer is not large enough to hold the full path. However,
* the truncated result will always be null-terminated. The returned value is
* the amount of characters which the resulting path would take if it was not
* truncated (excluding the null-terminating character).
*
* @param base_directory The base path from which the relative path will
* start.
* @param path The target path where the relative path will point to.
* @param buffer The buffer where the result will be written to.
* @param buffer_size The size of the result buffer.
* @return Returns the total amount of characters of the full path.
*/
CWK_PUBLIC size_t cwk_path_get_relative(const char *base_directory,
const char *path, char *buffer, size_t buffer_size);
/**
* @brief Joins two paths together.
*
* This function generates a new path by combining the two submitted paths. It
* will remove double separators, and unlike cwk_path_get_absolute it permits
* the use of two relative paths to combine. The result will be written to a
* buffer, which might be truncated if the buffer is not large enough to hold
* the full path. However, the truncated result will always be
* null-terminated. The returned value is the amount of characters which the
* resulting path would take if it was not truncated (excluding the
* null-terminating character).
*
* @param path_a The first path which comes first.
* @param path_b The second path which comes after the first.
* @param buffer The buffer where the result will be written to.
* @param buffer_size The size of the result buffer.
* @return Returns the total amount of characters of the full, combined path.
*/
CWK_PUBLIC size_t cwk_path_join(const char *path_a, const char *path_b,
char *buffer, size_t buffer_size);
/**
* @brief Joins multiple paths together.
*
* This function generates a new path by joining multiple paths together. It
* will remove double separators, and unlike cwk_path_get_absolute it permits
* the use of multiple relative paths to combine. The last path of the
* submitted string array must be set to NULL. The result will be written to a
* buffer, which might be truncated if the buffer is not large enough to hold
* the full path. However, the truncated result will always be
* null-terminated. The returned value is the amount of characters which the
* resulting path would take if it was not truncated (excluding the
* null-terminating character).
*
* @param paths An array of paths which will be joined.
* @param buffer The buffer where the result will be written to.
* @param buffer_size The size of the result buffer.
* @return Returns the total amount of characters of the full, combined path.
*/
CWK_PUBLIC size_t cwk_path_join_multiple(const char **paths, char *buffer,
size_t buffer_size);
/**
* @brief Determines the root of a path.
*
* This function determines the root of a path by finding its length. The
* root always starts at the submitted path. If the path has no root, the
* length will be set to zero.
*
* @param path The path which will be inspected.
* @param length The output of the root length.
*/
CWK_PUBLIC void cwk_path_get_root(const char *path, size_t *length);
/**
* @brief Changes the root of a path.
*
* This function changes the root of a path. It does not normalize the result.
* The result will be written to a buffer, which might be truncated if the
* buffer is not large enough to hold the full path. However, the truncated
* result will always be null-terminated. The returned value is the amount of
* characters which the resulting path would take if it was not truncated
* (excluding the null-terminating character).
*
* @param path The original path which will get a new root.
* @param new_root The new root which will be placed in the path.
* @param buffer The output buffer where the result is written to.
* @param buffer_size The size of the output buffer where the result is
* written to.
* @return Returns the total amount of characters of the new path.
*/
CWK_PUBLIC size_t cwk_path_change_root(const char *path, const char *new_root,
char *buffer, size_t buffer_size);
/**
* @brief Determine whether the path is absolute or not.
*
* This function checks whether the path is an absolute path or not. A path is
* considered to be absolute if the root ends with a separator.
*
* @param path The path which will be checked.
* @return Returns true if the path is absolute or false otherwise.
*/
CWK_PUBLIC bool cwk_path_is_absolute(const char *path);
/**
* @brief Determine whether the path is relative or not.
*
* This function checks whether the path is a relative path or not. A path is
* considered to be relative if the root does not end with a separator.
*
* @param path The path which will be checked.
* @return Returns true if the path is relative or false otherwise.
*/
CWK_PUBLIC bool cwk_path_is_relative(const char *path);
/**
* @brief Gets the basename of a file path.
*
* This function gets the basename of a file path. A pointer to the beginning
* of the basename will be returned through the basename parameter. This
* pointer will be positioned on the first letter after the separator. The
* length of the file path will be returned through the length parameter. The
* length will be set to zero and the basename to NULL if there is no basename
* available.
*
* @param path The path which will be inspected.
* @param basename The output of the basename pointer.
* @param length The output of the length of the basename. This may be
* null if not required.
*/
CWK_PUBLIC void cwk_path_get_basename(const char *path, const char **basename,
size_t *length);
/**
* @brief Changes the basename of a file path.
*
* This function changes the basename of a file path. This function will not
* write out more than the specified buffer can contain. However, the
* generated string is always null-terminated - even if not the whole path is
* written out. The function returns the total number of characters the
* complete buffer would have, even if it was not written out completely. The
* path may be the same memory address as the buffer.
*
* @param path The original path which will be used for the modified path.
* @param new_basename The new basename which will replace the old one.
* @param buffer The buffer where the changed path will be written to.
* @param buffer_size The size of the result buffer where the changed path is
* written to.
* @return Returns the size which the complete new path would have if it was
* not truncated.
*/
CWK_PUBLIC size_t cwk_path_change_basename(const char *path,
const char *new_basename, char *buffer, size_t buffer_size);
/**
* @brief Gets the dirname of a file path.
*
* This function determines the dirname of a file path and returns the length
* up to which character is considered to be part of it. If no dirname is
* found, the length will be set to zero. The beginning of the dirname is
* always equal to the submitted path pointer.
*
* @param path The path which will be inspected.
* @param length The length of the dirname.
*/
CWK_PUBLIC void cwk_path_get_dirname(const char *path, size_t *length);
/**
* @brief Gets the extension of a file path.
*
* This function extracts the extension portion of a file path. A pointer to
* the beginning of the extension will be returned through the extension
* parameter if an extension is found and true is returned. This pointer will
* be positioned on the dot. The length of the extension name will be returned
* through the length parameter. If no extension is found both parameters
* won't be touched and false will be returned.
*
* @param path The path which will be inspected.
* @param extension The output of the extension pointer.
* @param length The output of the length of the extension.
* @return Returns true if an extension is found or false otherwise.
*/
CWK_PUBLIC bool cwk_path_get_extension(const char *path, const char **extension,
size_t *length);
/**
* @brief Determines whether the file path has an extension.
*
* This function determines whether the submitted file path has an extension.
* This will evaluate to true if the last segment of the path contains a dot.
*
* @param path The path which will be inspected.
* @return Returns true if the path has an extension or false otherwise.
*/
CWK_PUBLIC bool cwk_path_has_extension(const char *path);
/**
* @brief Changes the extension of a file path.
*
* This function changes the extension of a file name. The function will
* append an extension if the basename does not have an extension, or use the
* extension as a basename if the path does not have a basename. This function
* will not write out more than the specified buffer can contain. However, the
* generated string is always null-terminated - even if not the whole path is
* written out. The function returns the total number of characters the
* complete buffer would have, even if it was not written out completely. The
* path may be the same memory address as the buffer.
*
* @param path The path which will be used to make the change.
* @param new_extension The extension which will be placed within the new
* path.
* @param buffer The output buffer where the result will be written to.
* @param buffer_size The size of the output buffer where the result will be
* written to.
* @return Returns the total size which the output would have if it was not
* truncated.
*/
CWK_PUBLIC size_t cwk_path_change_extension(const char *path,
const char *new_extension, char *buffer, size_t buffer_size);
/**
* @brief Creates a normalized version of the path.
*
* This function creates a normalized version of the path within the specified
* buffer. This function will not write out more than the specified buffer can
* contain. However, the generated string is always null-terminated - even if
* not the whole path is written out. The function returns the total number of
* characters the complete buffer would have, even if it was not written out
* completely. The path may be the same memory address as the buffer.
*
* The following will be true for the normalized path:
* 1) "../" will be resolved.
* 2) "./" will be removed.
* 3) double separators will be fixed with a single separator.
* 4) separator suffixes will be removed.
*
* @param path The path which will be normalized.
* @param buffer The buffer where the new path is written to.
* @param buffer_size The size of the buffer.
* @return The size which the complete normalized path has if it was not
* truncated.
*/
CWK_PUBLIC size_t cwk_path_normalize(const char *path, char *buffer,
size_t buffer_size);
/**
* @brief Finds common portions in two paths.
*
* This function finds common portions in two paths and returns the number
* characters from the beginning of the base path which are equal to the other
* path.
*
* @param path_base The base path which will be compared with the other path.
* @param path_other The other path which will compared with the base path.
* @return Returns the number of characters which are common in the base path.
*/
CWK_PUBLIC size_t cwk_path_get_intersection(const char *path_base,
const char *path_other);
/**
* @brief Gets the first segment of a path.
*
* This function finds the first segment of a path. The position of the
* segment is set to the first character after the separator, and the length
* counts all characters until the next separator (excluding the separator).
*
* @param path The path which will be inspected.
* @param segment The segment which will be extracted.
* @return Returns true if there is a segment or false if there is none.
*/
CWK_PUBLIC bool cwk_path_get_first_segment(const char *path,
struct cwk_segment *segment);
/**
* @brief Gets the last segment of the path.
*
* This function gets the last segment of a path. This function may return
* false if the path doesn't contain any segments, in which case the submitted
* segment parameter is not modified. The position of the segment is set to
* the first character after the separator, and the length counts all
* characters until the end of the path (excluding the separator).
*
* @param path The path which will be inspected.
* @param segment The segment which will be extracted.
* @return Returns true if there is a segment or false if there is none.
*/
CWK_PUBLIC bool cwk_path_get_last_segment(const char *path,
struct cwk_segment *segment);
/**
* @brief Advances to the next segment.
*
* This function advances the current segment to the next segment. If there
* are no more segments left, the submitted segment structure will stay
* unchanged and false is returned.
*
* @param segment The current segment which will be advanced to the next one.
* @return Returns true if another segment was found or false otherwise.
*/
CWK_PUBLIC bool cwk_path_get_next_segment(struct cwk_segment *segment);
/**
* @brief Moves to the previous segment.
*
* This function moves the current segment to the previous segment. If the
* current segment is the first one, the submitted segment structure will stay
* unchanged and false is returned.
*
* @param segment The current segment which will be moved to the previous one.
* @return Returns true if there is a segment before this one or false
* otherwise.
*/
CWK_PUBLIC bool cwk_path_get_previous_segment(struct cwk_segment *segment);
/**
* @brief Gets the type of the submitted path segment.
*
* This function inspects the contents of the segment and determines the type
* of it. Currently, there are three types CWK_NORMAL, CWK_CURRENT and
* CWK_BACK. A CWK_NORMAL segment is a normal folder or file entry. A
* CWK_CURRENT is a "./" and a CWK_BACK a "../" segment.
*
* @param segment The segment which will be inspected.
* @return Returns the type of the segment.
*/
CWK_PUBLIC enum cwk_segment_type cwk_path_get_segment_type(
const struct cwk_segment *segment);
/**
* @brief Changes the content of a segment.
*
* This function overrides the content of a segment to the submitted value and
* outputs the whole new path to the submitted buffer. The result might
* require less or more space than before if the new value length differs from
* the original length. The output is truncated if the new path is larger than
* the submitted buffer size, but it is always null-terminated. The source of
* the segment and the submitted buffer may be the same.
*
* @param segment The segment which will be modifier.
* @param value The new content of the segment.
* @param buffer The buffer where the modified path will be written to.
* @param buffer_size The size of the output buffer.
* @return Returns the total size which would have been written if the output
* was not truncated.
*/
CWK_PUBLIC size_t cwk_path_change_segment(struct cwk_segment *segment,
const char *value, char *buffer, size_t buffer_size);
/**
* @brief Checks whether the submitted pointer points to a separator.
*
* This function simply checks whether the submitted pointer points to a
* separator, which has to be null-terminated (but not necessarily after the
* separator). The function will return true if it is a separator, or false
* otherwise.
*
* @param symbol A pointer to a string.
* @return Returns true if it is a separator, or false otherwise.
*/
CWK_PUBLIC bool cwk_path_is_separator(const char *str);
/**
* @brief Guesses the path style.
*
* This function guesses the path style based on a submitted path-string. The
* guessing will look at the root and the type of slashes contained in the
* path and return the style which is more likely used in the path.
*
* @param path The path which will be inspected.
* @return Returns the style which is most likely used for the path.
*/
CWK_PUBLIC enum cwk_path_style cwk_path_guess_style(const char *path);
/**
* @brief Configures which path style is used.
*
* This function configures which path style is used. The following styles are
* currently supported.
*
* CWK_STYLE_WINDOWS: Use backslashes as a separator and volume for the root.
* CWK_STYLE_UNIX: Use slashes as a separator and a slash for the root.
*
* @param style The style which will be used from now on.
*/
CWK_PUBLIC void cwk_path_set_style(enum cwk_path_style style);
/**
* @brief Gets the path style configuration.
*
* This function gets the style configuration which is currently used for the
* paths. This configuration determines how paths are parsed and generated.
*
* @return Returns the current path style configuration.
*/
CWK_PUBLIC enum cwk_path_style cwk_path_get_style(void);
#ifdef __cplusplus
} // extern "C"
#endif
#endif

@ -0,0 +1,298 @@
#include <stdlib.h>
#include <stdbool.h>
#include <bsd/string.h>
#include <errno.h>
#include <stdarg.h>
#include "fileList.h"
#include "utils.h"
// create empty fileList
struct fileList *newList() {
fileList *list = NULL;
mallocMacro(list, sizeof(struct fileList), "newList error");
list->next = NULL;
list->data = NULL;
list->dataSize = 0;
list->listSize = 1;
return list;
}
// initialize fileList
fileList *initList(fileList *next, char **data, size_t dSize) {
fileList *list = newList();
list->data = data;
list->next = next;
list->dataSize = dSize;
list->listSize = 1;
return list;
}
// add link to filelist
fileList *add(fileList *head, char **data, size_t dSize) {
if (head!=NULL) {
fileList *list = initList(head, data, dSize);
list->listSize=head->listSize;
head = list;
head->listSize++;
} else {
head=initList(NULL, data, dSize);
}
return head;
}
// append 2 list to each other
fileList *joinLists(fileList *file, fileList *toAdd) {
fileList *cursor = file;
if (file == NULL && toAdd == NULL) { // both list NULL, return NULL
return NULL;
} else if (file != NULL && toAdd == NULL) { // toAdd is NULL, return file
return file;
} else if (file == NULL && toAdd != NULL) { // file is NULL, return toAdd
return toAdd;
} else {
// loop through file to append toAdd at the end
for (size_t i=0; cursor->next != NULL; cursor = cursor->next,i++) {
}
cursor->next = toAdd;
file->listSize+=toAdd->listSize;
return file;
}
}
// split list in half, helper for mergesort
// every other element goes to part2, rest goes to part 1
void splitList(fileList *list, fileList **part1, fileList **part2) {
if (list == NULL || list->next == NULL) {
*part1=list;
*part2=NULL;
return;
}
// temporary pointers
fileList *fast=list->next;
fileList *slow=list;
while(fast!=NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*part1=list;
*part2=slow->next;
slow->next=NULL;
}
// join 2 lists in a sorted manner (ascending or descending), depending on sortMode, helper for mergesort
// cmpPos specifies the position of the data to compare for sorting
// mode is a sortMode enum, is either INTEGER or STRING
fileList *sortedJoinLists(fileList *part1, fileList *part2, size_t cmpPos, bool isAscending, sortMode mode) {
if (part1==NULL) {
return part2;
} else if (part2==NULL) {
return part1;
}
fileList *list=NULL;
if (mode==INTEGER) {
int data1=0, data2=0;
if (part1->dataSize>cmpPos && part2->dataSize>cmpPos) {
data1=parseStrToInt(part1->data[cmpPos]);
data2=parseStrToInt(part2->data[cmpPos]);
}
if (data1 <= data2 && isAscending==true ) {
list=part1;
list->next=sortedJoinLists(part1->next, part2, cmpPos, isAscending, mode);
} else {
list=part2;
list->next=sortedJoinLists(part1, part2->next, cmpPos, isAscending, mode);
}
} else if (mode==STRING) {
char *name1=NULL, *name2=NULL;
if (cmpPos < part1->dataSize && part1->data[cmpPos]!=NULL) {
name1=part1->data[cmpPos];
}
if (cmpPos < part2->dataSize && part2->data[cmpPos]!=NULL) {
name2=part2->data[cmpPos];
}
if (name1!=NULL && name2!=NULL && strcmp(name1, name2)<0 && isAscending==true) { // name2 is later in the alphabet
list=part1;
list->next=sortedJoinLists(part1->next, part2, cmpPos, isAscending, mode);
} else {
list=part2;
list->next=sortedJoinLists(part1, part2->next, cmpPos, isAscending, mode);
}
}
return list;
}
// mergesort list
// cmpPos is the position of the data to compare for sortedJoinList
void msortList(fileList **list, size_t cmpPos, bool isAscending, sortMode mode) {
if ((*list)!=NULL && (*list)->next!=NULL) {
int initialSize=(*list)->listSize;
fileList *part1, *part2;
splitList(*list, &part1, &part2);
// recursively split the list
msortList(&part1, cmpPos, isAscending, mode);
msortList(&part2, cmpPos, isAscending, mode);
*list=sortedJoinLists(part1, part2, cmpPos, isAscending, mode);
// fix listSize
(*list)->listSize=initialSize;
}
}
// print list content to stdout, debug use only
void printList(fileList *list) {
if (list!=NULL) {
size_t j=0;
printf("List start, listSize:\t%zu\n", list->listSize);
for (fileList *temp=list; temp!=NULL; temp=temp->next) {
printf("\tdataSize:\t%zu;\n", temp->dataSize);
if (temp->dataSize==0) {
printf("\tlist[%zu]->data[]:\tNO DATA!;\n", j);
} else {
for (size_t i=0; i<temp->dataSize; i++) {
printf("\tlist[%zu]->data[%zu]:\t%s;\n", j, i, temp->data[i]);
}
}
j++;
}
printf("List end\n\n");
} else {
fatalError_abort("printList error", "cannot print list, it is NULL!\n");
}
}
// free all contents of filelist
void freeList(struct fileList *list) {
for (fileList *temp=list; temp!=NULL; ) {
fileList *tempNext=temp->next;
for (size_t i = 0; i < temp->dataSize; i++) {
tryFree(temp->data[i]);
}
tryFree(temp->data);
tryFree(temp);
temp=tempNext;
}
list=NULL;
}
// append data to list
void addData(fileList *list, char *data) {
size_t size = 0;
if (list->dataSize == 0) {
list->dataSize = 1;
size = 1;
} else {
size = list->dataSize + 1;
list->dataSize = size;
}
list->data = realloc(list->data, (size * sizeof (char **)));
if (list->data != NULL) {
size_t strLen = strlen(data)+1;
list->data[size-1] = NULL;
mallocMacro(list->data[size-1], strLen, "addData error");
strlcpy(list->data[size - 1], data, strLen);
} else {
fatalError_abort("addData error", "realloc failed;\nError: %s;\n", strerror(errno));
}
}
// convert JSON to fileList
// mode specifies the type of JSON, ie: TVSHOW or MOVIE (note: only MO_MODE, MOVIE, has different behaviour)
fileList *JSONtofileList(cJSON *json, ioMode mode) {
fileList *list = NULL;
cJSON *item=NULL;
cJSON_ArrayForEach(item, json) {
char *tempStr=cJSON_Print(item);
list=add(list, NULL, 0);
addData(list, tempStr);
if (mode==MO_MODE) {
char *movieName=cJSON_GetStringValue(cJSON_GetObjectItem(item, "Movie"));
addData(list, movieName);
}
tryFree(tempStr);
}
return list;
}
// save fileList to a file, takes a header and a footer to before and after the list data content
void fileListToFile(fileList *list, char *dest, char *headerStr, char *footerStr) {
FILE *file=fopen(dest, "w+");
if (file!=NULL) {
if (headerStr!=NULL && fputs(headerStr, file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
for (fileList *temp=list; temp!=NULL; temp=temp->next) {
for (size_t i=0; i<temp->dataSize; i++) {
if (fputs(temp->data[i], file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
}
if (temp->next!=NULL) {
if (fputs(",\n", file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
} else if (fputs("\n", file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
}
if (footerStr!=NULL && fputs(footerStr, file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
if (fputs("\0", file)==EOF) {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
} else {
fatalError_abort("fileListToFile error", "failed while writing to file \"%s\";\nError: %s;\n", dest, strerror(errno));
}
printInfo("fileListToFile", false, "done saving to \"%s\";\n", dest);
fclose(file);
}
// fileList to single string
char *fileListToJSONStr(fileList *list) {
size_t sizeStr=4;
char *listStr=NULL;
mallocMacro(listStr, sizeStr, "fileListToChar error");
listStr[0]='\0';
snprintf(listStr, sizeStr, "[\n");
for (fileList *temp=list; temp!=NULL; temp=temp->next) {
for (size_t i=0; i<temp->dataSize; i++) {
sizeStr+=strlen(temp->data[i]);
listStr=realloc(listStr, sizeStr);
if (listStr==NULL) {
fatalError_abort("fileListToChar", "could not realloc listStr;\nError: %s;\n", strerror(errno));
}
strlcat(listStr, temp->data[i], sizeStr);
}
if (temp->next!=NULL) {
sizeStr+=3;
listStr=realloc(listStr, sizeStr);
if (listStr==NULL) {
fatalError_abort("fileListToChar", "could not realloc listStr;\nError: %s;\n", strerror(errno));
}
strlcat(listStr, ",\n", sizeStr);
} else {
sizeStr+=2;
listStr=realloc(listStr, sizeStr);
if (listStr==NULL) {
fatalError_abort("fileListToChar", "could not realloc listStr;\nError: %s;\n", strerror(errno));
}
strlcat(listStr, "\n", sizeStr);
}
}
sizeStr+=2;
listStr=realloc(listStr, sizeStr);
if (listStr==NULL) {
fatalError_abort("fileListToChar", "could not realloc listStr;\nError: %s;\n", strerror(errno));
}
strlcat(listStr, "]", sizeStr);
return listStr;
}

@ -0,0 +1,33 @@
#pragma once
#include <cjson/cJSON.h>
#include "iofiles.h"
typedef struct fileList {
struct fileList *next;
char **data;
size_t dataSize;
size_t listSize;
} fileList;
typedef enum {
INTEGER=0,
STRING=1
} sortMode;
struct fileList *newList();
fileList *initList(fileList *next, char **data, size_t dSize);
fileList *add(fileList *head, char **data, size_t dSize);
fileList *joinLists(fileList *file, fileList *toAdd);
fileList *sortedJoinLists(fileList *part1, fileList *part2, size_t cmpPos, bool isAscending, sortMode mode);
fileList *JSONtofileList(cJSON *json, ioMode mode);
void splitList(fileList *list, fileList **part1, fileList **part2);
// mergeSort a list
void msortList(fileList **list, size_t cmpPos, bool isAscending, sortMode mode);
void freeList(struct fileList *list);
void printList(fileList *list);
// save fileList to a file, header is a string to be put at the top of the file
// footer is to be put at the end of file
void fileListToFile(fileList *list, char *dest, char *headerStr, char *footerStr);
char *fileListToJSONStr(fileList *list);
// append data to list
void addData(fileList *list, char *data);

@ -0,0 +1,96 @@
#include <dirent.h>
#include <stdbool.h>
#include <stdio.h>
#include <bsd/string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include "utils.h"
#include "fileList.h"
#include "iofiles.h"
// Own implementation with opendir/readdir. nftw might be faster? Dunno, nftw seemed slower in tests
struct fileList *find(progConfig *conf, char *dirPath, char *searchStr, ioMode mode, bool recursive) {
DIR *directory = opendir(dirPath);
if (directory == NULL) {
printError("find warning", false, HYEL, "failed while opening directory \"%s\";\nError: %s;\n", dirPath, strerror(errno));
return NULL;
}
fileList *list = NULL;
for (struct dirent *fileP = readdir(directory); fileP != NULL; fileP = readdir(directory)) { // loop through all files in directory
size_t nameLen = strlen(fileP->d_name);
if (fileP->d_name[0] != '.' && fileP->d_name[nameLen - 1] != '~') { // ignore hidden files & such
size_t pathLen = strlen(dirPath);
char *path=NULL;
mallocMacro(path, pathLen+nameLen+5, "find error");
strlcpy(path, dirPath, pathLen+nameLen+5);
if (dirPath[pathLen - 1] != '/') {
strlcat(path, "/", pathLen+nameLen+5);
}
strlcat(path, fileP->d_name, pathLen+nameLen+5);
struct stat statBuff;
// d_type is not always true, thus stat is needed for S_ISDIR
// fstat not used because path is needed regardless
if (stat(path, &statBuff) != 0) {
printError("find warning", false, HYEL, "failed running stat on \"%s\";\nError: %s;\n", path, strerror(errno));
return NULL;
}
if (S_ISDIR(statBuff.st_mode) && (mode & DI_MODE)!=0) { // if file is directory and if mode has dir bit set
if (recursive==true) {
if ((mode & FI_MODE)==0) { // if FI_MODE is *NOT* set
if (list==NULL) {
list=newList();
}
list = initList(list, NULL, 0);
addData(list, path);
}
fileList *temp = find(conf, path, searchStr, mode, recursive);
if (temp != NULL) {
list = joinLists(list, temp);
}
} else {
fileList *newFile=newList();
addData(newFile, dirPath);
addData(newFile, fileP->d_name);
list=joinLists(newFile, list);
}
} else if (strstr(fileP->d_name, searchStr) && (mode & FI_MODE)!=0) { // if filename matches the string we looking for AND in file mode
char **fileMatch = NULL;
if ((mode & TV_MODE)!=0) { // if TV mode bit set
// if ( conf->tvDB_exists==true && (mode & CK_MODE)!=0 && strstr(conf->tvDB_str, path)!=NULL) { // if filename already in database & in 'check mode'
for (int i=0; i<conf->regexTVnum && fileMatch == NULL; i++) {
fileMatch=matchReg(path, conf->regexTVstr[i], conf->regexTVgroups);
if (fileMatch!=NULL) {
fileList *newFile=newList();
for (int j=1; j<=parseStrToInt(fileMatch[0]); j++) {
addData(newFile, fileMatch[j]);
if (j==1) {
addData(newFile, dirPath);
addData(newFile, fileP->d_name);
}
}
list = joinLists(newFile, list);
}
}
} else if ((mode & MO_MODE)!=0) { // if movie mode bit set...
/*
* Nothing, else works just as well
*/
} else { // if in file mode but NOT in movie/tv mode...
fileList *newFile=newList();
addData(newFile, path);
addData(newFile, dirPath);
addData(newFile, fileP->d_name);
list=joinLists(newFile, list);
}
freeStrArr(fileMatch);
}
tryFree(path);
}
}
closedir(directory);
return list;
}

@ -0,0 +1,12 @@
#pragma once
#include "conf.h"
typedef enum {
NO_MODE=0 << 0, // NOOP?
DI_MODE=1 << 0, // Find directories
FI_MODE=1 << 1, // Find files
MO_MODE=1 << 2, // Movie mode
TV_MODE=1 << 3 // TV show mode
} ioMode;
struct fileList *find(progConfig *conf, char *dirPath, char *searchStr, ioMode mode, bool recursive);

@ -0,0 +1,535 @@
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <bsd/string.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <libgen.h>
#include <pwd.h>
#include "conf.h"
#include "utils.h"
#include "iofiles.h"
#include "tvshow.h"
#include "movies.h"
#include "fileList.h"
#include "thread.h"
#include "main.h"
#define REPO_URL "https://github.com/farfalleflickan/cmyflix"
#define VERSION_STRING "0.1"
// GLOBAL VARIABLES
FILE *LOGFILE=NULL;
/* PRINT_MODE:
0=default mode, (warnings, minimal progress messages)
1=verbose mode (add function in error/warnings, additional progress messages),
2=quiet mode (print only warnings/errors (no progress messages)),
3=quieter mode (print only errors (no progress messages)),
4=quietest mode (print nothing) */
unsigned int PRINT_MODE=0;
pthread_mutex_t *mutex_stdout;
struct timeval timeProgStart;
void printHelp() {
resetSTDColors();
printf("Usage: cmyflix [options]\n\n");
printf("Options:\n");
printf(" --conf path/to/file\t\t\tspecifies configuration file\n");
printf(" --log path/to/file\t\t\tspecify log file for all output\n");
printf(" --html path/to/folder\t\t\tspecify path to html resources\n");
printf(" --fix \"name\"\t\t\t\trun fix mode, requires a mode to be set (either -m/--movies or -t/--tvshows) and at least one fix mode option\n");
printf(" \t\t--id \t 12345\t\tspecifies new id for fix mode\n");
printf(" \t\t--name \t \"new name\"\tspecifies new name for fix mode\n");
printf(" \t\t--poster path/to/file\tspecifies new poster for fix mode\n");
printf(" \t\t--refresh\t\trefresh info of \"name\", so refreshes episode names in TV shows (also re-downloads poster if --poster \"\" is passed)\n");
printf(" --version\t\t\t\tprint version\n");
printf(" --gen-config\t\t\t\tprint default configuration to shell\n");
printf(" --check-update\t\t\tcheck if program update is available\n");
printf(" -c, --clean\t\t\t\tclean database, check if database entries correspond to existing files\n");
printf(" -h, --help\t\t\t\tprints this help screen\n");
printf(" -m, --movies\t\t\t\trun in movies mode\n");
printf(" -q, --quiet\t\t\t\tsuppress shell output (-q suppress info & only prints warnings, -qq suppresses all output, except fatal errors, -qqq print nothing)\n");
printf(" -t, --tvshows\t\t\t\trun in tv-shows mode\n");
printf(" -v, --verbose\t\t\t\tenhance shell output\n");
printf(" -D, --db\t\t\t\tbuild database\n");
printf(" -H, --html\t\t\t\tbuild HTML files\n\n");
printf("For documentation, see: " REPO_URL "\n");
}
void printVersion() {
resetSTDColors();
printf("cmyflix - version: %s\n", VERSION_STRING);
printf("Created by Daria Rostirolla;\n");
printf(REPO_URL "\n");
exit(EXIT_SUCCESS);
}
// check github to see if there is a new version
void checkUpdate() {
const char *URL="https://raw.githubusercontent.com/farfalleflickan/cmyflix/master/main.c";
const char *getVersionCmd="curl -s %s | grep -i '#define VERSION_STRING ' | sed -e 's/#define VERSION_STRING\\| //g;s/\"//g'";
size_t cmdStrSize=strlen(getVersionCmd)+strlen(URL)+1;
char *cmdStr=NULL;
mallocMacro(cmdStr, cmdStrSize, "checkUpdate error");
snprintf(cmdStr, cmdStrSize, getVersionCmd, URL);
resetSTDColors();
FILE *cmdRet=popen(cmdStr, "r");
if (cmdRet==NULL) {
if (pclose(cmdRet)!=0) {
printError("cmyflix", false, HRED, "%s\n", strerror(errno));
}
tryFree(cmdStr);
fatalError_exit("checkUpdate", "something went wrong while trying to check for an update, errno is: %s\n", strerror(errno));
} else {
double foundVersion=-1;
fscanf(cmdRet, "%lf", &foundVersion);
if (foundVersion==-1) {
fatalError_exit("checkUpdate", "something went wrong while trying to check for an update, used URL: %s\n", URL);
} else if (foundVersion==parseStrToDouble(VERSION_STRING)) {
fprintf(stdout, HYEL "cmyflix is up-to-date\n" COLOR_RESET);
} else if (foundVersion>parseStrToDouble(VERSION_STRING)) {
fprintf(stdout, HGRN "Found an update to version: %g;\nFor more info, see: %s\n" COLOR_RESET, foundVersion, REPO_URL);
}
}
if (pclose(cmdRet)!=0) {
printError("cmyflix", false, HRED, "%s\n", strerror(errno));
}
tryFree(cmdStr);
}
// tv shows code
void *tvCode(void *args) {
threadStruct *threadArg=(threadStruct *) args;
progConfig *conf=threadArg->conf;
progFlags runFlags=threadArg->flags;
if (runFlags & SHOWS_MODE) {
fileList *tv=NULL;
if (runFlags & DB_MODE) {
tv=createTVShowDB(conf); // find files and create/edit database
if (tv!=NULL) {
fileListToFile(tv, conf->dbNameTV, "[", "]");
} else {
printError("cmyflix", false, HYEL, "nothing in db to save to \"%s\";\n", conf->dbNameTV);
}
}
if (runFlags & HTML_MODE) {
if (tv==NULL && (runFlags & DB_MODE)==0) {
tv=JSONtofileList(conf->JSON_tvDB, TV_MODE);
if (tv==NULL) {
printError("cmyflix warning", false, HYEL, "Running in HTML mode but no database could be found!\nBuilding new database...\n");
tv=createTVShowDB(conf); // find files and create/edit database
if (tv!=NULL) {
fileListToFile(tv, conf->dbNameTV, "[", "]");
} else {
printError("cmyflix", false, HYEL, "nothing in db to save to \"%s\";\n", conf->dbNameTV);
}
}
}
if (tv!=NULL) {
createShowsHTML(conf, tv);
} else {
printError("cmyflix", false, HYEL, "nothing in db to save to \"%s\";\n", conf->TVhtml);
}
}
freeList(tv);
}
return NULL;
}
// movies code
void *movieCode(void *args) {
threadStruct *threadArg=(threadStruct *) args;
progConfig *conf=threadArg->conf;
progFlags runFlags=threadArg->flags;
if (runFlags & MOVIES_MODE) {
fileList *movies=NULL;
if (runFlags & DB_MODE) {
movies=createMoviesDB(conf);
if (movies!=NULL) {
fileListToFile(movies, conf->dbNameMovie, "[", "]");
} else {
printError("cmyflix", false, HYEL, "nothing in db to save to \"%s\";\n", conf->dbNameMovie);
}
}
if (runFlags & HTML_MODE) {
if (movies==NULL && (runFlags & DB_MODE)==0) {
movies=JSONtofileList(conf->JSON_moDB, MO_MODE);
if (movies==NULL) {
movies=createMoviesDB(conf);
if (movies!=NULL) {
fileListToFile(movies, conf->dbNameMovie, "[", "]");
} else {
printError("cmyflix", false, HYEL, "nothing in db to save to \"%s\";\n", conf->dbNameMovie);
}
}
}
if (movies!=NULL) {
createMoviesHTML(conf, movies);
} else {
printError("cmyflix", false, BHYEL, "nothing in db to save to \"%s\";\n", conf->Mhtml);
}
}
freeList(movies);
}
return NULL;
}
void copyExtras(progConfig *conf, progFlags runFlags, char *htmlFolder, char *defExtPath[]) {
char *extPath=NULL;
// if "--html" option is passed
if (htmlFolder!=NULL) {
extPath=htmlFolder;
} else { // otherwise load from found extras in defaults paths
for (int i=0; extPath==NULL; i++) {
if (defExtPath[i]!=NULL) {
if (access(defExtPath[i], F_OK)==0) {
extPath=defExtPath[i];
}
} else {
extPath=NULL;
break;
}
}
}
char *tempStr=NULL;
if (extPath!=NULL) {
if (runFlags & HTML_MODE) {
if ((runFlags & MOVIES_MODE)) {
tempStr=dirname(conf->Mhtml);
}
if ((runFlags & SHOWS_MODE)) {
tempStr=dirname(conf->TVhtml);
}
if (tempStr!=NULL) {
char *cmdStr=NULL;
size_t tempStrSize=strlen("cp -r /* ")+strlen(extPath)+strlen(tempStr)+1;
mallocMacro(cmdStr, tempStrSize, "cmyflix error");
snprintf(cmdStr, tempStrSize, "cp -r %s/* %s", extPath, tempStr);
resetSTDColors();
FILE *cmdRet=popen(cmdStr, "r");
if (cmdRet==NULL) {
if (pclose(cmdRet)!=0) {
printError("cmyflix", false, HRED, "%s\n", strerror(errno));
}
tryFree(cmdStr);
fatalError_exit("cmyflix error", "something went wrong while trying to copy HTML resources from '%s' to '%s';\n", extPath, tempStr);
} else {
if (pclose(cmdRet)!=0) {
printError("cmyflix", false, HRED, "something went wrong while trying to copy HTML resources from '%s' to '%s';\n", extPath, tempStr);
printError("cmyflix", false, HRED, "%s\n", strerror(errno));
} else {
printInfo("", false, "Copied HTML resources from '%s' to '%s';\n", extPath, tempStr);
}
}
tryFree(cmdStr);
} else {
printError("cmyflix error", false, HRED, "could not get path to copy HTML resources to.\n");
}
}
} else {
printError("cmyflix error", false, HRED, "could not find HTML resources, paths tested:\n");
for (int i=0; defExtPath[i]!=NULL; i++) {
printError("cmyflix error", false, HRED, "\t%s\n", defExtPath[i]);
}
printError("cmyflix error", false, HRED, "nothing copied;\n");
}
}
void cleanMode(progConfig *conf, progFlags flags) {
pthread_t tvThread, movieThread;
threadStruct threadArgTV, threadArgMovies;
threadArgTV.conf=conf;
threadArgTV.flags=flags;
threadArgTV.oldJSON=NULL;
threadArgMovies.conf=conf;
threadArgMovies.flags=flags;
threadArgMovies.oldJSON=NULL;
if (flags & SHOWS_MODE) {
pthread_create(&tvThread, NULL, cleanTV, &threadArgTV);
}
if (flags & MOVIES_MODE) {
pthread_create(&movieThread, NULL, cleanMovies, &threadArgMovies);
}
if (flags & SHOWS_MODE) {
pthread_join(tvThread, NULL);
if (threadArgTV.oldJSON!=NULL) {
char *newDB=cJSON_Print(threadArgTV.oldJSON);
cJSON_Delete(threadArgTV.oldJSON);
writeCharToFile(newDB, conf->dbNameTV);
tryFree(newDB);
} else {
printInfo("cleanMode warning", true, "oldJSON was NULL!\n");
}
}
if (flags & MOVIES_MODE) {
pthread_join(movieThread, NULL);
if (threadArgMovies.oldJSON!=NULL) {
char *newDB=cJSON_Print(threadArgMovies.oldJSON);
cJSON_Delete(threadArgMovies.oldJSON);
writeCharToFile(newDB, conf->dbNameMovie);
tryFree(newDB);
} else {
printInfo("cleanMode warning", true, "oldJSON was NULL!\n");
}
}
if (flags & HTML_MODE) {
flags&=~DB_MODE;
threadArgTV.flags=flags;
threadArgMovies.flags=flags;
pthread_create(&tvThread, NULL, tvCode, &threadArgTV);
pthread_create(&movieThread, NULL, movieCode, &threadArgTV);
pthread_join(tvThread, NULL);
pthread_join(movieThread, NULL);
}
}
int main(int argc, char * argv[]) {
gettimeofday(&timeProgStart, NULL);
mallocMacro(mutex_stdout, sizeof(pthread_mutex_t), "cmyflix error");
pthread_mutex_init(mutex_stdout, NULL);
// construct default conf paths
char *binaryPath=dirname(argv[0]);
char *sameAsBinaryConfPath=NULL;
char *sameAsBinaryExtPath=NULL;
char *homeExtPath=NULL;
struct passwd *userPW=getpwuid(getuid());
size_t homeExtPathSize=strlen(userPW->pw_dir)+strlen("/.config/cmyflix/html/")+1;
mallocMacro(homeExtPath, homeExtPathSize, "cmyflix error");
snprintf(homeExtPath, homeExtPathSize, "%s/.config/cmyflix/html/", userPW->pw_dir);
char *homeConfPath=NULL;
size_t homeConfPathSize=strlen(userPW->pw_dir)+strlen("/.config/cmyflix/cmyflix.cfg")+1;
mallocMacro(homeConfPath, homeConfPathSize, "cmyflix error");
snprintf(homeConfPath, homeConfPathSize, "%s/.config/cmyflix/cmyflix.cfg", userPW->pw_dir);
if (binaryPath!=NULL) {
size_t tempStrSize=strlen(binaryPath)+strlen("/cmyflix.cfg")+1;
mallocMacro(sameAsBinaryConfPath, tempStrSize, "cmyflix error");
snprintf(sameAsBinaryConfPath, tempStrSize, "%s/cmyflix.cfg", binaryPath);
}
char *defConfPath[]={sameAsBinaryConfPath, homeConfPath, "/etc/cmyflix/cmyflix.cfg", NULL};
if (binaryPath!=NULL) {
size_t tempStrSize=strlen(binaryPath)+strlen("/cmyflix.cfg")+1;
mallocMacro(sameAsBinaryExtPath, tempStrSize, "cmyflix error");
snprintf(sameAsBinaryExtPath, tempStrSize, "%s/html/", binaryPath);
}
char *defExtPath[]={sameAsBinaryExtPath, homeExtPath, "/etc/cmyflix/html/", NULL};
const char *short_options="chmqtvDH";
struct option long_options[] = {
{"conf", required_argument, 0, '0'},
{"log", required_argument, 0, '1'},
{"html", required_argument, 0, '2'},
{"fix", required_argument, 0, '3'},
{"id", required_argument, 0, '4'},
{"poster", required_argument, 0, '5'},
{"name", required_argument, 0, '6'},
{"refresh", no_argument, 0, '7'},
{"version", no_argument, 0, '8'},
{"gen-config", no_argument, 0, '9'},
{"check-update", no_argument, 0, 'u'},
{"clean", no_argument, 0, 'c'},
{"help", no_argument, 0, 'h'},
{"movies", no_argument, 0, 'm'},
{"quiet", no_argument, 0, 'q'},
{"tvshows", no_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{"db", no_argument, 0, 'D'},
{"html", no_argument, 0, 'H'},
{0, 0, 0, 0 }
};
progFlags runFlags=0;
char *confFile=NULL, *htmlFolder=NULL, *fixStr=NULL, *fixID=NULL, *fixPoster=NULL, *fixName=NULL;
progConfig *conf = NULL;
opterr=0;
for (int currOption=0; currOption!=-1; currOption=getopt_long(argc, argv, short_options, long_options, NULL)) {
if (currOption=='0') { // --conf=
size_t strLen=strlen(optarg)+1;
if (confFile!=NULL) {
tryFree(confFile);
}
confFile=NULL;
mallocMacro(confFile, strLen, argv[0]);
strlcpy(confFile, optarg, strLen);
if (access(confFile, F_OK)==0) {
conf=getConfig(confFile);
} else {
fatalError_exit(argv[0], "could not open configuration file \"%s\": %s\n", confFile, strerror(errno));
}
} else if (currOption=='1') { // --log=
LOGFILE=fopen(optarg, "w");
if (LOGFILE==NULL) {
fatalError_exit("", "could not use log \"%s\": %s\n", optarg, strerror(errno));
}
} else if (currOption=='2') { // --html=
size_t strLen=strlen(optarg)+1;
mallocMacro(htmlFolder, strLen, argv[0]);
strlcpy(htmlFolder, optarg, strLen);
if (access(htmlFolder, F_OK)==0) {
} else {
fatalError_exit(argv[0], "could not access HTML folder \"%s\": %s\n", htmlFolder, strerror(errno));
}
} else if (currOption=='3') { // --fix=
runFlags |= FIX_MODE;
fixStr=optarg;
} else if (currOption=='4') { // --id
runFlags |= FIX_ID_MODE;
fixID=optarg;
} else if (currOption=='5') { // --poster
runFlags |= FIX_POSTER_MODE;
fixPoster=optarg;
if (optarg!=NULL && strlen(optarg)<=0) {
fixPoster=NULL;
}
} else if (currOption=='6') { // --name
fixName=optarg;
runFlags |= FIX_NAME_MODE;
} else if (currOption=='7') { // --refresh
runFlags |= FIX_REFR_MODE;
} else if (currOption=='8') { // --version
printVersion();
exit(EXIT_SUCCESS);
} else if (currOption=='9') { // --gen-config
resetSTDColors();
printf("%s\n", DEF_CONF);
exit(EXIT_SUCCESS);
} else if (currOption=='c') { // --clean
runFlags |= CLN_MODE;
} else if (currOption=='u') { // --check-update
checkUpdate();
exit(EXIT_SUCCESS);
} else if (currOption=='h') { // --help -h
printHelp();
exit(EXIT_SUCCESS);
} else if (currOption=='m') { // --movies -m
runFlags |= MOVIES_MODE;
} else if (currOption=='q') { // --quiet -q
if (PRINT_MODE<2) {
PRINT_MODE=2;
} else {
PRINT_MODE++;
}
} else if (currOption=='t') { // --tvshows -t
runFlags |= SHOWS_MODE;
} else if (currOption=='v') { // --verbose -v
PRINT_MODE=1;
} else if (currOption=='D') { // --db -D
runFlags |= DB_MODE;
} else if (currOption=='H') { // --html -H
runFlags |= HTML_MODE;
} else if (currOption=='?') { // error handling
if (optopt=='0' || optopt=='1' || optopt=='2' || optopt=='3' || optopt=='4' || optopt=='5' || optopt=='6') {
int option_index=(char) optopt - '0';
fatalError_exit(argv[0], "option '%s' requires an argument\n", long_options[option_index].name);
}
fatalError_exit(argv[0], "unknown argument\n");
}
}
if (optind < argc) {
printError(argv[0], false, HYEL, "invalid args: ");
while (optind < argc) {
fprintf(stderr, "%s ", argv[optind++]);
}
fprintf(stderr, "\n" COLOR_RESET);
exit(EXIT_FAILURE);
}
if (runFlags==0) { // nothing specified, defaults to everything
runFlags = SHOWS_MODE | MOVIES_MODE | DB_MODE | HTML_MODE;
} else if (((runFlags & DB_MODE) || (runFlags & HTML_MODE)) && ((runFlags & SHOWS_MODE)==0 && (runFlags & MOVIES_MODE)==0) && (runFlags & FIX_MODE)==0) {
// if in either DB mode or HTML mode, but without movies/shows specified (will use both), NOT in fix mode
runFlags |= SHOWS_MODE;
runFlags |= MOVIES_MODE;
} else if (((runFlags & DB_MODE)==0 && (runFlags & HTML_MODE)==0 && (runFlags & FIX_MODE)==0 && (runFlags & CLN_MODE)==0) && ((runFlags & SHOWS_MODE) || (runFlags & MOVIES_MODE))) {
// if in either movie or show mode, but without DB or HTML specified (will use both), NOT in fix mode
runFlags |= DB_MODE;
runFlags |= HTML_MODE;
} else if (((runFlags & DB_MODE) || (runFlags & HTML_MODE)) && ((runFlags & SHOWS_MODE) || (runFlags & MOVIES_MODE)) && (runFlags & FIX_MODE)==0) {
// if in either DB or HTML mode AND either movies or shows mode, AND NOT in FIX_MODE
} else if (runFlags == CLN_MODE) { // if only clean mode specified, add both shows & movies
runFlags |= SHOWS_MODE;
runFlags |= MOVIES_MODE;
} else if (runFlags > FIX_MODE && (runFlags & FIX_MODE)==0) {
printError("cmyflix", false, HRED, "Fix mode options passed without '--fix'\n");
fatalError_exit(argv[0], "exiting...\n");
} else if ((runFlags & FIX_MODE)==0 && (runFlags & CLN_MODE)==0) { // if nothing else was a match and not in FIX_MODE
printError(argv[0], false, HYEL, "strange, unpredicted bit flags!\n");
printBitFlags(runFlags);
fatalError_exit(argv[0], "exiting...\n");
}
for (int i=0; conf==NULL; i++) {
if (defConfPath[i]!=NULL) {
if (access(defConfPath[i], F_OK)==0) {
confFile=defConfPath[i];
conf=getConfig(confFile);
}
} else {
fatalError_exit(argv[0], "could not find any config file!\n");
}
}
if (runFlags & FIX_MODE) { // if in fix mode
// if in either TV show mode or movie mode *AND* ( --id or --poster or --name)
if (((runFlags & SHOWS_MODE) || (runFlags & MOVIES_MODE)) && ((runFlags & FIX_ID_MODE) || (runFlags & FIX_POSTER_MODE) || (runFlags & FIX_NAME_MODE) || (runFlags & FIX_REFR_MODE))) {
bool refreshMode=false;
if (runFlags & FIX_REFR_MODE) {
refreshMode=true;
}
if (fixMode(conf, runFlags, fixStr, fixID, fixPoster, fixName, refreshMode)!=0) { // fixMode found nothing to fix
char *usedDB=NULL;
if (runFlags & SHOWS_MODE) {
usedDB=conf->dbNameTV;
} else if (runFlags & MOVIES_MODE) {
usedDB=conf->dbNameMovie;
}
printError(argv[0], false, HYEL, "could not find '%s' to fix in '%s'!\n", fixStr, usedDB);
}
} else {
printError(argv[0], false, HRED, "invalid options for --fix\n");
}
} else if (runFlags & CLN_MODE) { // if in clean mode
cleanMode(conf, runFlags);
copyExtras(conf, runFlags, htmlFolder, defExtPath);
} else {
pthread_t tvThread, movieThread;
threadStruct threadArg;
threadArg.conf=conf;
threadArg.flags=runFlags;
pthread_create(&tvThread, NULL, tvCode, &threadArg);
pthread_create(&movieThread, NULL, movieCode, &threadArg);
pthread_join(tvThread, NULL);
pthread_join(movieThread, NULL);
copyExtras(conf, runFlags, htmlFolder, defExtPath);
}
confCleanup(conf);
pthread_mutex_destroy(mutex_stdout);
tryFree(mutex_stdout);
if (LOGFILE!=NULL) {
fclose(LOGFILE);
}
tryFree(sameAsBinaryConfPath);
tryFree(sameAsBinaryExtPath);
tryFree(homeConfPath);
tryFree(homeExtPath);
tryFree(htmlFolder);
return EXIT_SUCCESS;
}

@ -0,0 +1,22 @@
#pragma once
#include "conf.h"
typedef enum {
SHOWS_MODE = 1 << 0, // TV SHOWS MODE
MOVIES_MODE = 1 << 1, // MOVIES MODE
DB_MODE = 1 << 2, // DB MODE
HTML_MODE = 1 << 3, // HTML MODE
CLN_MODE = 1 << 4, // CLEAN MODE
FIX_MODE = 1 << 5, // FIX MODE
FIX_ID_MODE = 1 << 6, // FIX MODE ID
FIX_POSTER_MODE = 1 << 7, // FIX MODE POSTER
FIX_NAME_MODE = 1 << 8, // FIX MODE NAME
FIX_REFR_MODE = 1 << 9 // FIX MODE REFRESH
} progFlags;
void printHelp();
void printVersion();
void checkUpdate();
void *tvCode(void *args);
void *movieCode(void *args);
void cleanMode(progConfig *conf, progFlags flags);

@ -0,0 +1,503 @@
#include <cjson/cJSON.h>
#include <stdlib.h>
#include <pthread.h>
#include <bsd/string.h>
#include <errno.h>
#include <unistd.h>
#include "fileList.h"
#include "movies.h"
#include "iofiles.h"
#include "utils.h"
#include "thread.h"
struct fileList *createMoviesDB(progConfig *conf) {
fileList *folders=NULL;
char *infoStr="building home movies' database...";
if (conf->homeMovies==false) {
infoStr="building movies' database...";
folders=find(conf, conf->MoviesPath, "", DI_MODE, false);
}
printInfo("createMoviesDB info", true, "%s\n", infoStr);
if (folders!=NULL) {
int foldersListSize=folders->listSize, i=0;
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*foldersListSize, "createMoviesDB error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*foldersListSize, "createMoviesDB error");
for (fileList *temp=folders; temp!=NULL; temp=temp->next, i++) {
threadObj[i].conf=conf;
threadObj[i].data=temp->data;
threadObj[i].oldJSON=NULL;
threadObj[i].list=NULL;
threadObj[i].id=0;
pthread_create(&threads[i], NULL, findMovies, (void *) &threadObj[i]);
}
fileList *movieJSON=NULL;
for (i=0; i<foldersListSize; i++) { // loop through all found movies
pthread_join(threads[i], NULL);
if (threadObj[i].list!=NULL && threadObj[i].list->data!=NULL) { // if this list obj has data...
movieJSON=joinLists(movieJSON, threadObj[i].list); // join all to single list
} else {
freeList(threadObj[i].list);
}
}
tryFree(threads);
tryFree(threadObj);
freeList(folders);
// sort movies alphabetically
printInfo("createMoviesDB info", true, "sorting DB...\n");
msortList(&movieJSON, 1, true, STRING);
for (fileList *temp=movieJSON; temp!=NULL; temp=temp->next) { // remove temp->data[1] (which should be the movie name), meanwhile temp->data[0] is the whole movie JSON
if (temp->data!=NULL) {
tryFree(temp->data[1]);
temp->dataSize--;
}
}
char *jsonStr=fileListToJSONStr(movieJSON);
if (jsonStr!=NULL) {
cJSON_Delete(conf->JSON_moDB);
conf->JSON_moDB=cJSON_Parse(jsonStr);
}
tryFree(jsonStr);
return movieJSON;
} else { // basically, "home movies" behaviour
folders=find(conf, conf->MoviesPath, videoExt, DI_MODE | FI_MODE, true);
fileList *hmovieJSON=NULL;
if (folders!=NULL) {
if (conf->moDB_exists) { // Load old DB
hmovieJSON=joinLists(hmovieJSON, JSONtofileList(conf->JSON_moDB, MO_MODE));
}
for (fileList *temp=folders; temp!=NULL; temp=temp->next) {
if (temp->dataSize==3) { // stupid constant value
/* temp->data[0]=fullPath
* temp->data[1]="dirname"
* temp->data[2]=filename with extension
*/
if (conf->moDB_exists==true && strstr(conf->moDB_str, temp->data[2])!=NULL) { // already in DB
} else { // Add to DB
fileList *thisFile=newList();
char *movieName=removeExtension(temp->data[2]);
char *imgURL=genImage(conf->AutogenImgResizeMoCmd, conf->dMoFolder, movieName);
/*
// useless on genImage? compressed results bigger than original
if (conf->compressImgMo) {
imgURL=compressImg(conf->compressImgMoCmd, imgURL, true);
}
*/
if (imgURL==NULL) {
mallocMacro(imgURL, 1, "createMoviesDB error");
imgURL[0]='\0';
}
size_t JSONStrSize=strlen("{\"Movie\":\"\",\"ID\":\"\",\"Poster\":\"\",\"File\":\"\", \"Subs\":[]}")+strlen(movieName)+intSize(0)+strlen(imgURL)+strlen(temp->data[0])+1;
char *movieJSONStr=NULL;
mallocMacro(movieJSONStr, JSONStrSize, "createMoviesDB error");
movieJSONStr[0]='\0';
snprintf(movieJSONStr, JSONStrSize, "{\"Movie\":\"%s\",\"ID\":\"%d\",\"Poster\":\"%s\",\"File\":\"%s\",\"Subs\":[]}", movieName, 0, imgURL, temp->data[0]);
addData(thisFile, movieJSONStr);
addData(thisFile, movieName);
hmovieJSON=joinLists(hmovieJSON, thisFile);
tryFree(movieName);
tryFree(imgURL);
tryFree(movieJSONStr);
}
} else {
printError("createMoviesDB error", false, HYEL, "weird dataSize! List was:\n");
printList(folders);
fatalError_abort("", "Panicing!\n");
}
}
freeList(folders);
// sort movies alphabetically
printInfo("createMoviesDB info", true, "sorting DB...\n");
msortList(&hmovieJSON, 1, true, STRING);
for (fileList *temp=hmovieJSON; temp!=NULL; temp=temp->next) { // remove temp->data[1] (which should be the movie name), meanwhile temp->data[0] is the whole movie JSON
if (temp->dataSize>1) {
tryFree(temp->data[1]);
temp->dataSize--;
}
}
char *jsonStr=fileListToJSONStr(hmovieJSON);
if (jsonStr!=NULL) {
cJSON_Delete(conf->JSON_moDB);
conf->JSON_moDB=cJSON_Parse(jsonStr);
}
tryFree(jsonStr);
return hmovieJSON;
} else {
printError("createMoviesDB warning", false, HYEL, "could not find anything in \"%s\";\n", conf->MoviesPath);
}
}
printInfo("createMoviesDB info", true, "finished building DB\n");
return NULL;
}
void *findMovies(void *threadArg) {
threadStruct *thisThread=(threadStruct *) threadArg;
progConfig *conf=thisThread->conf;
size_t lenStr1=strlen(thisThread->data[0]);
size_t lenStr2=strlen(thisThread->data[1]);
char *fullPath=NULL;
mallocMacro(fullPath, lenStr1+lenStr2+3, "findMovies error");
strlcpy(fullPath, thisThread->data[0], lenStr1+3);
if (fullPath[lenStr1 - 1] != '/') {
strlcat(fullPath, "/", lenStr1+lenStr2+3);
}
strlcat(fullPath, thisThread->data[1], lenStr1+lenStr2+3);
if (thisThread->data[1][lenStr2-1] != '/') {
strlcat(fullPath, "/", lenStr1+lenStr2+3);
}
// Find movie files
fileList *movies = find(conf, fullPath, videoExt, DI_MODE | FI_MODE, true);
thisThread->list=newList();
if (movies!=NULL) { // no sub folders?
// technically if folder contains just 1 movie, movies contains just 1 element
// if folder is a "collection" then as many elements as movies
for (fileList *temp=movies; temp!=NULL; temp=temp->next) {
char *moviePath=temp->data[temp->dataSize-2]; // path to movie file
char *movieFile=temp->data[0];
char *movieNameNoExt=removeExtension(temp->data[temp->dataSize-1]); // name of movie file
char *movieName=replaceAll(movieNameNoExt, ".", " ");
char *imgURL=NULL;
int movieID=0;
// open JSON database/set up cJSON
cJSON *tempJSON=NULL;
if (conf->moDB_exists==true && strstr(conf->moDB_str, movieFile)!=NULL) {
tempJSON=cJSON_Duplicate(conf->JSON_moDB, true);
if (tempJSON!=NULL) {
cJSON *item=NULL;
cJSON_ArrayForEach(item, tempJSON) {
if (cJSON_GetObjectItem(item, "File")!=NULL && cJSON_GetStringValue(cJSON_GetObjectItem(item, "File"))!=NULL) {
if (strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(item, "File")), movieFile)==0) { // match
movieID=parseStrToInt(cJSON_GetStringValue(cJSON_GetObjectItem(item, "ID")));
char *tempStr=cJSON_GetStringValue(cJSON_GetObjectItem(item, "Poster"));
size_t tempStrLen=strlen(tempStr)+1;
if (tempStrLen>3) {
mallocMacro(imgURL, tempStrLen, "findMovies error");
strlcpy(imgURL, tempStr, tempStrLen);
}
break;
}
}
}
cJSON_Delete(tempJSON);
}
}
char *movieSubs=NULL;
if (conf->createMsubs) {
movieSubs=getSubs(conf, movieNameNoExt, moviePath); // JSON of movie's subs
}
if (movieID==0) {
movieID=getMovieID(conf, movieName);
}
if (imgURL==NULL && conf->getMposter==true && movieID>0) {
imgURL=getMoviePoster(thisThread->conf, movieID);
}
if (imgURL==NULL) { // if still NULL, getMoviePoster didn't work...
imgURL=genImage(conf->AutogenImgResizeMoCmd, conf->dMoFolder, movieName);
/*
// useless on genImage? compressed results seem to be bigger than original
if (conf->compressImgMo) {
imgURL=compressImg(conf->compressImgMoCmd, imgURL, true);
}
*/
}
if (imgURL==NULL) {
mallocMacro(imgURL, 1, "findMovies error");
imgURL[0]='\0';
}
if (movieSubs==NULL) {
mallocMacro(movieSubs, 1, "findMovies error");
movieSubs[0]='\0';
}
printInfo("findMovies info", true, "assembling JSON for \"%s\";\n", movieName);
size_t movieJSONStrSize=strlen("{\"Movie\":\"\",\"ID\":\"\",\"Poster\":\"\",\"File\":\"\", \"Subs\":[]}")+strlen(movieName)+intSize(movieID)+strlen(imgURL)+strlen(movieFile)+strlen(movieSubs)+1;
char *movieJSONStr=NULL;
mallocMacro(movieJSONStr, movieJSONStrSize, "findMovies error");
movieJSONStr[0]='\0';
snprintf(movieJSONStr, movieJSONStrSize, "{\"Movie\":\"%s\",\"ID\":\"%d\",\"Poster\":\"%s\",\"File\":\"%s\",\"Subs\":[%s]}", movieName, movieID, imgURL, movieFile, movieSubs);
addData(thisThread->list, movieJSONStr);
addData(thisThread->list, movieName);
if (temp->next!=NULL) {
thisThread->list=add(thisThread->list, NULL, 0);
}
tryFree(movieNameNoExt);
tryFree(movieName);
tryFree(movieSubs);
tryFree(imgURL);
tryFree(movieJSONStr);
}
} else {
printError("findMovies warning", false, HYEL, "please note, path \"%s\" is empty!\n", fullPath);
freeList(thisThread->list);
}
freeList(movies);
tryFree(fullPath);
return NULL;
}
//fetch movie ID
int getMovieID(progConfig *conf, char *movieName) {
int tmdbID=0;
if (conf->getMposter==true) {
CURL *curl=curl_easy_init();
char *escapedMovieName=curl_easy_escape(curl, movieName, 0);
char *apiOpts="&query=";
size_t tempURLStrSize=strlen(tmdbM_ID)+strlen(conf->TMDBapi)+strlen(apiOpts)+strlen(escapedMovieName)+1;
char *tempURLStr=NULL;
mallocMacro(tempURLStr, tempURLStrSize, "getMovieID error");
tempURLStr[0]='\0';
snprintf(tempURLStr, tempURLStrSize, "%s%s%s%s", tmdbM_ID, conf->TMDBapi, apiOpts, escapedMovieName);
if (tempURLStr!=NULL) {
printInfo("getMovieID info", true, "Searching for TMDB ID for \"%s\", URL: \"%s\";\n", movieName, tempURLStr);
tmdbID=getTmdbID(tempURLStr, conf);
if (tmdbID==0) {
printError("getMovieID warning", false, HYEL, "beware, could not find any ID for \"%s\";\n", movieName);
}
curl_free(escapedMovieName);
curl_easy_cleanup(curl);
} else {
printError("getMovieID error", false, HRED, "could not build URL request string, something went wrong...\n");
}
}
return tmdbID;
}
//fetch movie poster
char *getMoviePoster(progConfig *conf, int tmdb_id) {
char *imgURL=NULL;
size_t posterURLSize=strlen(tmdbSite)+strlen(tmdbM)+intSize(tmdb_id)+strlen(tmdbP)+strlen(conf->TMDBapi)+strlen(tmdbP_Opts)+strlen(conf->prefImgLangM)+2;
char *posterURL=NULL;
mallocMacro(posterURL, posterURLSize, "getMoviePoster error");
posterURL[0]='\0';
snprintf(posterURL, posterURLSize, "%s%s%d%s%s%s,%s", tmdbSite, tmdbM, tmdb_id, tmdbP, conf->TMDBapi, tmdbP_Opts, conf->prefImgLangM);
if (posterURL!=NULL) {
imgURL=getPoster(posterURL, conf, conf->prefImgWidthM, conf->prefImgRatioM, conf->prefImgLangM);
if (imgURL==NULL) {
printError("getMoviePoster error", true, HRED, "failed while using URL '%s';\n", posterURL);
} else {
printInfo("getMoviePoster info", true, "got poster for \"%d\", URL: \"%s\";\n", tmdb_id, imgURL);
if (conf->dMoImg) { // if image should actually be downloaded, otherwise will just link to imgURL
if (checkFolder(conf->dMoFolder, true)==0) {
size_t dlFileStrLen=strlen(imgURL)+strlen(conf->dMoFolder);
char *dlFileName=NULL;
mallocMacro(dlFileName, dlFileStrLen, "getMoviePoster error");
dlFileName[0]='\0';
snprintf(dlFileName, dlFileStrLen, "%s%s", conf->dMoFolder, strrchr(imgURL, '/')+1);
if (dlFile(conf, imgURL, dlFileName)==CURLE_OK) { // downloaded poster!
imgURL=realloc(imgURL, dlFileStrLen+1);
if (imgURL==NULL) {
fatalError_abort("getMoviePoster error", "could not realloc;\nError: %s;\n", strerror(errno));
}
strlcpy(imgURL, dlFileName, dlFileStrLen);
if (conf->compressImgMo) { // compress image
imgURL=compressImg(conf->compressImgMoCmd, imgURL, true);
}
}
tryFree(dlFileName);
}
}
}
tryFree(posterURL);
} else {
printError("getMoviePoster error", false, HRED, "could not build URL request string, something went wrong...\n");
}
return imgURL;
}
// create HTML for movies, spawns a thread for every movie object in JSON calling movieHTML
void createMoviesHTML(progConfig *conf, fileList *list) {
printInfo("createMoviesHTML info", true, "building HTML for movies...\n");
if (list==NULL || list->listSize<1) {
printError("createMoviesHTML warning", false, HYEL, "list was empty!\n");
return;
}
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*list->listSize, "createMoviesHTML error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*list->listSize, "createMoviesHTML error");
int i=0;
for (fileList *temp=list; temp!=NULL; temp=temp->next, i++) {
threadObj[i].conf=conf;
threadObj[i].data=temp->data;
threadObj[i].oldJSON=NULL;
threadObj[i].list=newList();
threadObj[i].id=i;
pthread_create(&threads[i], NULL, movieHTML, (void *) &threadObj[i]);
}
i=0;
fileList *htmlList=newList();
addData(htmlList, MOVIE_HTML_TOP);
for (fileList *temp=list; temp!=NULL; temp=temp->next, i++) {
pthread_join(threads[i], NULL);
for (size_t j=0; j<threadObj[i].list->dataSize; j++) {
addData(htmlList, threadObj[i].list->data[j]);
}
freeList(threadObj[i].list);
}
addData(htmlList, MOVIE_HTML_BOT);
fileListToFile(htmlList, conf->Mhtml, "", "");
tryFree(threadObj);
tryFree(threads);
freeList(htmlList);
}
void *movieHTML(void *threadArg) {
threadStruct *thisThread=threadArg;
progConfig *conf=thisThread->conf;
cJSON *myJSON=cJSON_Parse(thisThread->data[0]);
if (myJSON==NULL) {
printError("movieHTML warning", true, HYEL, " myJSON was NULL!\tThis show's JSON is unparsable!\nJSON dump:\n%s\n", thisThread->data[0]);
return NULL;
}
cJSON *movObj=cJSON_GetObjectItem(myJSON, "Movie");
cJSON *posObj=cJSON_GetObjectItem(myJSON, "Poster");
cJSON *fileObj=cJSON_GetObjectItem(myJSON, "File");
cJSON *mySubs=cJSON_GetObjectItem(myJSON, "Subs");
char *moviePoster=NULL;
char *movieName=NULL;
char *movieFile=NULL;
if (movObj!=NULL && cJSON_GetStringValue(movObj)!=NULL) {
movieName=cJSON_GetStringValue(movObj);
}
if (posObj!=NULL && cJSON_GetStringValue(posObj)!=NULL && strlen(cJSON_GetStringValue(posObj))>1) {
if (checkFolder(cJSON_GetStringValue(posObj), false)==0) {
moviePoster=getRelativePath(conf->Mhtml, cJSON_GetStringValue(posObj));
} else {
fatalError_exit("movieHTML", "could not find \"%s\";\nExiting...\n", cJSON_GetStringValue(posObj));
}
}
if (fileObj!=NULL && cJSON_GetStringValue(fileObj)!=NULL) {
movieFile=getRelativePath(conf->Mhtml, cJSON_GetStringValue(fileObj));
}
if (moviePoster==NULL && movieName!=NULL) {
char *genPath=genImage(thisThread->conf->AutogenImgResizeMoCmd, thisThread->conf->dMoFolder, movieName);
moviePoster=getRelativePath(conf->Mhtml, genPath);
tryFree(genPath);
/*
// useless on genImage? compressed results bigger than original
if (conf->compressImgMo) {
moviePoster=compressImg(conf->compressImgMoCmd, moviePoster, true);
}
*/
}
if (movieName==NULL) {
fatalError_abort("movieHTML error", "movieName==NULL; JSON was:\n%s\n--- END ---\n", cJSON_Print(myJSON));
}
if (movieFile==NULL) {
fatalError_abort("movieHTML error", "movieFile==NULL; JSON was:\n%s\n--- END ---\n", cJSON_Print(myJSON));
}
printInfo("movieHTML info", true, "building HTML for \"%s\";\n", movieName);
size_t tempStrSize=strlen(MOVIE_HTML_VIDEO)+intSize(thisThread->id)*3+strlen(moviePoster)+strlen(movieFile)+strlen(movieName)*2+1;
char *tempStr=NULL;
mallocMacro(tempStr, tempStrSize, "movieHTML error");
snprintf(tempStr, tempStrSize, MOVIE_HTML_VIDEO, thisThread->id, movieName, moviePoster, movieName, thisThread->id, thisThread->id, movieFile);
addData(thisThread->list, tempStr);
cJSON *currSub=NULL;
cJSON_ArrayForEach(currSub, mySubs) {
char *subLang=cJSON_GetStringValue(cJSON_GetObjectItem(currSub, "lang"));
char *subPath=getRelativePath(conf->Mhtml, cJSON_GetStringValue(cJSON_GetObjectItem(currSub, "subFile")));
if (subLang!=NULL && subPath!=NULL) {
tempStrSize=strlen(MOVIE_HTML_SUBS)+strlen(subLang)+strlen(subPath)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, MOVIE_HTML_SUBS, subPath, subLang);
addData(thisThread->list, tempStr);
}
tryFree(subPath);
}
addData(thisThread->list, MOVIE_HTML_VIDEO_BOT);
tryFree(moviePoster);
tryFree(movieFile);
tryFree(tempStr);
cJSON_Delete(myJSON);
return NULL;
}
void *cleanMovies(void *threadArg) {
threadStruct *thisThread=threadArg;
progConfig *conf=thisThread->conf;
if (conf->moDB_str==false || conf->JSON_moDB==NULL) {
printError("cleanMovies warning", false, HYEL, "no movies database to clean!\n");
} else {
printInfo("cleanMovies info", false, "cleaning \"%s\"...\n", conf->dbNameMovie);
cJSON *moviesRef=cJSON_Duplicate(conf->JSON_moDB, true);
cJSON *moviesArray=cJSON_Duplicate(conf->JSON_moDB, true);
cJSON *movie=NULL;
int i=0, numDeleted=0;
cJSON_ArrayForEach(movie, moviesArray) {
if (movie!=NULL && cJSON_GetObjectItem(movie, "File")!=NULL) {
char *tempStr=cJSON_GetStringValue(cJSON_GetObjectItem(movie, "File"));
if (tempStr!=NULL) {
if (access(tempStr, F_OK)==0) {
cJSON *subsArray=cJSON_Duplicate(cJSON_GetObjectItem(movie, "Subs"), true);
int j=0, subsDeleted=0;
cJSON *sub=NULL;
cJSON_ArrayForEach(sub, subsArray) {
char *tempSubStr=cJSON_GetStringValue(cJSON_GetObjectItem(sub, "subFile"));
if (tempSubStr!=NULL) {
if (access(tempSubStr, F_OK)!=0) {
cJSON_DeleteItemFromArray(cJSON_GetObjectItem(cJSON_GetArrayItem(moviesRef, i-numDeleted), "Subs"), j-subsDeleted);
subsDeleted++;
}
}
j++;
}
cJSON_Delete(subsArray);
} else {
cJSON_DeleteItemFromArray(moviesRef, i-numDeleted);
numDeleted++;
}
}
}
i++;
}
cJSON_Delete(moviesArray);
thisThread->oldJSON=moviesRef;
}
return NULL;
}

@ -0,0 +1,21 @@
#pragma once
#include "conf.h"
#include "fileList.h"
#define MOVIE_HTML_TOP "<!DOCTYPE html>\n<html>\n<head>\n<title>cmyflix</title>\n<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">\n<meta name=\"description\" content=\"Daria Rostirolla\">\n<meta name=\"keywords\" content=\"HTML, CSS\">\n<meta name=\"author\" content=\"Daria Rostirolla\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link href=\"css/movie.css\" rel=\"stylesheet\" type=\"text/css\">\n<link rel=\"icon\" type=\"image/png\" href=\"img/favicon.png\">\n</head>\n<body>\n<script type=\"text/javascript\" src=\"js/Mscript.js\"></script><div id=\"wrapper\">"
#define MOVIE_HTML_VIDEO "<div class=\"movieDiv\">\n<input id=\"A%d\" class=\"myBtn\" alt=\"%s\" onclick=\"javascript:showModal(this)\" type=\"image\" src=\"%s\" onload=\"javascript:setAlt(this, '%s')\">\n<div id=\"B%d\" class=\"modal\">\n<div class=\"modal-content\">\n<video id=\"C%d\" class=\"video_player\" controls preload=\"none\">\n<source src=\"%s\" type=\"video/mp4\">"
#define MOVIE_HTML_SUBS "\n<track src=\"%s\" kind=\"subtitles\" label=\"%s\">"
#define MOVIE_HTML_VIDEO_BOT "\n</video>\n<span onclick=\"javascript:hideModal()\" class=\"close\">&times;</span>\n</div>\n</div>\n</div>"
#define MOVIE_HTML_BOT "\n<div id=\"paddingDiv\">\n</div>\n</div>\n</body>\n</html>"
struct fileList *createMoviesDB(progConfig *conf);
void *findMovies(void *threadArg);
void *movieHTML(void *threadArg);
void *cleanMovies(void *threadArg);
void createMoviesHTML(progConfig *conf, fileList *list);
int getMovieID(progConfig *conf, char *movieName);
char *getMoviePoster(progConfig *conf, int tmdb_id);

@ -0,0 +1,14 @@
#pragma once
#include <cjson/cJSON.h>
#include "conf.h"
#include "fileList.h"
#include "main.h"
typedef struct threadStruct{
fileList *list;
progConfig *conf;
progFlags flags;
char **data;
unsigned int id;
cJSON *oldJSON;
} threadStruct;

@ -0,0 +1,972 @@
#include <stdbool.h>
#include <stdlib.h>
#include <pthread.h>
#include <bsd/string.h>
#include <cjson/cJSON.h>
#include <unistd.h>
#include <errno.h>
#include "tvshow.h"
#include "fileList.h"
#include "thread.h"
#include "iofiles.h"
#include "utils.h"
// JSON maker
struct fileList *createTVShowDB(progConfig *conf) {
printInfo("createTVShowDB info", true, "building TV shows' database...\n");
fileList *showFolders=find(conf, conf->TVpath, "", DI_MODE, false);
if (showFolders != NULL ) {
int foldersListSize=showFolders->listSize, i=0;
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*foldersListSize, "createTVShowDB error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*foldersListSize, "createTVShowDB error");
cJSON *tempJSON=NULL;
// open JSON database/set up cJSON
if (conf->tvDB_exists==true) {
tempJSON=cJSON_Duplicate(conf->JSON_tvDB, true);
}
for (fileList *tempList = showFolders; tempList != NULL; tempList = tempList->next, i++) {
threadObj[i].conf=conf;
threadObj[i].data=tempList->data;
threadObj[i].oldJSON=NULL;
threadObj[i].list=NULL;
threadObj[i].id=0;
if (conf->tvDB_exists==true && tempJSON!=NULL) {
char *tvShowName=replaceAll(tempList->data[1], ".", " ");
cJSON *item=NULL;
cJSON_ArrayForEach(item, tempJSON){
if (cJSON_GetObjectItem(item, "show")!=NULL && cJSON_GetStringValue(cJSON_GetObjectItem(item, "show"))!=NULL) {
char *tempStr=cJSON_GetStringValue(cJSON_GetObjectItem(item, "show"));
if (strcmp(tempStr, tvShowName)==0) { // match
threadObj[i].id=parseStrToInt(cJSON_GetStringValue(cJSON_GetObjectItem(item, "ID")));
threadObj[i].oldJSON=cJSON_DetachItemViaPointer(tempJSON, item);
break;
}
} else {
printError("createTVShowDB warning", false, "some errors occured while reading \"%s\", parts of the database will be rebuilt from scratch...\n", conf->dbNameTV);
threadObj[i].oldJSON=NULL;
conf->tvDB_exists=false;
cJSON_Delete(tempJSON);
tempJSON=NULL;
break;
}
}
tryFree(tvShowName);
}
pthread_create(&threads[i], NULL, findSeasons, (void *) &threadObj[i]);
}
fileList *showJSON=NULL;
for (i=0; i<foldersListSize;i++) { // loop through all found tv shows
pthread_join(threads[i], NULL);
showJSON=joinLists(showJSON, threadObj[i].list);
if (threadObj[i].oldJSON!=NULL){
cJSON_Delete(threadObj[i].oldJSON);
}
}
if (tempJSON!=NULL){
cJSON_Delete(tempJSON);
}
tryFree(threads);
tryFree(threadObj);
freeList(showFolders);
// sort shows alphabetically
msortList(&showJSON, 1, true, STRING);
for (fileList *temp=showJSON; temp!=NULL; temp=temp->next) { // remove temp->data[1] (which should be the tv show name), meanwhile temp->data[0] is the whole show JSON
tryFree(temp->data[temp->dataSize-1]);
temp->dataSize--;
}
char *jsonStr=fileListToJSONStr(showJSON);
if (jsonStr!=NULL) {
cJSON_Delete(conf->JSON_tvDB);
conf->JSON_tvDB=cJSON_Parse(jsonStr);
}
tryFree(jsonStr);
return showJSON;
} else {
printError("createTVShowDB warning", false, HYEL, "could not find anything in \"%s\";\n", conf->TVpath);
}
return NULL;
}
void *findSeasons(void *threadArg) { // runs in Show.Name folder and spawns threads in every season folder
threadStruct *thisThread=(threadStruct *) threadArg;
progConfig *conf=thisThread->conf;
size_t lenStr1=strlen(thisThread->data[0]);
size_t lenStr2=strlen(thisThread->data[1]); // thisThread->data[1] name of tv show top folder
char *showPath=NULL;
mallocMacro(showPath, lenStr1+lenStr2+2, "findSeasons error");
strlcpy(showPath, thisThread->data[0], lenStr1+1);
if (showPath[lenStr1 - 1] != '/') {
strlcat(showPath, "/", lenStr1+lenStr2+2);
}
strlcat(showPath, thisThread->data[1], lenStr1+lenStr2+2);
if (thisThread->data[1][lenStr2-1] != '/') {
strlcat(showPath, "/", lenStr1+lenStr2+2);
}
// Find all the seasons of the current tv show
printInfo("findSeasons info", true, "looking for seasons' folders in: \"%s\";\n", showPath);
fileList *seasonsList = find(conf, showPath, "", DI_MODE, false); // get all seasons folders
if (seasonsList!=NULL && seasonsList->data!=NULL) {
bool showHasExtras=false;
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*seasonsList->listSize, "findSeasons error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*seasonsList->listSize, "findSeasons error");
// TV show stuff
int tmdb_id=thisThread->id;
char *imgURL=NULL;
char *tvShowName=replaceAll(thisThread->data[1], ".", " ");
if (tmdb_id==0) {
tmdb_id=getShowID(conf, tvShowName); // get the ID for this show
}
int i=0;
for (fileList *tempList=seasonsList; tempList!=NULL; tempList=tempList->next, i++) { // run thread in every season folder
size_t tempPathSize=strlen(showPath)+strlen(tempList->data[1])+2;
char *tempPath=NULL; // path to season
mallocMacro(tempPath, tempPathSize, "findSeasons error");
strlcpy(tempPath, showPath, tempPathSize);
strlcat(tempPath, tempList->data[1], tempPathSize);
if (tempPath[strlen(tempPath)-1]!='/') {
strlcat(tempPath, "/", tempPathSize);
}
if (strstr(tempPath, conf->TVextraStr)) {
showHasExtras=true;
}
// search for episodes & stuff
threadObj[i].conf=thisThread->conf;
threadObj[i].oldJSON=thisThread->oldJSON;
threadObj[i].list=NULL;
threadObj[i].data=NULL;
mallocMacro(threadObj[i].data, sizeof(char **), "findSeasons error");
size_t tempSize=strlen(tempPath)+1;
threadObj[i].data[0]=NULL;
mallocMacro(threadObj[i].data[0], tempSize, "findSeasons error");
strlcpy(threadObj[i].data[0], tempPath, tempSize);
threadObj[i].id=tmdb_id;
pthread_create(&threads[i], NULL, findEpisodes, (void *) &threadObj[i]);
tryFree(tempPath);
}
// get TV show poster!
if (thisThread->oldJSON!=NULL) {
char *tempStr=cJSON_GetStringValue(cJSON_GetObjectItem(thisThread->oldJSON, "Poster"));
size_t tempStrLen=strlen(tempStr)+1;
if (tempStrLen>3) {
imgURL=NULL;
mallocMacro(imgURL, tempStrLen, "findSeasons error");
strlcpy(imgURL, tempStr, tempStrLen);
}
}
if (imgURL==NULL && thisThread->conf->getTVposter==true && tmdb_id>0) {
imgURL=getShowPoster(thisThread->conf, tmdb_id);
}
if (imgURL==NULL) { // if still NULL, getShowPoster didn't work...
imgURL=genImage(conf->AutogenImgResizeTVCmd, conf->dTVFolder, tvShowName);
/*
// useless on genImage? compressed results bigger than original
if (conf->compressImgTV) {
imgURL=compressImg(conf->compressImgTVCmd, imgURL, true);
}
*/
}
for (int j=0; j<i; j++) {
pthread_join(threads[j], NULL);
thisThread->list=joinLists(thisThread->list, threadObj[j].list);
tryFree(threadObj[j].data[0]);
tryFree(threadObj[j].data);
}
if (thisThread->list!=NULL) {
if (thisThread->list->listSize>1) {
msortList(&thisThread->list, 0, true, INTEGER);
}
size_t numOfSeasons=seasonsList->listSize;
if (showHasExtras) {
numOfSeasons--;
}
if (imgURL==NULL) {
mallocMacro(imgURL, 1, "findSeasons error");
imgURL[0]='\0';
}
size_t showJSONStrSize=strlen("{\"Show\":\"\",\"ID\":\"\",\"Poster\":\"\",\"Seasons\":\"\",\"Episodes\":[],\"Extras\":[]}")+strlen(tvShowName)+intSize(tmdb_id)+strlen(imgURL)+intSize(numOfSeasons)+1;
char *showJSONStr=NULL;
mallocMacro(showJSONStr, showJSONStrSize, "findSeasons error");
showJSONStr[0]='\0';
snprintf(showJSONStr, showJSONStrSize, "{\"Show\":\"%s\",\"ID\":\"%d\",\"Poster\":\"%s\",\"Seasons\":\"%zu\",\"Episodes\":[", tvShowName, tmdb_id, imgURL, numOfSeasons);
i=0;
size_t extrasJSONStrSize=2, j=0;
char *extrasJSONStr=NULL;
mallocMacro(extrasJSONStr, extrasJSONStrSize, "findSeasons error");
extrasJSONStr[0]='\0';
for (fileList *tempList=thisThread->list; tempList!=NULL; tempList=tempList->next) {
if (tempList->dataSize>=2 && tempList->data[1]!=NULL) {
if (strstr(tempList->data[1], conf->TVextraStr)!=NULL) { // check if this list comes from a 'extras season'
for (size_t k=1; k<tempList->dataSize; k++) { // iterate over all files in the 'extras' folder
extrasJSONStrSize+=strlen(tempList->data[k]);
extrasJSONStr=realloc(extrasJSONStr, extrasJSONStrSize);
if (extrasJSONStr==NULL)
fatalError_abort("findSeasons error", "could not realloc;\nError: %s;\n", strerror(errno));
if (j>0) {
extrasJSONStrSize++;
strlcat(extrasJSONStr, ",", extrasJSONStrSize);
}
strlcat(extrasJSONStr, tempList->data[k], extrasJSONStrSize);
j++;
}
} else { //list from a regular season, not extras
for (size_t k=1; k<tempList->dataSize; k++) {
showJSONStrSize+=strlen(tempList->data[k]);
showJSONStr=realloc(showJSONStr, showJSONStrSize);
if (showJSONStr==NULL)
fatalError_abort("findSeasons error", "could not realloc;\nError: %s;\n", strerror(errno));
if (i>0) {
showJSONStrSize++;
strlcat(showJSONStr, ",", showJSONStrSize);
}
strlcat(showJSONStr, tempList->data[k], showJSONStrSize);
i++;
}
}
}
}
char *tempShowJSONStr=NULL;
mallocMacro(tempShowJSONStr, showJSONStrSize, "findSeasons error");
strlcpy(tempShowJSONStr, showJSONStr, showJSONStrSize);
showJSONStr=realloc(showJSONStr, showJSONStrSize+extrasJSONStrSize);
if (showJSONStr==NULL) {
fatalError_abort("findSeasons error", "could not realloc;\nError: %s;\n", strerror(errno));
}
showJSONStr[0]='\0';
snprintf(showJSONStr, showJSONStrSize+extrasJSONStrSize, "%s],\"Extras\":[%s]}", tempShowJSONStr, extrasJSONStr);
freeList(thisThread->list);
thisThread->list=newList();
addData(thisThread->list, showJSONStr);
addData(thisThread->list, tvShowName);
tryFree(threads);
tryFree(threadObj);
freeList(seasonsList);
tryFree(imgURL);
tryFree(showJSONStr);
tryFree(tvShowName);
tryFree(extrasJSONStr);
tryFree(tempShowJSONStr);
} else {
printError("findSeasons warning", false, HYEL, "please note, could not find any \".%s\" in path \"%s\"\n", videoExt, showPath);
}
} else {
printError("findSeasons warning", false, HYEL, "please note, path \"%s\" is empty!\n", showPath);
}
tryFree(showPath);
return NULL;
}
void *findEpisodes(void *threadArg) { // find files of 'this' season
threadStruct *thisThread = (threadStruct *) threadArg;
fileList *foundFiles=NULL;
ioMode mode=TV_MODE | FI_MODE;
if (strstr(thisThread->data[0], thisThread->conf->TVextraStr)!=NULL) {
mode=FI_MODE;
}
printInfo("findEpisodes info", true, "looking for episodes in: \"%s\";\n", thisThread->data[0]);
foundFiles=find(thisThread->conf, thisThread->data[0], videoExt, mode, false); // search for video files in this folder
if (foundFiles==NULL) {
thisThread->list=NULL;
} else {
size_t thisShowSeason=9999999; // "No season" as start value, because of sorting
if ((mode & TV_MODE)!=0) { // if mode has TV_MODE bit set then we are NOT in the folder of the extras
msortList(&foundFiles, 5, true, INTEGER); // sort list by data[5] ( episode number )
if (foundFiles->dataSize>4) { // getting season & not in Season.Extras
thisShowSeason=parseStrToInt(foundFiles->data[4]);
} else { // could not get current season from filename, trying by getting it from folder name
if (foundFiles->dataSize>1) {
// this only works if folder is named using the 'Something.1' format
char *tempStrPtr=strrchr(foundFiles->data[1], '.');
size_t tempStrPtrLen=strlen(tempStrPtr);
char *tempStr=NULL;
mallocMacro(tempStr, tempStrPtrLen, "findEpisodes error");
tempStr[0]='\0';
if (tempStrPtr[tempStrPtrLen-1]=='/') {
tempStrPtrLen--;
}
strlcpy(tempStr, tempStrPtr+1, tempStrPtrLen);
thisShowSeason=parseStrToInt(tempStr);
}
}
}
fileList *jsonObjList=newList();
unsigned int showId=thisThread->id;
size_t size=intSize(thisShowSeason)+1;
char *tempStr=NULL;
mallocMacro(tempStr, size, "findEpisodes error");
tempStr[0]='\0';
intToStr(tempStr, thisShowSeason);
addData(jsonObjList, tempStr);
for (fileList *temp=foundFiles; temp!=NULL; temp=temp->next) { //iterate through episodes
char *epNum=NULL, *seNum=NULL, *epName=NULL, *epSubs=NULL;
bool seasonExtra=false;
if (thisThread->conf->tvDB_exists && strstr(thisThread->conf->tvDB_str, temp->data[0])) {
if (thisThread->oldJSON!=NULL){
cJSON *JSONcopy=cJSON_Duplicate(thisThread->oldJSON, true);
cJSON *episodesArray=cJSON_GetObjectItem(JSONcopy, "episodes");
cJSON *item=NULL;
if (episodesArray!=NULL) {
cJSON_ArrayForEach(item, episodesArray) {
if (item!=NULL) {
cJSON *obj=cJSON_GetObjectItem(item, "File");
if (obj!=NULL) {
char *fileStr=cJSON_GetStringValue(obj);
if (fileStr!=NULL && strcmp(fileStr, temp->data[0])==0) { //match
item=cJSON_DetachItemViaPointer(episodesArray, item);
char *tempSeNum=cJSON_GetStringValue(cJSON_GetObjectItem(item, "Season"));
char *tempEpNum=cJSON_GetStringValue(cJSON_GetObjectItem(item, "Episode"));
char *tempEpName=cJSON_GetStringValue(cJSON_GetObjectItem(item, "Title"));
size_t tempSize=0;
tempSize=strlen(tempSeNum)+1;
if (tempSize>1) {
seNum=NULL;
mallocMacro(seNum, tempSize, "findEpisodes error");
strlcpy(seNum, tempSeNum, tempSize);
}
tempSize=strlen(tempEpNum)+1;
if (tempSize>1) {
epNum=NULL;
mallocMacro(epNum, tempSize, "findEpisodes error");
strlcpy(epNum, tempEpNum, tempSize);
}
tempSize=strlen(tempEpName)+1;
if (tempSize>1) {
epName=NULL;
mallocMacro(epName, tempSize, "findEpisodes error");
strlcpy(epName, tempEpName, tempSize);
}
cJSON_Delete(item);
break;
}
}
}
}
cJSON_Delete(JSONcopy);
}
//} else {
// printError("File \"%s\" found in tvDB_str but oldJSON==NULL\n", temp->data[0]);
}
}
if (temp->data!=NULL && strstr(temp->data[0], thisThread->conf->TVextraStr)!=NULL) {
seasonExtra=true;
epName=removeExtension(temp->data[2]); // episode name is filename without extension
} else { // get episodes' names
/* temp->data 'format'
* temp->data[0] full path to file ( ex: ../TV/Show/Season/Show.S01E01.TheOneThatIsAnExample.mp4 )
* temp->data[1] path to file's folder ( ex: ../TV/Show/Season/ )
* temp->data[2] filename ( ex: Show.S01E01.TheOneThatIsAnExample.mp4 )
now filename is split into regex groups... Default would be something like the following
* temp->data[3] Show
* temp->data[4] 01
* temp->data[5] 01
* temp->data[6] TheOneThatIsAnExample.mp4
*/
if (temp->dataSize > 5 ) { // use regexTVgroups instead of hard coded number? See temp->data 'format'
if (seNum==NULL) {
size_t tempStrLen=strlen(temp->data[4])+1;
seNum=NULL;
mallocMacro(seNum, tempStrLen, "findEpisodes error");
strlcpy(seNum, temp->data[4], tempStrLen);
}
if (epNum==NULL) {
size_t tempStrLen=strlen(temp->data[5])+1;
epNum=NULL;
mallocMacro(epNum, tempStrLen, "findEpisodes error");
strlcpy(epNum, temp->data[5], tempStrLen);
}
if (epNum!=NULL && seNum!=NULL && epName==NULL && thisThread->conf->getEpisodeName==true && showId!=0 ) {
epName=getEpisodeName(thisThread->conf, showId, seNum, epNum, thisThread->conf->TMDBapi);
}
} else { // dataSize got weird, shouldn't really happen?
if (temp->dataSize>0){
printError("findEpisodes warning", false, HYEL, "file \"%s\" has weird dataSize: %d;\n", temp->data[0], temp->dataSize);
}
}
}
if (thisThread->conf->createTVsubs) { // search for subs, convert srt to vtt - no matter if already in DB or not
if (temp->dataSize>2) {
epSubs=getSubs(thisThread->conf, temp->data[2], thisThread->data[0]);
}
}
if (epName==NULL) {
if (temp->dataSize>5 && seasonExtra==false) {
if (strcmp(temp->data[6], videoExt)==0) {
epName=removeExtension(temp->data[2]);
} else {
epName=removeExtension(temp->data[6]);
}
} else {
epName=removeExtension(temp->data[2]);
}
}
if (epSubs==NULL) {
epSubs=NULL;
mallocMacro(epSubs, 1, "findEpisodes error");
epSubs[0]='\0';
}
if (seNum==NULL) {
seNum=NULL;
mallocMacro(seNum, 2, "findEpisodes error");
seNum[0]='0';
seNum[1]='\0';
}
if (epNum==NULL) {
epNum=NULL;
mallocMacro(epNum, 2, "findEpisodes error");
epNum[0]='0';
epNum[1]='\0';
}
char *epJSON=NULL;
if (seasonExtra) {
size_t epJSONStrSize=strlen("{\"Title\":\"\",\"File\":\"\",\"Subs\":[]}")+strlen(seNum)+strlen(epNum)+strlen(epName)+strlen(temp->data[0])+strlen(epSubs)+1;
epJSON=NULL;
mallocMacro(epJSON, epJSONStrSize, "findEpisodes error");
epJSON[0]='\0';
snprintf(epJSON, epJSONStrSize, "{\"Title\":\"%s\",\"File\":\"%s\",\"Subs\":[%s]}", epName, temp->data[0], epSubs);
addData(jsonObjList, epJSON);
} else if (temp->dataSize>0) {
size_t epJSONStrSize=strlen("{\"Season\":\"\",\"Episode\":\"\",\"Title\":\"\",\"File\":\"\",\"Subs\":[]}")+strlen(seNum)+strlen(epNum)+strlen(epName)+strlen(temp->data[0])+strlen(epSubs)+1;
epJSON=NULL;
mallocMacro(epJSON, epJSONStrSize, "findEpisodes error");
epJSON[0]='\0';
snprintf(epJSON, epJSONStrSize, "{\"Season\":\"%s\",\"Episode\":\"%s\",\"Title\":\"%s\",\"File\":\"%s\",\"Subs\":[%s]}", seNum, epNum, epName, temp->data[0], epSubs);
addData(jsonObjList, epJSON);
}
tryFree(epJSON);
tryFree(epSubs);
tryFree(epName);
tryFree(epNum);
tryFree(seNum);
}
tryFree(tempStr);
thisThread->list=jsonObjList;
}
freeList(foundFiles);
return NULL;
}
char *getShowPoster(progConfig *conf, unsigned int tmdb_id) {
char *imgURL=NULL;
size_t posterURLSize=strlen(tmdbSite)+strlen(tmdbTV)+intSize(tmdb_id)+strlen(tmdbP)+strlen(conf->TMDBapi)+strlen(tmdbP_Opts)+strlen(conf->prefImgLangTV)+2;
char *posterURL=NULL;
mallocMacro(posterURL, posterURLSize, "getShowPoster error");
posterURL[0]='\0';
snprintf(posterURL, posterURLSize, "%s%s%u%s%s%s,%s", tmdbSite, tmdbTV, tmdb_id, tmdbP, conf->TMDBapi, tmdbP_Opts, conf->prefImgLangTV);
imgURL=getPoster(posterURL, conf, conf->prefImgWidthTV, conf->prefImgRatioTV, conf->prefImgLangTV);
printInfo("getShowPoster info", true, "got poster for \"%d\", URL: \"%s\";\n", tmdb_id, imgURL);
if (imgURL!=NULL && conf->dTVImg) { // if image should actually be downloaded, otherwise will just link to imgURL
if (checkFolder(conf->dTVFolder, true)==0) {
size_t dlFileStrLen=strlen(imgURL)+strlen(conf->dTVFolder);
char *dlFileName=NULL;
mallocMacro(dlFileName, dlFileStrLen, "getShowPoster error");
dlFileName[0]='\0';
snprintf(dlFileName, dlFileStrLen, "%s%s", conf->dTVFolder, strrchr(imgURL, '/')+1);
if (dlFile(conf, imgURL, dlFileName)==CURLE_OK) { // downloaded poster!
imgURL=realloc(imgURL, dlFileStrLen+1);
if (imgURL==NULL)
fatalError_abort("getShowPoster error", "could not realloc;\nError: %s;\n", strerror(errno));
strlcpy(imgURL, dlFileName, dlFileStrLen);
if (conf->compressImgTV) {
imgURL=compressImg(conf->compressImgTVCmd, imgURL, true);
}
}
tryFree(dlFileName);
}
}
tryFree(posterURL);
return imgURL;
}
char *getEpisodeName(progConfig *conf, unsigned int showId, char *seNum, char *epNum, char *TMDBapi) {
char *epName=NULL;
char *season="/season/";
char *episode="/episode/";
char *apiOpts="?api_key=";
size_t tempStrSize=strlen(tmdbSite)+strlen(tmdbTV)+intSize(showId)+strlen(season)+strlen(seNum)+strlen(episode)+strlen(epNum)+strlen(apiOpts)+strlen(TMDBapi)+1;
char *tempStr=NULL;
mallocMacro(tempStr, tempStrSize, "getEpisodeName error");
tempStr[0]='\0';
snprintf(tempStr, tempStrSize, "%s%s%u%s%s%s%s%s%s", tmdbSite, tmdbTV, showId, season, seNum, episode, epNum, apiOpts, TMDBapi);
memBlock *mem=initBlock();
printInfo("getEpisodeName info", true, "finding episode name for show: \"%d\", season:\"%s\", episode: \"%s\", URL: \"%s\";\n", showId, seNum, epNum, tempStr);
getRequest(conf, tempStr, mem, curlMemCb);
cJSON *json_root=cJSON_Parse(mem->memory);
if (json_root!=NULL) {
cJSON *json_name=cJSON_DetachItemFromObject(json_root, "name");
if (json_name!=NULL){
char *tempEpName=cJSON_Print(json_name);
if (tempEpName!=NULL) {
// remove quotation marks at the beginning and end of string
size_t tempEpNameSize=strlen(tempEpName);
epName=NULL;
mallocMacro(epName, tempEpNameSize+1, "getEpisodeName error");
strlcpy(epName, tempEpName+1, tempEpNameSize-1);
}
tryFree(tempEpName);
} else {
if (cJSON_GetNumberValue(cJSON_GetObjectItem(json_root, "status_code"))!=34) {
printError("getEpisodeName warning", true, HYEL, " json_name==NULL - JSON received was:\n");
char *cJSONstr=cJSON_Print(json_root);
printError("", true, HBLU, cJSONstr);
printError("", true, HYEL, "\nrequest was: '%s%s%s';", HBLU, tempStr, HYEL);
printError("", true, HYEL, "\nEND;\n%s", COLOR_RESET);
tryFree(cJSONstr);
}
}
cJSON_Delete(json_name);
} else {
printError("getEpisodeName warning", true, HYEL, " json_root==NULL\n");
}
tryFree(tempStr);
cJSON_Delete(json_root);
freeBlock(mem);
char *fixedEpName=replaceAll(epName, "\\\"", "");
tryFree(epName);
return fixedEpName;
}
void createShowsHTML(progConfig *conf, fileList *list) {
printInfo("createShowsHTML info", true, "building HTML for TV shows...\n");
if (list==NULL || list->listSize<2) {
fatalError_abort("createShowsHTML error", "list was NULL\n");
}
if (checkFolder(conf->TVhtml, true)==-1) {
fatalError_exit("createShowsHTML", "could not find \"%s\";\nExiting...\n", conf->TVhtml);
}
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*list->listSize, "createShowsHTML error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*list->listSize, "createShowsHTML error");
size_t i=0;
for (fileList *temp=list; temp!=NULL; temp=temp->next) {
threadObj[i].conf=conf;
threadObj[i].data=temp->data;
threadObj[i].oldJSON=NULL;
threadObj[i].list=newList();
threadObj[i].id=i;
pthread_create(&threads[i], NULL, showHTML, (void *) &threadObj[i]);
i++;
}
i=0;
fileList *htmlList=newList();
addData(htmlList, TV_HTML_TOP);
char *htmlStr=NULL;
for (fileList *temp=list; temp!=NULL; temp=temp->next) {
pthread_join(threads[i], NULL);
char *showFile=NULL;
char *showPoster=NULL;
if (checkFolder(threadObj[i].list->data[0], false)==0) {
showFile=getRelativePath(conf->TVhtml, threadObj[i].list->data[0]);
} else {
fatalError_exit("createShowsHTML", "could not find \"%s\";\nExiting...\n", threadObj[i].list->data[0]);
}
if (checkFolder(threadObj[i].list->data[1], false)==0) {
showPoster=getRelativePath(conf->TVhtml, threadObj[i].list->data[1]);
} else {
fatalError_exit("createShowsHTML", "could not find \"%s\";\nExiting...\n", threadObj[i].list->data[1]);
}
if (showPoster==NULL) {
showPoster=NULL;
mallocMacro(showPoster, 1, "createShowsHTML error");
showPoster[0]='\0';
}
char *showName=threadObj[i].list->data[2];
size_t htmlStrSize=strlen(TV_HTML_FRAME)+strlen(showFile)+strlen(showPoster)+strlen(showName)*2+intSize(i)+1;
htmlStr=realloc(htmlStr, htmlStrSize);
if (htmlStr==NULL) {
fatalError_abort("createShowsHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(htmlStr, htmlStrSize, TV_HTML_FRAME, i, showName, showFile, showPoster, showName, i, i, i);
addData(htmlList, htmlStr);
freeList(threadObj[i].list);
tryFree(showFile);
tryFree(showPoster);
i++;
}
addData(htmlList, TV_HTML_BOT);
fileListToFile(htmlList, conf->TVhtml, "", "");
tryFree(threadObj);
tryFree(threads);
tryFree(htmlStr);
freeList(htmlList);
}
void *showHTML(void *threadArg) {
threadStruct *thisThread=threadArg;
fileList *this_show=newList();
cJSON *myJSON=cJSON_Parse(thisThread->data[0]);
if (myJSON==NULL) {
printError("showHTML warning", false, HYEL, " myJSON was NULL!\tThis show's JSON is unparsable!\nJSON dump:\n%s\n", thisThread->data[0]);
return NULL;
}
cJSON *showObj=cJSON_GetObjectItem(myJSON, "Show");
cJSON *posObj=cJSON_GetObjectItem(myJSON, "Poster");
char *showPoster=NULL;
char *showName=NULL;
if (posObj!=NULL && cJSON_GetStringValue(posObj)!=NULL) {
showPoster=cJSON_GetStringValue(posObj);
}
if (showObj!=NULL && cJSON_GetStringValue(showObj)!=NULL) {
showName=cJSON_GetStringValue(showObj);
}
if (showPoster==NULL) {
showPoster=genImage(thisThread->conf->AutogenImgResizeTVCmd, thisThread->conf->dTVFolder, showName);
/*
// useless on genImage? compressed results bigger than original
if (thisThread->conf->compressImgTV) {
showPoster=compressImg(thisThread->conf->compressImgTVCmd, showPoster, true);
}
*/
}
if (showName==NULL) {
fatalError_abort("showHTML error", "showName==NULL; JSON was:\n%s\n--- END ---\n", cJSON_Print(myJSON));
}
char *numOfSeasonsStr=cJSON_GetStringValue(cJSON_GetObjectItem(myJSON, "Seasons"));
int myNumSeasons=0;
if (numOfSeasonsStr!=NULL) {
myNumSeasons=parseStrToInt(numOfSeasonsStr);
}
int uuid=thisThread->id;
cJSON *episodesArray=cJSON_GetObjectItem(myJSON, "Episodes");
cJSON *extrasArray=cJSON_GetObjectItem(myJSON, "Extras");
if (episodesArray==NULL || extrasArray==NULL) {
fatalError_abort("showHTML error", " episodesArray or extrasArray were equal to NULL; JSON was:\n%s\n--- END ---\n ", cJSON_Print(myJSON));
}
printInfo("showHTML info", true, "building HTML for \"%s\";\n", showName);
cJSON *episode=NULL;
addData(this_show, SHOW_HTML_TOP);
int currSeason=0;
int uuidEpisode=0;
size_t tempStrSize=strlen(SHOW_HTML_SEL)+intSize(uuid)+1; //'<select>' HTML size+uuid size+NULL
char *tempStr=NULL;
mallocMacro(tempStr, tempStrSize, "showHTML error");
tempStr[0]='\0';
snprintf(tempStr, tempStrSize, SHOW_HTML_SEL, uuid);
addData(this_show, tempStr);
while (currSeason<myNumSeasons) {
currSeason++;
tempStrSize=strlen(SHOW_HTML_OPT_SEASON)+intSize(currSeason)+intSize(currSeason)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("showHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_OPT_SEASON, currSeason, currSeason);
addData(this_show, tempStr);
}
if (extrasArray!=NULL && cJSON_GetArraySize(extrasArray)>0) {
currSeason++;
tempStrSize=strlen(SHOW_HTML_OPT_EXTRAS)+intSize(currSeason)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("showHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_OPT_EXTRAS, currSeason);
addData(this_show, tempStr);
}
addData(this_show, "\n</select>");
currSeason=0;
cJSON_ArrayForEach(episode, episodesArray) {
episodeHTML(this_show, thisThread->conf, episode, &currSeason, &uuid, &uuidEpisode);
}
addData(this_show, "\n</ul>");
if (extrasArray!=NULL && cJSON_GetArraySize(extrasArray)>0) {
currSeason++;
tempStrSize=intSize(uuid)+intSize(currSeason)+strlen(SHOW_HTML_UL)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL)
fatalError_abort("showHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
snprintf(tempStr, tempStrSize, SHOW_HTML_UL, uuid, currSeason);
addData(this_show, tempStr);
cJSON *extra=NULL;
cJSON_ArrayForEach(extra, extrasArray) {
episodeHTML(this_show, thisThread->conf, extra, &currSeason, &uuid, &uuidEpisode);
}
addData(this_show, "\n</ul>");
}
tempStrSize=intSize(uuid)+strlen(SHOW_HTML_BOT)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL)
fatalError_abort("showHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
snprintf(tempStr, tempStrSize, SHOW_HTML_BOT, uuid);
addData(this_show, tempStr);
char *fileName=replaceAll(showName, " ", "");
tempStrSize=strlen(fileName)+strlen(thisThread->conf->showHTMLFolder)+16;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("showHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
if (thisThread->conf->showHTMLFolder[strlen(thisThread->conf->showHTMLFolder)-1]=='/') {
snprintf(tempStr, tempStrSize, "%sTV%s.html", thisThread->conf->showHTMLFolder, fileName);
} else {
snprintf(tempStr, tempStrSize, "%s/TV%s.html", thisThread->conf->showHTMLFolder, fileName);
}
if (checkFolder(thisThread->conf->showHTMLFolder, true)==0) {
fileListToFile(this_show, tempStr, NULL, NULL);
addData(thisThread->list, tempStr);
addData(thisThread->list, showPoster);
addData(thisThread->list, fileName);
}
if (posObj==NULL || cJSON_GetStringValue(posObj)==NULL) {
tryFree(showPoster);
}
tryFree(fileName);
tryFree(tempStr);
cJSON_Delete(myJSON);
freeList(this_show);
return NULL;
}
void episodeHTML(fileList *this_show, progConfig *conf, cJSON *episode, int *currSeason, int *uuid, int *uuidEpisode) {
int this_seasonNum=0;
cJSON *jsonSeason=cJSON_GetObjectItem(episode, "Season");
if (jsonSeason!=NULL) {
this_seasonNum=parseStrToInt(cJSON_GetStringValue(jsonSeason));
}
char *this_episodeName=cJSON_GetStringValue(cJSON_GetObjectItem(episode, "Title"));
char *this_file=getRelativePath(conf->TVhtml, cJSON_GetStringValue(cJSON_GetObjectItem(episode, "File")));
cJSON *this_subs=cJSON_GetObjectItem(episode, "Subs");
size_t tempStrSize=0;
char *tempStr=NULL;
if (this_seasonNum>*currSeason) {
if (*currSeason>0) { // new season, so close prev season list
addData(this_show, "\n</ul>\n");
}
(*currSeason)++;
tempStrSize=intSize(*uuid)+intSize(*currSeason)+strlen(SHOW_HTML_UL)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_UL, *uuid, *currSeason);
addData(this_show, tempStr);
}
tempStrSize=intSize(*uuid)+intSize(*uuidEpisode)+strlen(this_episodeName)+strlen(SHOW_HTML_LI)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_LI, *uuid, *uuidEpisode, this_episodeName);
addData(this_show, tempStr);
tempStrSize=intSize(*uuid)+intSize(*uuidEpisode)+strlen(SHOW_HTML_DIV)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_DIV, *uuid, *uuidEpisode);
addData(this_show, tempStr);
tempStrSize=strlen(this_episodeName)+strlen(SHOW_HTML_SPAN)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_SPAN, this_episodeName);
addData(this_show, tempStr);
tempStrSize=intSize(*uuid)+intSize(*uuidEpisode)+strlen(this_file)+strlen(SHOW_HTML_VIDEO)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_VIDEO, *uuid, *uuidEpisode, this_file);
addData(this_show, tempStr);
cJSON *currSub=NULL;
cJSON_ArrayForEach(currSub, this_subs) {
char *subLang=cJSON_GetStringValue(cJSON_GetObjectItem(currSub, "lang"));
char *subPath=getRelativePath(conf->TVhtml, cJSON_GetStringValue(cJSON_GetObjectItem(currSub, "subFile")));
if (subLang!=NULL && subPath!=NULL) {
tempStrSize=strlen(SHOW_HTML_SUBS)+strlen(subLang)+strlen(subPath)+1;
tempStr=realloc(tempStr, tempStrSize);
if (tempStr==NULL) {
fatalError_abort("episodeHTML error", "could not realloc;\nError: %s;\n", strerror(errno));
}
snprintf(tempStr, tempStrSize, SHOW_HTML_SUBS, subPath, subLang);
addData(this_show, tempStr);
}
tryFree(subPath);
}
addData(this_show, SHOW_HTML_CMD);
(*uuidEpisode)++;
tryFree(tempStr);
tryFree(this_file);
}
void *cleanTV(void *threadArg) {
threadStruct *thisThread=threadArg;
progConfig *conf=thisThread->conf;
if (conf->tvDB_exists==false || conf->JSON_tvDB==NULL) {
printError("cleanTV warning", false, HYEL, "no TV database to clean!\n");
} else {
printInfo("cleanTV info", false, "cleaning \"%s\"...\n", conf->dbNameTV);
cJSON *tempJSON=cJSON_Duplicate(conf->JSON_tvDB, true);
int jsonArrSize=cJSON_GetArraySize(tempJSON);
pthread_t *threads=NULL;
mallocMacro(threads, sizeof(pthread_t)*jsonArrSize, "cleanTV error");
threadStruct *threadObj=NULL;
mallocMacro(threadObj, sizeof(threadStruct)*jsonArrSize, "cleanTV error");
cJSON *show=NULL;
int i=0;
cJSON_ArrayForEach(show, tempJSON) {
threadObj[i].conf=conf;
threadObj[i].oldJSON=cJSON_Duplicate(show, true);
pthread_create(&threads[i], NULL, cleanShow, (void *) &threadObj[i]);
i++;
}
cJSON_Delete(tempJSON);
int numThreads=i;
cJSON *newJSON=cJSON_CreateArray();
for (i=0; i<numThreads; i++) {
pthread_join(threads[i], NULL);
cJSON_AddItemToArray(newJSON, threadObj[i].oldJSON);
}
thisThread->oldJSON=cJSON_Duplicate(newJSON, true);
cJSON_Delete(newJSON);
tryFree(threads);
tryFree(threadObj);
return NULL;
}
return NULL;
}
void *cleanShow(void *threadArg) {
threadStruct *thisThread=threadArg;
cJSON *show=thisThread->oldJSON;
if (show!=NULL && cJSON_GetObjectItem(show, "Episodes")!=NULL) {
cJSON *episodesArray=cJSON_Duplicate(cJSON_GetObjectItem(show, "Episodes"), true);
cJSON *episode=NULL;
int i=0, numDeleted=0;
cJSON_ArrayForEach(episode, episodesArray) {
if (episode!=NULL && cJSON_GetObjectItem(episode, "File")!=NULL) {
char *tempStr=cJSON_GetStringValue(cJSON_GetObjectItem(episode, "File"));
if (tempStr!=NULL) {
if (access(tempStr, F_OK)==0) {
cJSON *subsArray=cJSON_Duplicate(cJSON_GetObjectItem(episode, "Subs"), true);
int j=0, subsDeleted=0;
cJSON *sub=NULL;
cJSON_ArrayForEach(sub, subsArray) {
char *tempSubStr=cJSON_GetStringValue(cJSON_GetObjectItem(sub, "subFile"));
if (tempSubStr!=NULL) {
if (access(tempSubStr, F_OK)!=0) {
cJSON *tempSubs=cJSON_GetObjectItem(cJSON_GetArrayItem(cJSON_GetObjectItem(show, "Episodes"), i-numDeleted), "Subs");
cJSON_DeleteItemFromArray(tempSubs, j-subsDeleted);
subsDeleted++;
}
}
j++;
}
cJSON_Delete(subsArray);
} else {
cJSON_DeleteItemFromArray(cJSON_GetObjectItem(show, "Episodes"), i-numDeleted);
numDeleted++;
}
}
}
i++;
}
cJSON_Delete(episodesArray);
}
return NULL;
}
int getShowID(progConfig *conf, char *tvShowName) {
int tmdbID=0;
if (conf->getTVposter || conf->getEpisodeName) { // if poster needed -> find out tmdb_id
CURL *curl=curl_easy_init();
char *escapedTVShowName=curl_easy_escape(curl, tvShowName, 0);
char *apiOpts="&api_key=";
size_t tempURLStrSize=strlen(tmdbTV_ID)+strlen(escapedTVShowName)+strlen(apiOpts)+strlen(conf->TMDBapi)+1;
char *tempURLStr=NULL;
mallocMacro(tempURLStr, tempURLStrSize, "getShowID error");
tempURLStr[0]='\0';
snprintf(tempURLStr, tempURLStrSize, "%s%s%s%s", tmdbTV_ID, escapedTVShowName, apiOpts, conf->TMDBapi);
printInfo("getShowID info", true, "Searching for TMDB ID for \"%s\", URL: \"%s\";\n", tvShowName, tempURLStr);
tmdbID=getTmdbID(tempURLStr, conf);
if (tmdbID==0) {
printError("getShowID warning", false, HYEL, "beware, could not find any ID for \"%s\";\n", tvShowName);
tmdbID=-1;
}
curl_free(escapedTVShowName);
curl_easy_cleanup(curl);
}
return tmdbID;
}

@ -0,0 +1,46 @@
#pragma once
#include "conf.h"
#include "fileList.h"
#define TV_HTML_TOP "<!DOCTYPE html>\n<html>\n<head>\n<title>cmyflix</title>\n<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">\n<meta name=\"description\" content=\"Daria Rostirolla\">\n<meta name=\"keywords\" content=\"HTML, CSS\">\n<meta name=\"author\" content=\"Daria Rostirolla\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link href=\"css/tv.css\" rel=\"stylesheet\" type=\"text/css\">\n<link rel=\"icon\" type=\"image/png\" href=\"img/favicon.png\">\n</head>\n<body>\n<script type=\"text/javascript\" src=\"js/mainTVScript.js\"></script>\n<div id=\"wrapper\">\n"
#define TV_HTML_FRAME "<div class=\"showDiv\">\n<input id=\"A%zu\" class=\"myBtn\" alt=\"%s\" onclick=\"javascript:setFrame(this, \'%s\' )\" type=\"image\" src=\"%s\" onload=\"javascript:setAlt(this, \'%s\')\">\n<div id=\"B%zu\" class=\"modal\">\n<div id=\"frameDiv%zu\" class=\"modal-content\">\n<iframe id=\"IN%zu\" src=\"\" frameborder=\"0\" onload=\"javascript:resizeFrame(this)\" allowfullscreen></iframe>\n</div>\n</div>\n</div>\n"
#define TV_HTML_BOT "\n<div id=\"paddingDiv\">\n</div>\n</div>\n</body>\n</html>"
#define SHOW_HTML_TOP "<!DOCTYPE html><html><head><title>cmyflix</title><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"><meta name=\"description\" content=\"Daria Rostirolla\"><meta name=\"keywords\" content=\"HTML, CSS\"><meta name=\"author\" content=\"Daria Rostirolla\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link href=\"../css/tv.css\" rel=\"stylesheet\" type=\"text/css\"><link rel=\"icon\" type=\"image/png\" href=\"../img/favicon.png\"></head><body>\n<span onclick=\"javascript:hideModal()\" class=\"close\">&times;</span>\n"
#define SHOW_HTML_CMD "\n</video>\n<div class=\"nextEpDiv\">\n<input class=\"nextEpButton\" onclick=\"javascript:resetPlayer()\" type=\"button\" value=\"Reset Player\">\n<input class=\"prevEpButton\" onclick=\"javascript:prevEp()\" type=\"button\" value=\"Prev episode\" >\n<input class=\"nextEpButton\" onclick=\"javascript:nextEp()\" type=\"button\" value=\"Next episode\">\n<label class=\"autoButtonLabel\">\n<input class=\"autoButton\" onclick=\"javascript:autoSwitch()\" type=\"checkbox\" value=\"Automatic\">Automatic</label>\n</div>\n</div>\n</div>\n</li>"
#define SHOW_HTML_SEL "<select id=\"selector%d_\" onchange=\"javascript:changeSeason(this)\" class=\"showSelect\">"
#define SHOW_HTML_OPT_SEASON "\n<option value=\"%d\">Season %d</option>"
#define SHOW_HTML_OPT_EXTRAS "\n<option value=\"%d\">Extras</option>"
#define SHOW_HTML_UL "\n<ul id=\"C%d_%d\" class=\"showEpUl\">"
#define SHOW_HTML_LI "\n<li>\n<input id=\"D%d_%d\" class=\"epButton\" onclick=\"javascript:showVideoModal(this)\" type=\"button\" value=\"%s\">\n"
#define SHOW_HTML_DIV "<div id=\"E%d_%d\" class=\"modal\">\n<div class=\"modal-content\">"
#define SHOW_HTML_SPAN "<span onclick=\"javascript:hideVideoModal()\" class=\"close\">&times;</span>\n<p id=\"epTitle\">%s</p>"
#define SHOW_HTML_VIDEO "\n<video id=\"F%d_%d\" class=\"video_player\" controls preload=\"none\" onplaying=\"javascript:rezHandler()\">\n<source src=\"../%s\" type=\"video/mp4\">"
#define SHOW_HTML_SUBS "\n<track src=\"../%s\" kind=\"subtitles\" label=\"%s\">"
#define SHOW_HTML_BOT "\n<script type=\"text/javascript\" src=\"../js/TVScript.js\" onload=\"javascript:showModal('selector%d_')\"></script></body></html>"
struct fileList *createTVShowDB(progConfig *conf);
void *findSeasons(void *threadArg);
void *findEpisodes(void *threadArg);
void createShowsHTML(progConfig *conf, fileList *list);
void *showHTML(void *threadArg);
void *cleanTV(void *threadArg);
void *cleanShow(void *threadArg);
void episodeHTML(fileList *this_show, progConfig *conf, cJSON *episode, int *currSeason, int *uuid, int *uuidEpisode);
char *getShowPoster(progConfig *conf, unsigned int tmdb_id);
char *getEpisodeName(progConfig *conf, unsigned int showId, char *seNum, char *epNum, char *TMDBapi);
int getShowID(progConfig *conf, char *tvShowName);

@ -0,0 +1,985 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>
#include <bsd/string.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <regex.h>
#include <ctype.h>
#include <libgen.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libgen.h>
#include "movies.h"
#include "tvshow.h"
#include "utils.h"
#include "iofiles.h"
#include "fileList.h"
#include "cwalk.h"
extern unsigned int PRINT_MODE;
/* PRINT_MODE:
0=default mode, (warnings, minimal progress messages)
1=verbose mode (add function in error/warnings, additional progress messages),
2=quiet mode (print only warnings/errors (no progress messages)),
3=quieter mode (print only errors (no progress messages)),
4=quietest mode (print nothing) */
extern FILE *LOGFILE;
extern pthread_mutex_t *mutex_stdout;
extern struct timeval timeProgStart;
// reset colors to defaults for stdout and stderr
void resetSTDColors() {
if (LOGFILE==NULL) {
while (pthread_mutex_trylock(mutex_stdout)!=0) {
msleep(10);
}
fprintf(stdout, COLOR_RESET);
fprintf(stderr, COLOR_RESET);
pthread_mutex_unlock(mutex_stdout);
}
}
void printInfo(const char *caller, bool extraInfo, char *why, ...) {
while (pthread_mutex_trylock(mutex_stdout)!=0) {
msleep(10);
}
FILE *output_ptr=stdout;
if (LOGFILE!=NULL) {
output_ptr=LOGFILE;
}
va_list arg;
va_start(arg, why);
if (extraInfo==true && PRINT_MODE==1) {
if (strlen(caller)>0) {
fprintf(output_ptr, "%s [%Lf] %s%s: ", COLOR_RESET, getElapsedTime(), HBLU, caller);
}
vfprintf(output_ptr, why, arg);
fprintf(output_ptr, COLOR_RESET);
} else if (extraInfo==false) {
if (strlen(caller)>0 && PRINT_MODE==1) {
fprintf(output_ptr, "%s [%Lf] %s%s: ", COLOR_RESET, getElapsedTime(), HGRN, caller);
vfprintf(output_ptr, why, arg);
} else if (PRINT_MODE<2){
char *whyCopy=NULL;
size_t whySize=strlen(why)+1;
mallocMacro(whyCopy, whySize+1, "printInfo error");
strlcpy(whyCopy, why, whySize);
whyCopy[0]=toupper(why[0]);
fprintf(output_ptr, HGRN);
vfprintf(output_ptr, whyCopy, arg);
tryFree(whyCopy);
}
}
fprintf(output_ptr, COLOR_RESET);
va_end(arg);
pthread_mutex_unlock(mutex_stdout);
}
void printError(const char *caller, bool extraInfo, const char *colorStr, char *why, ...) {
if ((extraInfo==true && PRINT_MODE==1) || extraInfo==false) {
va_list arg;
va_start(arg, why);
vprintError(caller, colorStr, why, arg);
va_end(arg);
}
}
void vprintError(const char *caller, const char *colorStr, char *why, va_list arg) {
while (pthread_mutex_trylock(mutex_stdout)!=0) {
msleep(10);
}
FILE *output_ptr=stderr;
if (LOGFILE!=NULL) {
output_ptr=LOGFILE;
}
if (strlen(caller)>0 && PRINT_MODE==1) {
fprintf(output_ptr, "%s [%Lf] %s%s: ", COLOR_RESET, getElapsedTime(), colorStr, caller);
vfprintf(output_ptr, why, arg);
} else {
if (strlen(caller)>0 && (PRINT_MODE<3 || (PRINT_MODE==3 && strstr(caller, "warning")==NULL))) {
char *whyCopy=NULL;
size_t whySize=strlen(why)+1;
mallocMacro(whyCopy, whySize, "vprintError error");
strlcpy(whyCopy, why, whySize);
whyCopy[0]=toupper(why[0]);
fprintf(output_ptr, "%s", colorStr);
vfprintf(output_ptr, whyCopy, arg);
fprintf(output_ptr, "%s", COLOR_RESET);
tryFree(whyCopy);
}
}
pthread_mutex_unlock(mutex_stdout);
}
void fatalError_abort(const char *caller, char *why, ...) {
va_list arg;
va_start(arg, why);
vprintError(caller, HRED, why, arg);
va_end(arg);
abort();
}
void fatalError_exit(const char *caller, char *why, ...) {
va_list arg;
va_start(arg, why);
vprintError(caller, HRED, why, arg);
va_end(arg);
exit(EXIT_FAILURE);
}
int msleep(unsigned long msec) {
struct timespec ts;
int res;
ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}
memBlock *initBlock(){
memBlock *mem = NULL;
mallocMacro(mem, sizeof(memBlock), "initBlock error");
mem->memory=NULL;
mem->size=0;
return mem;
}
void freeBlock(memBlock *mem) {
free(mem->memory);
free(mem);
}
// curl memory callback
size_t curlMemCb (void *contents, size_t size, size_t quantity, void *obj) {
size_t realSize = size * quantity;
memBlock *mem=(memBlock *) obj;
char *tempPtr=realloc(mem->memory, mem->size+realSize+1);
if (tempPtr==NULL) {
fatalError_abort("curlMemCb error: realloc error!\nError: %s\n", strerror(errno));
}
mem->memory=tempPtr;
memcpy(&(mem->memory[mem->size]), contents, realSize);
mem->size+=realSize;
mem->memory[mem->size]='\0';
return realSize;
}
// perform GET request with curl
CURLcode getRequest(struct progConfig *conf, const char *url, void *data, size_t (*func)(void *contents, size_t size, size_t quantity, void *obj)) {
CURL *curl=curl_easy_init();
char errbuf[CURL_ERROR_SIZE];
curl_easy_setopt(curl, CURLOPT_SHARE, conf->cURLshare);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, func);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 300);
curl_easy_setopt(curl, CURLOPT_MAXAGE_CONN, 30);
//curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
if (curl != NULL) {
CURLcode ret;
for (int i=1; i <= 10; i++) { // basically, DOS protection
errbuf[0]='\0';
ret=curl_easy_perform(curl);
if (ret==CURLE_OK){
curl_easy_cleanup(curl);
return ret;
} else if (ret==CURLE_COULDNT_RESOLVE_HOST) {
}
printError("getRequest warning", true, HYEL, "URL: \"%s\";\nReturned \"%s\" - sleeping for %dms\n", url, curl_easy_strerror(ret), i*2000);
msleep(i*2000);
}
printError("getRequest warning", true, HYEL, "URL: \"%s\";\nReturned %d:\n\"%s\"\n", url, ret, errbuf);
curl_easy_cleanup(curl);
return ret;
} else {
curl_easy_cleanup(curl);
printError("getRequest warning", true, HYEL, "could not init curl, pointer was NULL!\n");
return -1;
}
}
size_t dlFileCb(void *ptr, size_t size, size_t nmemb, void *stream) {
return fwrite(ptr, size, nmemb, (FILE *)stream);
}
// use curl to download file
CURLcode dlFile(progConfig *conf, const char *url, const char *fileName) {
FILE *file=fopen(fileName, "w");
if (file==NULL) {
printError("dlFile warning", true, HYEL, "could not open file: \"%s\";\nError: %s;\n", fileName, strerror(errno));
return -1;
}
CURLcode ret=getRequest(conf, url, file, dlFileCb);
fclose(file);
return ret;
}
// check if string matches regex
char **matchReg(const char *str, const char *regStr, int maxMatches) {
regex_t regComp;
regmatch_t *matchArr=NULL;
mallocMacro(matchArr, sizeof(regmatch_t)*maxMatches, "mathReg error");
if (regcomp(&regComp, regStr, REG_EXTENDED)) {
fatalError_abort("matchReg error", "could not compile reg expression: \"%s\";\nError: %s;\n", regStr, strerror(errno));
}
char **srcCopy=NULL;
if (regexec(&regComp, str, maxMatches, matchArr, 0)==0) {
int iter=0;
for (int i=1; i<=maxMatches; i++ ) {
if (matchArr[i-1].rm_so == -1)
break; // No more groups
if (srcCopy==NULL) {
srcCopy=NULL;
mallocMacro(srcCopy, sizeof(char *)*(i+1), "matchReg error");
srcCopy[0]=NULL;
} else {
char **tmp=srcCopy;
srcCopy=realloc(tmp, sizeof(char *)*(i+1));
if (srcCopy==NULL) {
fatalError_abort("matchReg error", "could not realloc srcCopy!\nError: %s;\n", strerror(errno));
}
}
srcCopy[i]=NULL;
int subStrLen=(matchArr[i-1].rm_eo-matchArr[i-1].rm_so)+1;
if (i==2) {
char *temp=NULL;
mallocMacro(temp, subStrLen, "matchReg error");
strlcpy(temp, str+matchArr[i-1].rm_so, subStrLen);
char *justFilename = basename(temp);
subStrLen=strlen(justFilename)+1;
srcCopy[i]=NULL;
mallocMacro(srcCopy[i], subStrLen, "matchReg error");
strlcpy(srcCopy[i], justFilename, subStrLen);
free(temp);
} else {
srcCopy[i]=NULL;
mallocMacro(srcCopy[i], subStrLen, "matchReg error");
strlcpy(srcCopy[i], str+matchArr[i-1].rm_so, subStrLen);
}
iter=i;
}
size_t iterSize=intSize(iter)+1;
char *tempBuff=NULL;
mallocMacro(tempBuff, iterSize, "matchReg error");
tempBuff[0]='\0';
snprintf(tempBuff, iterSize, "%d", iter);
srcCopy[0]=NULL;
mallocMacro(srcCopy[0], iterSize, "matchReg error");
strlcpy(srcCopy[0], tempBuff, iterSize);
tryFree(tempBuff);
}
regfree(&regComp);
tryFree(matchArr);
return srcCopy;
}
// int to string
void intToStr(char *buff, int num) {
if (buff==NULL) {
fatalError_abort("intToStr error", "failed because '*buff' is NULL\n");
}
size_t size=intSize(num);
char *tempBuff=NULL;
mallocMacro(tempBuff, size+1, "intToStr error");
tempBuff[0]='\0';
snprintf(tempBuff, size+1, "%d", num);
strlcpy(buff, tempBuff, size+1);
tryFree(tempBuff);
}
// read integer from string
int parseStrToInt(const char *str) {
if (str==NULL){
fatalError_abort("parseStrToInt error", "could not convert to int, string is NULL!\n");
}
errno=0;
char *end = NULL;
long value = strtol(str, &end, 10);
if (end == str || '\0' != *end || 0 != errno) {
fatalError_abort("parseStrToInt error", "error converting \"%s\" to int!\nError: %s;\n", str, strerror(errno));
return -1;
} else {
return value;
}
}
// read double from string
double parseStrToDouble(const char *str) {
if (str==NULL){
fatalError_abort("parseStrToDouble error", "could not convert to double, string is NULL!\n");
}
errno=0;
char *end = NULL;
double value = strtod(str, &end);
if (end == str || '\0' != *end || 0 != errno) {
fatalError_abort("parseStrToDouble error", "error converting \"%s\" to double!\nError: %s;\n", str, strerror(errno));
return -1;
} else {
return value;
}
}
// free string array
void freeStrArr(char **str) {
if (str!=NULL){
if (str[0]!=NULL){
int val = parseStrToInt(str[0]);
for (int i=0; i<=val; i++){
free(str[i]);
}
}
free(str);
}
}
// remove extension from string
char *removeExtension(const char *str) {
size_t size=strlen(str);
char *newStr=NULL;
mallocMacro(newStr, size+1, "removeExtension error");
strlcpy(newStr, str, size+1);
char *end = newStr + size;
while (end > newStr && *end != '.' && *end != '\\' && *end != '/') {
--end;
}
if ((end > newStr && *end == '.') && (*(end - 1) != '\\' && *(end - 1) != '/')) {
*end = '\0';
}
return newStr;
}
// return extension from string
char *getExtension(const char *str) {
char *dotPos=strrchr(str, '.');
char *newStr=NULL;
if (dotPos!=NULL) {
size_t size=strlen(dotPos);
mallocMacro(newStr, size+1, "getExtension error");
newStr[0]='\0';
if ((*(dotPos + size - 1) != '\\' && *(dotPos + size - 1) != '/')) {
strlcpy(newStr, dotPos+1, size);
}
} else {
printError("getExtension error", true, HRED, "could not get extension of \"%s\"\n", str);
}
return newStr;
}
// replace all occurences of oldStr with newStr in str
char *replaceAll(char *str, const char *oldStr, const char *newStr) {
if (str==NULL || oldStr==NULL) {
return NULL;
}
size_t oldStrSize=strlen(oldStr);
if (oldStrSize==0) {
return NULL;
}
if (newStr==NULL) {
newStr = "";
}
size_t newStrSize=strlen(newStr);
char *temp1=str, *temp2=NULL;
int counter=0;
for (; (temp2=strstr(temp1, oldStr)); ++counter) {
temp1=temp2+oldStrSize;
}
size_t newSize=strlen(str)+(newStrSize-oldStrSize)*counter+1;
char *resStr = temp2 = malloc(newSize);
if (resStr==NULL || temp2==NULL) {
fatalError_abort("replaceAll error", "could not malloc;\nError: %s;\n", strerror(errno));
}
while (counter--) {
temp1=strstr(str, oldStr);
int diffSize=temp1-str;
strlcpy(temp2, str, diffSize+1);
temp2+=diffSize;
strlcpy(temp2, newStr, newStrSize+1);
temp2+=newStrSize;
str+=diffSize+oldStrSize;
}
strlcpy(temp2, str, newSize);
return resStr;
}
void tryFree(void *ptr){
if (ptr!=NULL){
free(ptr);
ptr=NULL;
}
}
// use mmap to read file to memory
char *fileToMem(const char *filePath) {
int file = open(filePath, O_RDONLY);
if (file < 0 ) {
fatalError_abort("fileToMem error", "could not open: \"%s\";\nError: %s;\n", filePath, strerror(errno));
}
struct stat fileProp;
if (fstat(file, &fileProp)==-1) {
fatalError_abort("fileToMem error", "could not get filesize of: \"%s\";\nError: %s;\n", filePath, strerror(errno));
}
size_t fileSize=fileProp.st_size;
char *fileMap=NULL;
if (fileSize>0) {
fileMap=mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE, file, 0);
if (fileMap==MAP_FAILED) {
fatalError_abort("fileToMem error", "could not use 'mmap' on file: \"%s\";\nError: %s;\n", filePath, strerror(errno));
}
}
return fileMap;
}
int freeFileMem(const char *filePath, char *fileStr) {
struct stat fileProp;
if (stat(filePath, &fileProp)==-1) {
fatalError_abort("freeFileMem error", "could not get filesize of: \"%s\";\nError: %s;\n", filePath, strerror(errno));
}
size_t fileSize=fileProp.st_size;
int ret = munmap(fileStr, fileSize);
if ( ret == -1){
fatalError_abort("freeFileMem error", "could not use 'munmap' on file: \"%s\";\nError: %s;\n", filePath, strerror(errno));
}
return ret;
}
// get number of digits in number
size_t intSize(size_t num) { // literally fastest way to get digits, see stackoverflow
if (num >= 100000000000000) return 15;
if (num >= 10000000000000) return 14;
if (num >= 1000000000000) return 13;
if (num >= 100000000000) return 12;
if (num >= 10000000000) return 11;
if (num >= 1000000000) return 10;
if (num >= 100000000) return 9;
if (num >= 10000000) return 8;
if (num >= 1000000) return 7;
if (num >= 100000) return 6;
if (num >= 10000) return 5;
if (num >= 1000) return 4;
if (num >= 100) return 3;
if (num >= 10) return 2;
return 1;
}
// calculate relative path from fromPath to toPath
char *getRelativePath(const char *fromPath, const char *toPath) {
char *relPath=malloc(FILENAME_MAX+1);
size_t fromPathSize=strlen(fromPath);
if (fromPath[fromPathSize-1]!='/') {
char *fromPathCopy=NULL;
mallocMacro(fromPathCopy, fromPathSize, "getRelativePath error");
snprintf(fromPathCopy, fromPathSize, "%s", fromPath);
cwk_path_get_relative(dirname(fromPathCopy), toPath, relPath, FILENAME_MAX);
tryFree(fromPathCopy);
} else {
cwk_path_get_relative(fromPath, toPath, relPath, FILENAME_MAX);
}
return relPath;
}
// check if folder exists, otherwise basically "mkdir -p" - REQUIRES forward slash on folder paths
int checkFolder(const char *filePath, bool runMKDIR) {
size_t pathSize=strlen(filePath)+1;
char *path=NULL;
mallocMacro(path, pathSize, "checkFolder error");
strlcpy(path, filePath, pathSize);
if (path[strlen(path)-1]!='/') { // if given filePath is not of an actual directory
path=dirname(path);
}
struct stat statBuff;
int ret=stat(path, &statBuff);
if (ret==-1) {
if (errno==ENOENT && runMKDIR==true) {
if (mkdir(path, 0755)!=0 && errno!=EEXIST) {
if (errno==ENOENT) {
path=dirname(path);
char *tempStr=NULL;
mallocMacro(tempStr, strlen(path)+2, "checkFolder error");
snprintf(tempStr, strlen(path)+2, "%s/", path);
if (checkFolder(tempStr, true)==0 && checkFolder(filePath, true)==0) {
} else {
tryFree(tempStr);
fatalError_abort("checkFolder error", "could not create folder \"%s\";\nError: %s;\n", path, strerror(errno));
}
tryFree(tempStr);
} else {
fatalError_abort("checkFolder error", "could not create folder \"%s\";\nError: %s;\n", path, strerror(errno));
}
}
} else if (errno!=EEXIST && errno!=EISDIR) {
tryFree(path);
return -1;
}
}
tryFree(path);
return 0;
}
// generate image with text label
char *genImage(char *cmd, char *filePath, char *imgLabel) {
int ret=checkFolder(filePath, true);
char *retImg=NULL;
if (ret==0) {
char *fileName=randStr(16);
size_t cmdSize=strlen(filePath)+strlen(fileName)+6; // 6=length of ".png" + padding
char *fullFilePath=NULL;
mallocMacro(fullFilePath, cmdSize, "genImage error");
snprintf(fullFilePath, cmdSize, "%s%s.png", filePath, fileName);
cmdSize+=strlen(cmd)+strlen(imgLabel)+4;
char *cmdStr=NULL;
mallocMacro(cmdStr, cmdSize, "genImage error");
snprintf(cmdStr, cmdSize, "%s\"%s\" %s", cmd, imgLabel, fullFilePath);
resetSTDColors();
FILE *imgMag=popen(cmdStr, "r");
if (imgMag!=NULL) {
retImg=fullFilePath;
} else {
printError("genImage warning", true, HYEL, "could not run \"%s\";\nError: %s;\n", cmdStr, strerror(errno));
tryFree(fullFilePath);
}
tryFree(fileName);
if (pclose(imgMag)!=0) {
printError("", false, HRED, "%s\n", strerror(errno));
printError("genImage warning", true, HYEL, "error while running \"%s\";\nError: %s;\n", cmdStr, strerror(errno));
}
tryFree(cmdStr);
}
return retImg;
}
void curlLock(CURL *handle, curl_lock_data data, curl_lock_access laccess, void *userptr) {
while (pthread_mutex_trylock((pthread_mutex_t *) userptr)!=0) {
msleep(100);
}
}
void curlUnlock(CURL *handle, curl_lock_data data, void *userptr) {
pthread_mutex_unlock((pthread_mutex_t *) userptr);
}
// returns string of random characters
char *randStr(size_t size) {
const char dict[62]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
char *str=NULL;
mallocMacro(str, size+1, "randStr error");
for (size_t i=0; i<size; i++) {
str[i]=dict[rand()%62];
}
str[size]='\0';
return str;
}
// finds subtitles for fileStr in filePath
char *getSubs(progConfig *conf, char *fileStr, char *filePath) {
char *epSubs=NULL;
char *fileName=removeExtension(fileStr);
fileList *subs=find(conf, filePath, fileName, FI_MODE, false);
for (fileList *tempSub=subs; tempSub!=NULL; tempSub=tempSub->next) {
if (tempSub->dataSize>2) {
tryFree(fileName);
fileName=removeExtension(tempSub->data[2]);
char *tempExtension=getExtension(tempSub->data[2]);
if (tempExtension==NULL) {
continue;
}
if (strcmp(tempExtension, subExt1)==0) { // if file is srt
char *folderPath=tempSub->data[1];
size_t tempStrSize=strlen(folderPath)+strlen(fileName)+strlen(subExt2)+strlen(".")+2;
char *tempStr=NULL;
mallocMacro(tempStr, tempStrSize, "getSubs error");
tempStr[0]='\0';
//check if folder has /
if (folderPath[strlen(folderPath)-1]=='/') {
snprintf(tempStr, tempStrSize, "%s%s.%s", folderPath, fileName, subExt2);
} else {
snprintf(tempStr, tempStrSize, "%s/%s.%s", folderPath, fileName, subExt2);
}
if (access(tempStr, F_OK)!=0) { // file doesn't already exist, so go ahead and convert srt to vtt
char *ffmpegCmd="ffmpeg -loglevel fatal -y -nostdin -i";
size_t cmdStrSize=strlen(ffmpegCmd)+strlen(" \"\" \"\"")+strlen(tempSub->data[0])+tempStrSize+1;
char *cmdStr=NULL;
mallocMacro(cmdStr, cmdStrSize, "getSubs error");
cmdStr[0]='\0';
snprintf(cmdStr, cmdStrSize, "%s \"%s\" \"%s\"", ffmpegCmd, tempSub->data[0], tempStr);
resetSTDColors();
FILE *cmdRet=popen(cmdStr, "r");
if (cmdRet==NULL) {
printError("getSubs warning", true, HYEL, "running \"%s %s %s%s.%s\" failed;\nErrno is %d \"%s\"", ffmpegCmd, tempSub->data[0], folderPath, fileName, subExt2, errno, strerror(errno));
} else { // Conversion worked!
char *subLangFound=strrchr(fileName, '_');
char *subLang=NULL;
if (subLangFound==NULL){
subLang=NULL;
mallocMacro(subLang, 4, "getSubs error");
strlcpy(subLang, "_en", 4);
} else {
subLang=subLangFound;
}
size_t sizeOfJSONStr=strlen("{\"subFile\":\"\",\"lang\":\"\"}")+strlen(subLang)+tempStrSize+2;
char *tempJSONStr=NULL;
mallocMacro(tempJSONStr, sizeOfJSONStr, "getSubs error");
tempJSONStr[0]='\0';
if (epSubs!=NULL) {
snprintf(tempJSONStr, sizeOfJSONStr, ",{\"subFile\":\"%s\",\"lang\":\"%s\"}", tempStr, subLang+1);
size_t newSize=strlen(epSubs)+sizeOfJSONStr+1;
epSubs=realloc(epSubs, newSize);
if (epSubs==NULL)
fatalError_abort("getSubs error: could not realloc;\nError: %s;\n", strerror(errno));
strlcat(epSubs, tempJSONStr, newSize);
} else {
snprintf(tempJSONStr, sizeOfJSONStr, "{\"subFile\":\"%s\",\"lang\":\"%s\"}", tempStr, subLang+1);
epSubs=NULL;
mallocMacro(epSubs, sizeOfJSONStr, "getSubs error");
strlcpy(epSubs, tempJSONStr, sizeOfJSONStr);
}
if (subLangFound==NULL) {
tryFree(subLang);
}
tryFree(tempJSONStr);
}
if (pclose(cmdRet)!=0) {
printError("getSubs error", false, HRED, "error occured whilst running pclose on \"%s\";\n", cmdStr);
}
tryFree(cmdStr);
}
tryFree(tempStr);
} else if (strcmp(tempExtension, subExt2)==0) { // if file is vtt & not already in DB
char *subLangFound=strrchr(fileName, '_');
char *subLang=NULL;
if (subLangFound==NULL){
subLang=NULL;
mallocMacro(subLang, 4, "getSubs error");
strlcpy(subLang, "_en", 4);
} else {
subLang=subLangFound;
}
size_t sizeOfJSONStr=strlen("{\"subFile\":\"\",\"lang\":\"\"}")+strlen(subLang)+strlen(tempSub->data[0])+2;
char *tempJSONStr=NULL;
mallocMacro(tempJSONStr, sizeOfJSONStr, "getSubs error");
tempJSONStr[0]='\0';
if (epSubs!=NULL) {
snprintf(tempJSONStr, sizeOfJSONStr, ",{\"subFile\":\"%s\",\"lang\":\"%s\"}", tempSub->data[0], subLang+1);
size_t newSize=strlen(epSubs)+sizeOfJSONStr+1;
epSubs=realloc(epSubs, newSize);
if (epSubs==NULL)
fatalError_abort("getSubs error: could not realloc;\nError: %s;\n", strerror(errno));
strlcat(epSubs, tempJSONStr, newSize);
} else {
snprintf(tempJSONStr, sizeOfJSONStr, "{\"subFile\":\"%s\",\"lang\":\"%s\"}", tempSub->data[0], subLang+1);
epSubs=NULL;
mallocMacro(epSubs, sizeOfJSONStr, "getSubs error");
strlcpy(epSubs, tempJSONStr, sizeOfJSONStr);
}
if (subLangFound==NULL) {
tryFree(subLang);
}
tryFree(tempJSONStr);
}
tryFree(tempExtension);
}
}
freeList(subs);
tryFree(fileName);
return epSubs;
}
int getTmdbID(char *URLStr, progConfig *conf) {
int tmdbID=0;
memBlock *mem=initBlock();
getRequest(conf, URLStr, mem, curlMemCb);
cJSON *json_root=cJSON_Parse(mem->memory);
if (json_root!=NULL) {
cJSON *json_totRes=cJSON_DetachItemFromObject(json_root, "total_results");
if (json_totRes!=NULL) {
if (cJSON_GetNumberValue(json_totRes)>0) {
cJSON *json_item=cJSON_DetachItemFromObject(json_root, "results");
cJSON *json_obj=cJSON_DetachItemFromArray(json_item, 0);
cJSON *json=cJSON_DetachItemFromObject(json_obj, "id");
tmdbID=cJSON_GetNumberValue(json);
cJSON_Delete(json);
cJSON_Delete(json_obj);
cJSON_Delete(json_item);
}
} else {
printError("getTmdbID warning", true, HYEL, "request error, URL: '%s';\njson_totRes==NULL - json_root was:\n", URLStr);
char *tempStr=cJSON_Print(json_root);
printError("", true, COLOR_RESET, tempStr);
printError("", true, HYEL, "\nEND;\n");
tryFree(tempStr);
}
cJSON_Delete(json_totRes);
} else {
printError("getTmdbID warning", true, HYEL, "request error, URL: '%s';\njson_root==NULL\n", URLStr);
}
tryFree(URLStr);
cJSON_Delete(json_root);
freeBlock(mem);
return tmdbID;
}
char *getPoster(const char *posterURL, progConfig *conf, int prefImgWidth, double prefImgRatio, char *prefImgLang) {
char *imgURL=NULL;
memBlock *mem=initBlock();
getRequest(conf, posterURL, mem, curlMemCb);
cJSON *json_root=cJSON_Parse(mem->memory);
if (json_root!=NULL) {
cJSON *json_posters=cJSON_DetachItemFromObject(json_root, "posters");
if (json_posters!=NULL){
for (int j=0; j<cJSON_GetArraySize(json_posters) && imgURL==NULL; j++) { // loop through all & check width & check ratio
cJSON *item=cJSON_DetachItemFromArray(json_posters, j);
if (item!=NULL) {
cJSON *width=cJSON_DetachItemFromObject(item, "width");
cJSON *ratio=cJSON_DetachItemFromObject(item, "aspect_ratio");
cJSON *lang=cJSON_DetachItemFromObject(item, "iso_639_1");
if ((width!=NULL && cJSON_GetNumberValue(width)==prefImgWidth) || (ratio!=NULL && cJSON_GetNumberValue(ratio)==prefImgRatio)) {
if (lang!=NULL && cJSON_GetStringValue(lang)!=NULL && strcmp(cJSON_GetStringValue(lang), prefImgLang)==0) {
cJSON *imgStr=cJSON_DetachItemFromObject(item, "file_path");
if (imgStr!=NULL && cJSON_GetStringValue(imgStr)!=NULL) {
size_t urlLen=strlen(tmdbImg)+strlen(cJSON_GetStringValue(imgStr))+1;
imgURL=NULL;
mallocMacro(imgURL, urlLen, "getPoster error");
imgURL[0]='\0';
snprintf(imgURL, urlLen, "%s%s", tmdbImg, cJSON_GetStringValue(imgStr));
}
cJSON_Delete(imgStr);
}
cJSON_Delete(width);
cJSON_Delete(ratio);
cJSON_Delete(lang);
}
} else {
printError("getPoster warning", true, HYEL, "request error, URL: '%s';\nitem==NULL - json_posters was:\n", posterURL);
char *tempStr=cJSON_Print(json_posters);
printError("", true, COLOR_RESET, tempStr);
printError("", true, HYEL, "\nEND;\n");
tryFree(tempStr);
}
cJSON_Delete(item);
}
if (imgURL==NULL) {
printError("getPoster warning", true, HYEL, "request error, URL: '%s';\nitem==NULL - json_posters was:\n", posterURL);
char *tempStr=cJSON_Print(json_posters);
printError("", true, COLOR_RESET, tempStr);
printError("", true, HYEL, "\nEND;\n");
tryFree(tempStr);
}
cJSON_Delete(json_posters);
} else {
printError("getPoster warning", true, HYEL, "request error, URL: '%s';\njson_posters==NULL - json_root was:\n", posterURL);
char *tempStr=cJSON_Print(json_root);
printError("", true, COLOR_RESET, tempStr);
printError("", true, HYEL, "\nEND;\n");
tryFree(tempStr);
}
cJSON_Delete(json_root);
} else {
printError("getPoster warning", true, HYEL, "request error, URL: '%s';\njson_root==NULL\n", posterURL);
}
freeBlock(mem);
return imgURL;
}
char *compressImg(const char *convCmd, char *fileToConvert, bool overwrite) {
char *outputFile=NULL;
if (overwrite) {
outputFile=fileToConvert;
} else {
char *fileExt=getExtension(fileToConvert);
char *filePath=dirname(fileToConvert);
size_t fileNameSize=strlen(filePath)+1+16+strlen(fileExt)+1;
mallocMacro(outputFile, fileNameSize, "compressImg error");
char *randomString=randStr(16);
snprintf(outputFile, fileNameSize, "%s/%s.%s", filePath, randomString, fileExt);
tryFree(randomString);
tryFree(fileExt);
}
size_t cmdStrSize=strlen(convCmd)+strlen(fileToConvert)+strlen(outputFile)+4; // NULL+spaces
char *cmdStr=NULL;
mallocMacro(cmdStr, cmdStrSize, "compressImg error");
snprintf(cmdStr, cmdStrSize, "%s %s %s", convCmd, fileToConvert, outputFile);
resetSTDColors();
FILE *cmdRet=popen(cmdStr, "r");
if (cmdRet==NULL) {
printError("compressImg warning", true, HYEL, "running \"%s %s %s\" failed;\nErrno is %d \"%s\"", convCmd, fileToConvert, outputFile, errno, strerror(errno));
if (outputFile!=fileToConvert) {
tryFree(outputFile);
}
outputFile=NULL;
} else { // Conversion worked!
}
if (pclose(cmdRet)!=0) {
printError("compressImg error", false, HRED, "error occured whilst running pclose on \"%s\";\n", cmdStr);
}
tryFree(cmdStr);
return outputFile;
}
// helper funtion for printBitFlags
void printBits(unsigned bits) {
if (bits>1) {
printBits(bits/2);
}
printf("%u", bits%2);
}
void printBitFlags(unsigned bits) {
printf("bitflag is: \t0b");
printBits(bits);
printf(";\n");
}
int fixMode(progConfig *conf, progFlags flags, const char *toFix, const char *id, const char *poster, const char *newName, bool refreshMode) {
cJSON *DBptr=NULL;
const char *dbStr=NULL, *dbPath=NULL;
if (flags & MOVIES_MODE) {
DBptr=conf->JSON_moDB;
dbStr="Movie";
dbPath=conf->dbNameMovie;
} else if (flags & SHOWS_MODE) {
DBptr=conf->JSON_tvDB;
dbStr="Show";
dbPath=conf->dbNameTV;
}
if (DBptr!=NULL) {
cJSON *element=NULL;
cJSON_ArrayForEach(element, DBptr) { // let's check every element of database
cJSON *this_name=cJSON_GetObjectItem(element, dbStr);
if (strcmp(cJSON_GetStringValue(this_name), toFix)==0) { // it's a match!
cJSON *this_id=cJSON_GetObjectItem(element, "ID");
cJSON *this_poster=cJSON_GetObjectItem(element, "Poster");
if (id!=NULL) {
printInfo("fixMode info", false, "setting id for '%s' from '%s' to '%s';\n", toFix, cJSON_GetStringValue(this_id), id);
cJSON_SetValuestring(this_id, id);
} else {
id=cJSON_GetStringValue(this_id);
}
if (newName!=NULL) {
printInfo("fixMode info", false, "setting name of '%s' to '%s';\n", toFix, newName);
cJSON_SetValuestring(this_name, newName);
}
if (poster!=NULL) {
printInfo("fixMode info", false, "changing poster of '%s' from '%s' to '%s';\n", toFix, cJSON_GetStringValue(this_poster), poster);
cJSON_SetValuestring(this_poster, poster);
} else {
if (refreshMode && (flags & FIX_POSTER_MODE)) {
const char *IDptr=cJSON_GetStringValue(this_id);
if (id!=NULL) {
IDptr=id;
}
int tempID=parseStrToInt(IDptr);
if (tempID>0) {
if ((flags & MOVIES_MODE) && conf->getMposter) {
printInfo("fixMode info", false, "fetching poster for '%s';\n", toFix);
poster=getMoviePoster(conf, tempID);
} else if ((flags & SHOWS_MODE) && conf->getTVposter) {
printInfo("fixMode info", false, "fetching poster for '%s';\n", toFix);
poster=getShowPoster(conf, tempID);
}
if (poster==NULL) {
poster="";
}
printInfo("fixMode info", false, "changing poster of '%s' from '%s' to '%s';\n", toFix, cJSON_GetStringValue(this_poster), poster);
cJSON_SetValuestring(this_poster, poster);
}
}
}
if ((flags & SHOWS_MODE) && conf->getEpisodeName && refreshMode) {
int tempID=parseStrToInt(id);
cJSON *this_episodes=cJSON_GetObjectItem(element, "Episodes");
cJSON *episode=NULL;
printInfo("fixMode info", false, "refreshing episode titles of '%s'...\n", cJSON_GetStringValue(this_name));
cJSON_ArrayForEach(episode, this_episodes) {
cJSON *this_episodeTitle=cJSON_GetObjectItem(episode, "Title");
char *seNum=cJSON_GetStringValue(cJSON_GetObjectItem(episode, "Season"));
char *epNum=cJSON_GetStringValue(cJSON_GetObjectItem(episode, "Episode"));
char *thisEpisodeName=getEpisodeName(conf, tempID, seNum, epNum, conf->TMDBapi);
if (thisEpisodeName!=NULL) {
cJSON_SetValuestring(this_episodeTitle, thisEpisodeName);
tryFree(thisEpisodeName);
}
}
}
char *json=cJSON_Print(DBptr);
writeCharToFile(json, dbPath);
printInfo("fixMode info", false,"fixed '%s' in '%s'.\n", toFix, dbPath);
tryFree(json);
return 0;
}
}
} else {
fatalError_exit("fixMode error", "No database to fix!\n");
}
return -1; // didn't find anything to fix
}
int writeCharToFile(const char *str, const char *fileStr) {
FILE *filePtr = fopen(fileStr, "w");
if (filePtr != NULL) {
fputs(str, filePtr);
fclose(filePtr);
} else {
fatalError_abort("writeCharToFile error", "could not open '%s';\nErrno: %s;\n", fileStr, strerror(errno));
}
return 0;
}
long double getElapsedTime() {
struct timeval currentTime;
gettimeofday(&currentTime, NULL);
return (currentTime.tv_sec - timeProgStart.tv_sec)+((long double)(currentTime.tv_usec - timeProgStart.tv_usec)/1000000);
}

@ -0,0 +1,142 @@
#pragma once
#include <curl/curl.h>
#include <stdint.h>
#include "conf.h"
#include "main.h"
#define tmdbSite "https://api.themoviedb.org/3/"
#define tmdbP "/images?api_key="
#define tmdbP_Opts "&include_image_language=null"
#define tmdbM "movie/"
#define tmdbM_ID "https://api.themoviedb.org/3/search/movie?page=1&api_key=" // blah&query=name +opts
#define tmdbM_Opts "&include_adult=false&language=en-US"
#define tmdbTV "tv/"
#define tmdbTV_ID "https://api.themoviedb.org/3/search/tv?page=1&query=" // name&api_key=blah +opts
#define tmdbTV_Opts "&language=en" //to find the ID based on name
#define tmdbImg "https://image.tmdb.org/t/p/original"
#define videoExt "mp4"
#define subExt1 "srt"
#define subExt2 "vtt"
#define mallocMacro(var, size, caller) do {var=malloc(size); if(var==NULL){fatalError_abort(caller, "could not malloc;\nError: %s;\n", strerror(errno));}}while(0)
//Regular text
#define BLK "\033[0;30m"
#define RED "\033[0;31m"
#define GRN "\033[0;32m"
#define YEL "\033[0;33m"
#define BLU "\033[0;34m"
#define MAG "\033[0;35m"
#define CYN "\033[0;36m"
#define WHT "\033[0;37m"
//Regular bold text
#define BBLK "\033[1;30m"
#define BRED "\033[1;31m"
#define BGRN "\033[1;32m"
#define BYEL "\033[1;33m"
#define BBLU "\033[1;34m"
#define BMAG "\033[1;35m"
#define BCYN "\033[1;36m"
#define BWHT "\033[1;37m"
//Regular underline text
#define UBLK "\033[4;30m"
#define URED "\033[4;31m"
#define UGRN "\033[4;32m"
#define UYEL "\033[4;33m"
#define UBLU "\033[4;34m"
#define UMAG "\033[4;35m"
#define UCYN "\033[4;36m"
#define UWHT "\033[4;37m"
//Regular background
#define BLKB "\033[40m"
#define REDB "\033[41m"
#define GRNB "\033[42m"
#define YELB "\033[43m"
#define BLUB "\033[44m"
#define MAGB "\033[45m"
#define CYNB "\033[46m"
#define WHTB "\033[47m"
//High intensty background
#define BLKHB "\033[0;100m"
#define REDHB "\033[0;101m"
#define GRNHB "\033[0;102m"
#define YELHB "\033[0;103m"
#define BLUHB "\033[0;104m"
#define MAGHB "\033[0;105m"
#define CYNHB "\033[0;106m"
#define WHTHB "\033[0;107m"
//High intensty text
#define HBLK "\033[0;90m"
#define HRED "\033[0;91m"
#define HGRN "\033[0;92m"
#define HYEL "\033[0;93m"
#define HBLU "\033[0;94m"
#define HMAG "\033[0;95m"
#define HCYN "\033[0;96m"
#define HWHT "\033[0;97m"
//Bold high intensity text
#define BHBLK "\033[1;90m"
#define BHRED "\033[1;91m"
#define BHGRN "\033[1;92m"
#define BHYEL "\033[1;93m"
#define BHBLU "\033[1;94m"
#define BHMAG "\033[1;95m"
#define BHCYN "\033[1;96m"
#define BHWHT "\033[1;97m"
//Reset
#define COLOR_RESET "\033[0m"
typedef struct memBlock {
char *memory;
size_t size;
} memBlock;
void resetSTDColors();
void printInfo(const char *caller, bool extraInfo, char *why, ...);
void printError(const char *caller, bool extraInfo, const char *colorStr, char *why, ...);
void vprintError(const char *caller, const char *colorStr, char *why, va_list arg);
void fatalError_abort(const char *caller, char *why, ...);
void fatalError_exit(const char *caller, char *why, ...);
int msleep(unsigned long msec);
size_t curlMemCb (void *contents, size_t size, size_t quantity, void *obj);
memBlock *initBlock();
void freeBlock(memBlock *mem);
size_t curlMemCb (void *contents, size_t size, size_t quantity, void *obj);
CURLcode getRequest(progConfig *conf, const char *url, void *data, size_t (*func)(void *contents, size_t size, size_t quantity, void *obj));
size_t dlFileCb(void *ptr, size_t size, size_t nmemb, void *stream);
CURLcode dlFile(progConfig *conf, const char *url, const char *fileName);
char **matchReg(const char *str, const char *regStr, int maxMatches);
int parseStrToInt(const char *str);
double parseStrToDouble(const char *str);
void intToStr(char *buff, int num);
void freeStrArr(char **str);
char *removeExtension(const char *str);
char *getExtension(const char *str);
char *replaceAll(char *str, const char *oldStr, const char *newStr);
void tryFree(void *ptr);
char *fileToMem(const char *filePath);
int freeFileMem(const char *filePath, char *fileStr);
size_t intSize(size_t num);
int isSymlink(const char *path);
char *getRelativePath(const char *fromPath, const char *toPath);
int checkFolder(const char *filePath, bool runMKDIR);
char *genImage(char *cmd, char *filePath, char *imgLabel);
void curlLock(CURL *handle, curl_lock_data data, curl_lock_access laccess, void *userptr);
void curlUnlock(CURL *handle, curl_lock_data data, void *userptr);
char *randStr(size_t size);
char *getSubs(progConfig *conf, char *fileStr, char *filePath);
int getTmdbID(char *URLStr, progConfig *conf);
char *getPoster(const char *posterURL, progConfig *conf, int prefImgWidth, double prefImgRatio, char *prefImgLang);
char *compressImg(const char *convCmd, char *fileToConvert, bool overwrite);
void printBits(unsigned bits);
void printBitFlags(unsigned bits);
int fixMode(progConfig *conf, progFlags flags, const char *toFix, const char *id, const char *poster, const char *newName, bool refreshMode);
int writeCharToFile(const char *str, const char *fileStr);
long double getElapsedTime();
Loading…
Cancel
Save